C Notes PDF
C Notes PDF
C Notes PDF
Programming
Evolution
ALGOL (Algorithmic Language) was the first computer language to
use block structure.
In 1967, Martin Richards developed a language called BCPL (Basic
Combined Programming Language) primarily for writing system
software.
In 1970, Ken Thompson created a language using many features of
BCPL and named it B.
C was evolved from ALGOL, BCPL and B. C was developed by
Dennis Ritchie at Bell Laboratories in1972.
C uses many concepts from these languages and added some new
features and emerged as a new language.
Most of the modern programming software and system software are
coded in C.
Characteristics of C Language
Well suited for structured modular programming.
Robust language with rich set of built-in functions and operators.
Has minimal instruction set and programs written in are efficient and fast.
Highly portable.
Highly flexible.
Allows access to the machine at bit level (Low level (Bitwise) programming).
Supports pointer implementation - extensive use of pointers for arrays,
structures, and functions.
Page 1 of 40
A program
It is a collection of declarations and functions.
It contains block structured statements.
Variables declared within a block are allocated on entry and terminated on exit.
Functions are blocks of codes defined for specific purpose inside the program
and can be called at the time of need.
Every C program begins with main() function and ends on exiting the main()
function.
Structure of a C Program
C program can be viewed as a group of building blocks called functions:
documentation section
preprocessor directives
global declaration section
main()
{
local declarations;
input statements;
processing statements;
output statements;
}
user-defined function definitions;
C Compilation Model
Preprocessor:
1. The Preprocessor accepts source code as input and interprets special
Page 2 of 40
Link Editor:
1. Source file may contain references, library functions or functions
defined in other source files and it is the role of link editor to combine
these functions with main() to create an executable file.
2. External variable references are also resolved here.
C Fundamentals
Basic elements of C language constitutes:
1. Character set
2. Identifiers
3. Operators
4. Expressions
5. Statements
C program organization
1. Relies on standard library for input & output.
2. Relies on external standard library for assertion.
3. Preprocessor for handling directives in the program.
Data types
Data type defines the kind of information and it includes the byte strength
supported by the compiler and range of values that it can accept
Categories
Page 3 of 40
Primary
:User defined:Derived
:Empty
:-
predefined built-in
defined by user
derived from combination of primary data types
Ex: void
Description
Integer quantity
Single character
Floating point members
Double precision floating
Point numbers
Memory
2 bytes
1 byte
4 byte
8 bytes
Range
-32,768 to 32,767
-128 to 127
3.4E-38 to 3.4E+38
1.73E-308 to
1.7E+308
Memory in bytes
int
signed int
unsigned int
short int
signed short int
unsigned short int
long int
signed long int
unsigned long int
2
2
2
1
1
1
4
4
4
Range
-32,768 to 32,767
-32,768 to 32,767
0 to 65,535
-128 to 127
-128 to 127
0 to 225
-2,147,483,648 to 2,147,483,647
-2,147,483,648 to 2,147,483,647
0 to 4,294,967,295
Page 4 of 40
Program elements
Tokens/alphabet,
Operators,
Comments,
Keywords,
Identifiers/ variables,
Literals/constants,
Statements
Tokens
It is the collection of characters that forms the basic vocabulary for compiler.
Alphabet
Lower case :- a,b,c,..,x,y,z.
Upper case :- A,B,C,.,X,Y,Z.
Digits
:- 0,1,2,3,4,5,6,7,8,9.
Special character:- (,),(),(),(),(),(.),(;).
Operators
Arithmetic :- (+),(-),(*),(/),(%).
Relational :- (<,>),(<=),(>=),(==),(!=).
Logical
:- &&, ||,!
Conditional :- ?:
Assignment :- =
Increment,decrement
:- ++,--,+=,-=,/=,%=,^=.
Boolean
:- <<,>>,/\,\/
Pointer
:- *,&,->,.
Parenthesis :- {,},(,),[,].
Comments
Comment lines are included in the program to give explanatory comments about
the program.
Comment lines have to be marked to separate them from program while compiling.
Page 5 of 40
::-
/*comment*/
//comment (rest of the line)
Keywords
Explicitly reserved words that have strict predefined meaning in C.
EX- else, register, static, long, int, virtual, etc
Use of Keywords
Keywords are used for
Declarations
Statement syntax
Access control
Compiler directives
Identifiers /variables
It is a sequence of letters or digits or characters.
Used as identifier (label/name) for objects (variables), methods (functions), and
symbolic constant.
Identifier should Not begin with a digit.
Upper, lower case letters are distinct.
Can be v-long (principle).
(usually) 31 characters.
Example
:-
Literals/ constants
Constant values are
Literals can be of any native data type values.
Example
:-
5,8,57,64,.
Page 6 of 40
Unsigned
Long
Octal
Hexadecimal
Boolean
Floating point
(Double)Floating point
Floating point (Long)
Character
Alignment
Wchart
String
::::::::::::-
8u,76u,54u,.
4L,50L,
O8,O96,.
Ox8,Ox96,..
true,false.
5.0,8.96,
5.0F,60.4F,..
5.0L,60.4L,.
S,..
\n,
LXYZ,..
S,.
alert
backslash
back space
carriage return
double quote
form feed
tab
new line
null character
single quote
vertical tab
Statements
1 Initialization
2 Input/output statements
3 Expression
4 Assignment statements
5 Control statements
6 Compound statement
7 Control structures
Input/output statements
Page 7 of 40
Input statements
scanf:
Syntax
example
Output statements
printf:
Syntax
example
//declared,defined,but un initialized.
//declared,defined,initialised.
Expression
Combination of identifier, constant and their operations (represented by operator)
that can be evaluated to a single value.
Tolerant towards mixing types.
Allows widening conversions
Eg : int can be widened to double.
Allows explicit/implicit narrowing conversions(considered a bad programming
practice) Eg : float can be narrowed to int.
Page 8 of 40
{
int a=0; //inner block
printf(%d %d,a,b);
}
printf(%d %d,a,b);
//outer block
Scope
Page 12 of 40
Page 13 of 40
Page 14 of 40
The elements in the array are always stored in consecutive memory locations.
An array of 5 integer elements, occupies 10 contiguous bytes in memory.
1st element
2nd element
1000
1002
Array Declaration:
3rd element
1004
4th element
1006
5th element
1008
Arrays are declared with appropriate data type and size. Array declaration
reserves space in memory.
Syntax:
datatype array_name[size];
EX:
int x[5];
Defines an integer array x of 5 integers starting at x[0], and ending at x[4].
char str[16]="qwerty";
Defines a character array which is used to represent a string of maximum of 16
characters.
float sales_amt[10];
Defines an floating point array sales_amt of 10 floating point numbers
starting at sales_amt[0]
and ending at sales_amt[9]
Accessing array elements
The array elements are accessed by specifying the subscript / index
Syntax:
array_name[index or subscript];
Page 16 of 40
Examples:
x[0]-> to access the 1st element in array
x[4]-> to access the 5th element in array
str[2]-> to access the 3rd character in a string
sales_amt[8]-> to access the 9th sales amount
Array initialization
Array elements can be initialized during declaration or can be initialized in the
program statements.
In partial initialization, the uninitialized array elements are initialized to zero or
NULL
Syntax:
datatype arrayname[size] = {value(s)};
OR
datatype arrayname[ ] = {value(s)};
Example
1.int a[5]={1,2,3,4,5};
/*a[0]=1, a[1]=2, a[2]=3, a[3]=4 and a[4]=5*/
2.int a[5]={0};
/*all the array elements are initialized to zero*/
3.int a[5]={1,2,3,4}; /*a[4] = 0*/
int a[ ] = {1,2,3,4};
/*a[0]=1, a[1]=2, a[2]=3, a[3]=4*/ If not specified size depends upon the
number of
values initialized.
4.float b[2]={10.2,45.34};
/*b[0] = 10.20, b[1] = 45.34*/
To initialize the array to zero automatically, the keyword static can be used
during initialization.
static int a[10];
/*all the array elements are initialized to zero automatically*/
Page 17 of 40
2.The static keyword is used to retain the value of array between function calls.
When static,
arrayinitial()
{
static int a[3];
a[0]+=10;
a[1]+=11;
a[2]+=5;
}
1. During the first call to the function:
Initial: a[0]=a[1]=a[2]=0
Final: a[0]=10 a[1]=11 a[2]=5
2.During the second call to the function:
Initial: a[0]=10 a[1]=11 a[2]=5
Final: a[0]=20 a[1]=22 a[2]=10
Basic operation of an array
1.Basic operation allowed on arrays are storing, retrieving, processing array
elements, and deleting array elements.
2.Inserting an element to an array is not directly possible.
3.Once an array element is deleted, the value in that location will be undefined
or garbage
Array is a constant pointer, so following expressions are illegal:
1.a++: Base address of array a is modified by adding one.
2.a+=2: Base address of array a is modified by adding two.
Getting the value for arrays
Examples:
int a[3];
scanf(%d, &a[0]);
/*get the value for 1st location*/
scanf(%d%d%d, a, a+1, a+2);
/*get the value for first 3 locations
(array name has the base address)*/
for(i=0;i<3;i++)
Page 18 of 40
scanf(%d,&a[i]);
Printing out of the arrays elements
Examples:
int a[3];
printf(%d, a[0]);
/*prints value of 1st location*/
printf(%d%d%d,a[0],a[1],a[2]);
/*prints value of first 3 locations*/
for(i=0;i<3;i++)
printf(%d,a[i]);
Multidimensional arrays
The elements of an array can themselves be arrays.
Multidimensional arrays will also occupy the contiguous memory locations.
Array elements are usually stored in row major order.
Two-Multidimensional array(Declaration)
Syntax:
datatype arrayname [row ][column]
Example:
int a[2][2];
/*creates 8 bytes of contiguous memory locations. (2*2 = 4
elements).*/
Assume that array starts at location 1000:
1.a[0][0] will be in 1000 (row 0 and column 0)
2.a[0][1] will be in 1002 (row 0 and column 1)
3.a[1][0] will be in 1006 (row 1 and column 0)
4.a[1][1] will be in 1008 (row 1 and column 1)
Two-Multidimensional array: Initialization
Multidimensional arrays can also be initialized in the declaration statement.
Examples:
int num[2][3] = {1,2,3,4,5,6};
int num[2][3] = {1,2,3,4,5};
Page 19 of 40
/*num[1][2] = 0*/
int num[2][3] = {{1,2,3},{1,2,3}};
/*row elements are initialized separately*/
int num[2][3] = {{1,2},{4}};
/*num[0][2] = 0, num[1][1]=num[1][2]=0*/
Advantages:
1.Simple and easy to use
2.Stored in contiguous locations
3.Fast retrieval because of its indexed nature
4.No need for the user to worry about the allocation and de-allocation of
arrays
Limitations:
1.If m elements out of n locations defined, n-m locations are
unnecessarily wasted
2.No automatic array bounds checking during compilation
Strings
Strings are sequence of characters.
A character string is stored in an array of character type, one ASCII character
per location.
String should always have a NULL character (\0) at the end.
Ex:
char c[4]={s,u,m,\0);
/*c[0] = s, c[1] = u, c[2] = m, c[3] = \0*/
char str[16]="qwerty";
Creates a string. The value at str[5] is the character y.
The value at str[6] is NULL.
The values from str[7] to str[15] are undefined.
char name[5] = INDIA
Strings are terminated by the null character, one extra storage location in an
array is required.
Array of string Declaration
Two dimensional character arrays are used to represent array of strings.
Page 20 of 40
Syntax:
char arrayname [no. of strings]
[max no. of chars in strings];
Example:
char studname[50][15];
50 student names each with 15 characters at the maximum.
Arrays of strings: initialization
Syntax:
char arrayname[r][c]={values};
Example:
char name[3][5] = {bata,cat,at}
char name[3][5] ={{b,a,t,a,\0},{c,a,t,\0},{a,t,\0}}
Reading a string
String can be read either by character-bycharacter or as an entire string
(using %s)
Example:
1. char name[20];
int i=0;
while((name[i]=getchar()) != \n)
i++;
scanf( %s , name);
ILLEGAL OPERATIONS ON A STRING:
1. Assigning a string to another string variable using = operator.
2.Comparing two strings using == operator.
3.Concatenating two strings using + operator.
Structures and union
Structures and unions help to store heterogeneous data items in one data
arrangement.
Structures and Unions are the main constructs available in C through which
Page 21 of 40
Structure Declaration
Structures are defined via a template and declared with a tag which helps to
avoid repeating the definition.
struct keyword is used to define structures.
Syntax:
struct tag_name
{
type variable-name, variable-name,........;
type variable-name, variable-name,........;
type variable-name, variable-name,........;
::
type variable-name, variable-name,........;
};
Structure-variables can be declared anywhere in the program.
Syntax to define structure variables:
struct tag_name new-structure-variable;
Example:
struct employee
Page 22 of 40
{
int code;
char name[20];
int dept_code;
float salary;
};
struct employee emp1, emp2;
Structure definition and declaration of structure variables can be combined
together.
Example:
struct employee
{
int code;
char name[20];
int dept_code;
float salary;
} emp1, emp2;
Note: Tag name is optional in this case.
Structure Initialization
Structure variables can be initialized at the time of declaration.
If the structure variable is declared before the main function, the member
variables are automatically initialized to zero or Null.
If it is partially initialized, then uninitialized members will be assigned zero or
Null character
.
Example:
struct stud
{
int rollnum;
char name[20];
int semester;
float avg;
};
Page 23 of 40
24s24t24r24u24c24t24_24v24a24r24i24a24b24l24e24.24m24e24m24b24e24r
24-24f24i24e24l24d24-24n24a24m24e24
24 24 24E24x24a24m24p24l24e24:24
24 24 24 24e24m24p24124.24c24o24d24e
emp1.name
emp1.dept_code
emp1.salary
emp2.code
emp2.name
Operations on structure:
Two structure variables cannot be compared for equality, even though the values
store In the member variables are the same. This is because slack bytes are added
in between two member variables and these slack bytes have some garbage value.
Nested structures
Structures can contain members that themselves are structures.
struct date
{
int day;
int month;
int year;
};
struct employee
{
int code;
char name [20];
struct date doj ;
int dept_code;
float salary;
}emp1,emp2;
Structures and arrays
The members of structures can be arrays and the structure can also be an array
Example:
struct stud
{
int rollnum;
char name[20];
int semester;
int avg;
};
struct stud student[50];
Accessing values:
student[1].rollnum, student[1].name,
Page 25 of 40
student[1].semester, student[1].avg
Arrays within structure:
Example:
struct student-mark
{
int rollnumber;
char name[15];
int sub_marks[5];
} student;
Accessing values:
student.sub_marks[0],
student.sub_mark[1], student.name
UNIONS
1.Union, like a structure, is a derived data type
2.Unions follow the same syntax as structures but the only difference is that
members of the union share storage.
3.Union differs from structure only in storage and in initialization.
DECLARATION
Syntax:
union tag_name
{
type variable-name, variable-name,........;
type variable-name, variable-name,........;
type variable-name, variable-name,........;
::
type variable-name, variable-name,........;
}union-variable1, union-variable2...... ;
UNION INITIALIZATION
Union can be initialized only with a value for the first union member. All other
member can not be initialized.
Example:
union item
Page 26 of 40
{
int m;
float x;
char c;
};
union item product = {100};
100 will be assigned to union member variable m.
UNIONS OF STRUCTURES
The members of structures and unions can include other structures and unions.
Example:
struct employee_type
{
int code;
char name[20];
int dept_code;
float salary;
};
struct stud_type
{
int rollno;
char name[15];
int age;
float avg;
};
union person
{
char surname[10];
struct employee_type e1;
struct stud_type s1;
}ex;
ENUMERATION
Enumeration is a derived data type, similar to structures or a union.
Page 27 of 40
Its members are constants that are written as identifiers, though they have signed
integer values.
These constants represent values that can be assigned to corresponding
enumeration variables.
enum keyword is used to declare enumerated variables.
Syntax:
enum tag {member1,member2,member n};
tag is a name that identifies enumerations.
Members represent the identifiers
Enumerated variables can be declared as follows:
storage-class enum tag var1,var2,varn;
Example:
enum escapes {bell=`\a', backspace=`\b', tab=`\t, newline=`\n', vtab=`\v',
return=`\r'}
main()
{
enum escapes e1;
e1 = getch();
if (e1 == newline)
printf("newline");
}
typedef
The typedef allows users to define new data types that are equivalent to existing
data types.
It gives new names to existing data types.
Syntax:
typedef datatype new-type;
Example:
typedef int numbers;
Page 28 of 40
Here, numbers is the new name given to integer data type and it can be used to
declare integer variables.
Example:
numbers n1, n2;
Example:
typedef struct
{
int empno;
char empname[10];
}employee;
employee emp1, emp2;
Note:
No need to use struct keyword when declaring structure variables.
Control structures
1. Linear structure: Executes in a sequential fashion where the next line will
be followed as the previous line is completed.
2.Decision Making /Branching/selection structures:Execute the portion of
statements that are found true on decision
simple if
if & if else structures
nested- if
ladder if
switch - case structure
goto statement
break statement
continue statement
3.Looping/iterative/cyclic structures:Repeated execution of set of statements
(from a starting point to ending point / as long as the condition is true/until
the condition becomes false)
while structure
do structure
for-loop structure
Page 29 of 40
Simple if
The general form is
if(condition)
statement;
Working
If the condition results in true then the following / subsequent statement is
executed.
If the condition results in false then the following / subsequent statement is not
executed.
Condition can be,
Boolean value(i.e., true or false).
Boolean expression.
Expression with logical / relational operators resulting in Boolean values.
Any integer / float value are implicitly converted to Boolean values.
Example
if(temperature<0)
printf(warning:Extreme chillness observed as the temperature is below 0);
if else structure
General form is
if(condition);
statement1;
else
Page 30 of 40
statement2;
statement3;
Working
if(mark<50)
printf(fail); // will o/p if condition is true.
else
printf(pass); //will o/p if condition is false.
printf(result);
else
{
if(condition3)
statement3;
else
statement4;
}
Working
1.
if(gender==boy)
{
if(marks=>50)
printf(boy passed);
else
Page 32 of 40
printf(boy failed);
}
else
{
if(marks=>50)
printf(girl passed);
else
printf(girl failed);
}
2.
if(subject1=>50)
{
if(subject2=>50)
{
if(subject3=>50)
{
if(subject4=>50)
{
if(subject5=>50)
printf(pass);
}
}
}
}
}
Working
First the expression is evaluated.
The expression value is matched with the values specified in the case area of
switch structure.
If the matching value is found, the respective statement is executed.
If no match is found then default statement is executed.
Control exits the structure & next statement outside the structure is executed.
Note:
A break statement is required at the end of each statement or compound
statement in the switch structure.
The break statement enables the control to exit the structure after executing
the respective statement.
In the absence of break statement all statements following the selected
statement inside the structure are executed before exiting.
In the absence of default case statement, no match for value is found and
none of the statements in switch case structure are executed.
Conditions cannot be used in the value option of the switch case structure.
The closing braces of switch case should not be followed by a semicolon.
Example:
scanf(%d,salary_grade);
switch(salary_grade)
{
Page 34 of 40
case 1: salary=3,000;
printf(%d,salary);
break;
case 2: salary=8,000;
printf(%d,salary);
break;
case 3: salary=15,000;
printf(%d,salary);
break;
default:
printf(invalid grade);
break;
}
goto statement
goto statement is the most primitive form of branching.
The branching statement is an unconditional branching to a labeled
statement.
General form:
goto label;
label:
statement;
Working
The control is immediately transferred to the statement at the label.
Note
This statement is to used with extreme caution, so that it does not disturb any
structures.
Preferably donot use this statement.
Example:int i=10;
Page 35 of 40
goto next;
i++;
printf(%d,i);
next: printf(we have skipped the o/p);
break statement:
General form
break;
Working
Break statement will face the control out of the program structure (current
structure).
Eg -> loop structures, if-else, switch.
Note: Will force total exit out of current structure.
Example:
i=0;
do
{
printf(%d,i);
i++;
}while(i>0); //will form a continuous loop
i=0;
do
{
printf(%d,i);
i++;
if(i>100) break;
}while(i>0); //will print from 0-100.
continue statement:
General form:
Page 36 of 40
continue;
Working
Continue statement will force the control out of current loop only.
Control will continue with next loop.
Note:
Used in looping structures.
Will not forcecomplete exit.
Loop will continue with next iteration.
Example
i=0;
do
{
if(i%2) continue;
printf(%d,i);
i++;
if(i>100) break;
}while(i>0); //will print even numbers from 0-100
Looping structures
While structures
The general form of a while statement is
while(condition)
Statement;
Working
The condition is evaluated.
Page 37 of 40
Page 40 of 40