1st Yr - ch-3-1
1st Yr - ch-3-1
1st Yr - ch-3-1
INTRODUCTION TO C
Q. What is C?
Ans: C is a general-purpose, procedural programming language that is ideal for software
developing firmware or portable applications. Originally intended to write system software,
embedded systems. It was developed in the early 1970s by Dennis Ritchie at (AT & T’s) Bell
Labs. It is one of the most widely used programming languages and has influenced many
other modern languages such as C++, C#, Java, and Python. This language is derived from B
so it is known as C.
SIGNIFICANT FEATURES OF C
1. Low-level Language:
C provides access to low-level memory and system resources, making it close to
assembly language. It’s often used for system programming (e.g., operating systems,
embedded systems).
2. Portable:
Programs written in C can be compiled and run on different machines with minimal
or no changes, making C highly portable.
3. Structured:
C allows you to break down programs into smaller, reusable functions. This makes it
easier to organize and manage large programs.
4. Efficient:
C is a fast language because it provides direct access to memory through pointers
and allows for low-level operations, leading to highly efficient code execution.
5. Rich Library Support:
C has a wide array of built-in functions provided by libraries, particularly the standard
library (<stdio.h>, <math.h>, etc.), that help with tasks such as I/O operations, math,
and string manipulation.
6. Procedural Language:
C follows a procedural paradigm, which means the program is divided into functions
that operate on data rather than objects, as seen in object-oriented languages.
7. Small and Simple Language:
The core language of C is small, but it provides powerful features such as pointers,
memory management, and bitwise operations.
Q. Why Learn C?
1. Foundation Language: C forms the basis for understanding many modern
programming languages like C++, Java, and Python.
2. System-Level Programming: If you want to work with operating systems, drivers, or
embedded systems, C is an essential language.
3. Efficiency: C gives programmers control over hardware, which is crucial in
performance-critical applications.
What are the characteristics of C programming Language.
The C programming language has several important characteristics that make it one of the
most widely used and influential programming languages in history. Below are the key
characteristics of C:
1. Simple and Efficient:
C has a small set of keywords and basic constructs, making it easy to understand and
use. Programs written in C are highly efficient in terms of both memory usage and
execution speed, as it allows for direct manipulation of hardware and memory.
2. Portable:
C is highly portable, meaning code written on one system can be compiled and run
on another system with minimal modifications. This portability makes it ideal for
cross-platform development.
3. Structured Language:
C supports structured programming through the use of functions and blocks, which
makes programs easier to understand, debug, and modify. You can break a program
into smaller modules or functions, which promotes reusability and readability.
4. Low-level Language:
C provides access to low-level memory and hardware manipulation through the use
of pointers and direct memory access, making it suitable for system-level
programming like operating systems, device drivers, and embedded systems.
5. Rich Library Support:
C has a vast collection of built-in libraries, especially in the standard library (e.g.,
<stdio.h>, <stdlib.h>, <string.h>, etc.), which provides functions for input/output,
memory management, string handling, and other common operations.
6. Fast Execution:
C compiles to machine-level code, allowing programs to run faster compared to
other high-level languages like Python or Java, which rely on interpreters or virtual
machines.
7. Supports Pointers:
One of C's unique features is its use of pointers, which allow direct manipulation of
memory addresses. Pointers provide powerful capabilities for memory management,
dynamic memory allocation, and handling arrays and structures efficiently.
8. Extensibility:
C is an extensible language, meaning that you can easily add new features or
functions. You can define your own data types, functions, and libraries, making the
language versatile for various applications.
9. Memory Management:
C provides manual memory management features, allowing programmers to allocate
and free memory dynamically using functions like malloc(), calloc(), and free().
10. Middle-level Language:
C is often referred to as a middle-level language because it combines features of both
high-level and low-level languages. It provides abstraction through functions and
user-defined types but also gives direct access to system resources like memory.
11. Recursion:
C supports recursive functions, allowing functions to call themselves, which is useful
for solving problems that can be divided into similar sub-problems, such as tree
traversals or factorial calculation.
12. Modularity:
C encourages breaking programs into smaller, self-contained functions or modules,
promoting code reusability and better organization.
13. Wide Application:
C is used in a wide range of applications, including operating systems (e.g., Linux),
embedded systems, database management systems (e.g., MySQL), compilers, and
graphical interfaces.
14. Operator Rich:
C supports a variety of operators, including arithmetic, relational, logical, bitwise, and
assignment operators. This provides great flexibility in performing various operations
on data.
15. Preprocessor Directives:
C has a powerful preprocessor that allows for macros, file inclusion, conditional
compilation, and more. This helps in code organization and portability.
16. Function-Rich:
C supports a wide range of built-in functions in the standard library and allows the
creation of user-defined functions to perform specific tasks, facilitating code reuse
and modularity.
Applications of C:
Operating Systems: Many operating systems, including Linux and Unix, are written in
C.
Embedded Systems: Due to its efficiency and ability to directly manipulate hardware,
C is widely used in embedded systems.
Compilers and Interpreters: Many programming language compilers and interpreters
are written in C.
Database Systems: Popular database systems like MySQL are developed in C.
Graphics and Game Development: C is used in high-performance software such as
game engines and 3D graphics.
BASIC STRUCTURE OF C
INCLUDE SECTION
GLOBAL DECLARATION(optional)
FUNCTION PROTOTYPE(optional)
MAIN FUNCTION()
{
LOCAL DECLARATION;
PROGRAM STATEMENTS;
Calling of user defined functions;
PROGRAM STATEMENT
---
---
}
Definition of user defined function1 – optional
{
Local Declaration;
Program Statement;
}
Definition of user defined function2 – optional
{
Local Declaration;
Program Statement;
}
1. Preprocessor Directives:
Preprocessor directives are commands that are processed by the preprocessor
before the actual compilation starts. They typically include header files or define
constants.
2. Global Variables (Optional):
Global variables are declared outside of all functions and are accessible to all
functions within the program.
3. Function Prototypes (Optional):
Function prototypes provide a declaration of user-defined functions before they are
used in the program. This informs the compiler about the function’s return type and
parameters.
4. The main() Function:
Every C program must have a main() function. It serves as the entry point where
program execution begins. The main() function typically returns an integer (int),
where return 0; signifies successful execution.
5. Braces:
Every C program should have a pair of curly braces ({,}).The left Braces indicates the
beginning of the main function, user defined functions, compound statement.
9. C programs can contain user-defined functions. These functions are defined outside
the main() function to perform specific tasks and can be called from the main() or
other functions.
EXECUTING THE C PROGRAM
The following sequence of steps involved in the execution of a C Program:
I. Create Source Program in C
II. Preprocessing of macros(# include, # define etc.)
III. Compilation of the program: shows the errors in the programs
IV. Linking the program with C library functions.
V. Execution of the program.
SOURCE PROGRAM
PRE-PROCESSOR
COMPILE SOURCE
PROGRAM
SYNTAX YES
ERROR
NO
LINKING PROCESS
SEMANTIC ANALYSIS:
Assembler: A computer will not understand any program written in a language, other than its
machine language. The programs written in other languages must be translated into the
machine language. Such translation is performed with the help of software. A program which
translates an assembly language program into a machine language program is called an
assembler. If an assembler which runs on a computer and produces the machine codes for the
same computer then it is called self-assembler or resident assembler. If an assembler that runs
on a computer and produces the machine codes for another computer then it is called Cross
Assembler.
Assemblers are further divided into two types: One Pass Assembler and Two Pass Assembler.
One pass assembler is the assembler which assigns the memory addresses to the variables
and translates the source code into machine code in the first pass simultaneously. A Two Pass
Assembler is the assembler which reads the source code twice. In the first pass, it reads all the
variables and assigns them memory addresses. In the second pass, it reads the source code
and translates the code into object code.
Interpreter: An interpreter is a program which translates statements of a program into
machine code. It translates only one statement of the program at a time. It reads only one
statement of program, translates it and executes it. Then it reads the next statement of the
program again translates it and executes it. In this way it proceeds further till all the
statements are translated and executed. On the other hand, a compiler goes through the
entire program and then translates the entire program into machine codes. A compiler is 5 to
25 times faster than an interpreter. By the compiler, the machine codes are saved permanently
for future reference. On the other hand, the machine codes produced by interpreter are not
saved. An interpreter is a small program as compared to compiler. It occupies less memory
space, so it can be used in a smaller system which has limited memory space.
Linker: In high level languages, some built in header files or libraries are stored. These libraries
are predefined and these contain basic functions which are essential for executing the
program. These functions are linked to the libraries by a program called Linker. If linker does
not find a library of a function, then it informs to compiler and then compiler generates an
error. The compiler automatically invokes the linker as the last step in compiling a program.
Not built in libraries, it also links the user defined functions to the user defined libraries.
Usually, a longer program is divided into smaller subprograms called modules. And these
modules must be combined to execute the program. The process of combining the modules is
done by the linker.
Loader: Loader is a program that loads machine codes of a program into the system memory.
In Computing, a loader is the part of an Operating System that is responsible for loading
programs. It is one of the essential stages in the process of starting a program. Because it
places programs into memory and prepares them for execution. Loading a program involves
reading the contents of executable file into memory. Once loading is complete, the operating
system starts the program by passing control to the loaded program code. All operating
systems that support program loading have loaders. In many operating systems the loader is
permanently resident in memory.
Syntax Errors in C:
A syntax error in C occurs when the code violates the rules of the C language, and the compiler
catches these errors. Compilation will fail, and the compiler will typically output an error
message pointing to the line causing the issue.
Common Examples of Syntax Errors in C:
Missing semicolon: Every statement in C must end with a semicolon. Forgetting this
will result in a syntax error.
int a = 5 // Syntax Error: missing semicolon
Mismatched braces or parentheses: Blocks of code (e.g., in if, for, or while statements)
need to be enclosed in curly braces {}. Forgetting to close them leads to a syntax error.
if (a > 5) {
printf("A is greater than 5");
// Syntax Error: missing closing brace
Incorrect use of variable types: Declaring variables with an invalid type or trying to
assign incompatible types will cause a syntax error.
int a;
a = "hello"; // Syntax Error: assigning a string to an integer variable
Misspelling of keywords: C is case-sensitive, so spelling errors can cause compilation
failures.
int main() {
Printf("Hello, World!"); // Syntax Error: misspelled 'printf'
}
2. Logical Errors in C:
Logical errors occur when the code compiles and runs but produces incorrect results. These
errors are not detected by the compiler, meaning the program may behave unexpectedly.
Debugging and testing are required to detect logical errors.
Common Examples of Logical Errors in C:
Incorrect use of operators: Using the assignment operator (=) instead of the equality
operator (==) in conditional expressions is a common logical error.
int a = 5;
if (a = 10) { // Logical Error: '=' should be '==' for comparison
printf("a is 10");
}
Off-by-one errors in loops: When iterating through arrays, it’s easy to go one element
too far or one element short.
int arr[5] = {1, 2, 3, 4, 5};
for (int i = 0; i <= 5; i++) { // Logical Error: 'i <= 5' should be 'i < 5'
printf("%d ", arr[i]);
}
Incorrect formula or logic: Incorrectly implementing an algorithm or formula can lead
to wrong results.
int sum = a + b / 2; // Logical Error: division has higher precedence than addition
// Correct should be: int sum = (a + b) / 2;
Fixing Errors:
For Syntax Errors: Carefully read the error message provided by the compiler. It
typically tells you the line number and nature of the syntax violation. Review your code
to correct the mistake, such as adding missing semicolons or fixing mismatched braces.
For Logical Errors: Logical errors require careful debugging. Use printf() statements to
print intermediate values in your program or use a debugger (like gdb) to step through
your code and observe the program's flow.
5.Tokens:
Def: A programming token is the components of the source code. Characters are categorized
as one of five classes of tokens that describe their functions(constants, identifiers, operators,
reserved words, and separators) in accordance with the rules of the programming language.
Tokens are the basic building blocks in C language which are constructed together to write a
C program. Each and every smallest individual unit in a C program is known as a C token. C
token is of types.
TOKENS
Strings
KEYWORDS (int, Identifiers (total, constants Special symbols
("anything in Operators (+,*,%)
for, char) num) (10,20.5) ({,#,^)
quote"
7.Identifiers:
Def: An identifier is a string of alphanumeric characters that begins with an alphabet
character or an underscore character that are used to represent various programming
elements such as variables, functions, arrays, structures, unions, and so on.
So, they are basically used to refer elements like variables, constants, array names, function
names, file names, pointer names and structure names.
Guidelines to define an identifier:
i. A sequence of letters, digits and _(underscore) can only be used for defining an
identifier.
ii. The first character should be a letter or _(underscore).
iii. Both lower-case and upper-case letters are permitted.
iv. Keywords should not be used as identifiers.
v. Identifiers are case sensitive.
vi. The maximum length of an identifier should be 32.
Example: valid: A, number1, number_, _number, first_1, first1_, first_number, etc.
Invalid: 1stno., 1st no., a’s, etc.
CONSTANT
NUMERICAL CHARACTER
CONSTANTS CONSTANT
SINGLE CHARACTER
INTEGER CONSTANTS/
CONSTANTS / STRING
REAL CONSTANTS
CONSTANTS
VARIABLES:
Def: Variables are simply names used to refer to some location in memory – a location that
holds a value with which we are working. It may help to think of variables as a placeholder
for a value.
[Note: variable is the one whose value can be changed during the execution of the program.
It plays an important role in computer programming. Instead of entering data directly into a
program, a programmer can use variables to store the data in memory. The memory location
is identified by the variable name. So when the program is executed, the variables are
replaced with data. The variables must be declared before they can be used in a program.]
(i)Declaring variables in C
To declare one variable:
Syntax: data-type variable;
Example: int a; float rate; char ch;
To declare more than one variable:
Syntax: data-type variable1, variable2, …….variable;
Example: int a, age, sum;
Float salary, average;
While declaring a variable, it can be initialized with a value.
For example, int age = 18; float rate = 10.5; char ch = ‘a’;
When a variable is declared, memory location gets allocated for the variable and the
location holds the value of that variable.
For example: int age = 18;
For the variable “age”, two bytes of memory will be allocated and the location holds the
value 18.
Age = name of the variable
18 = value of the variable.
Note: Rules for declaring a variable is same as declaring an identifier.
(ii) Declaring a constant: A constant can be declared like a normal variable, but preceded
with “const” keyword and a value should be assigned.
For example: const int rate = 10; const float pi =3.141; const char ch =’a’;
[Note: The value of rate, pi and ch should not be changed in the program.]
A constant value of a constant variable is called literals.
DATA TYPES:
Def: Data types are declarations of memory locations or variables that determine the
characteristics of the data that may be stored and the methods(operations) of processing
that are permitted involving them.
[Note: A data type is to identify various types of data, such as real, integeror character that
determines the possible values for that type.
Why Do We Use C Format Specifiers?
Format specifiers in C are used to take inputs and print the output of a type. The symbol we
use in every format specifier is %. Format specifiers tell the compiler about the type of data
that must be given or input and the type of data that must be printed on the screen.
ALGORITHM
Def:An algorithm is a precise and general set of steps that are used to solve a
problem or perform a computation.
GUIDELINES FOR ALGORITHM
1. It should terminate after a finite time.
2. It should produce at least one output.
3. It should take zero or more input.
4. It should be deterministic means giving the same output for the same input case.
5. Every step in the algorithm must be effective i.e. every step should do some work.