You are on page 1of 119

1

 C Language is a general–purpose, procedure-oriented


programming language. C Language is known as Mother Language.
 It can be used to develop software like operating systems, databases,
compilers and different programs which we encounter in our daily
life.
 Algorithm :
An algorithm is a program which consists of well defined set of
instructions.
 Flow Chart :
Graphical Representation of an algorithm.
 Pseudo code :
Simple way of writing algorithm in English words. It gives text based
information of a program which helps to write algorithm and code.
2
Characteristics of an Algorithm:
 Finiteness: Every algorithm should terminate after finite number of
instructions.

 Unambiguity: Every instruction should be clear and have no ambiguity.

 Input: Every algorithm must and should have zero or more inputs.

 Output: Every algorithm must and should have one or more outputs.

 Definiteness: Specifying the sequence of operations for turning an input


into output.
3
S.NO NAME SYMBOL FUNCTION
1. PROCESS Evaluates the steps inside it

2. INPUT/OUTPUT Used to give input or to print output

3. DECISION Evaluates a condition, make a decision


(True/False)
4. CONNECTOR Connects flow charts

5. PREDEFINED Used to invoke a subroutine or interrupt


PROCESS program
6. TERMINAL Indicates starting or ending of a program

7. FLOW LINES Indicates the flow of direction

4
ALGORITHM FLOW CHART

Step 1: start start

Step 2: read a, b, sum;


read a, b, sum
Step 3: sum = a + b;
Step 4: print sum;
Step 5: stop sum = a + b

print sum

stop
5
 Dennis Richie is the father of C language.
 It was developed in 1972 at bell laboratories of AT & T, USA.
 In the 1960’s COBOL was used for commercial purposes and FORTAN is used for
scientific and engineering applications. At this stage, people started to develop a
language that is suitable for all possible applications.
 Therefore an International Committee was set up to develop ALGOL was released.
But it was not popular because it seemed too general.
 To reduce this generality a new language called CPL ( Combined programming
language ) was developed at Cambridge University. Then some other features are
added to this language and a new language called BCPL was developed by Martin
Richard at Cambridge university. Then B language was developed by Ken
Thompson at AT & T labs.

6
 Dennis Richie inherited the features of B and BCPL and added his own features and
developed C Language.

LANGUAGE YEAR DEVELOPED BY


ALGOL 1960 International Committee

CPL 1963 Cambridge University

BCPL 1967 Martin Richard

B 1970 Ken Thomson

C 1972 Dennis Richie

7
 Portability
 Design efficiency
 Procedure oriented
 Middle-level language
 Case sensitive
 Extensible
 Fast Execution

8
DOCUMENTATION SECTION
______________________________________________________________
LINK SECTION
______________________________________________________________
DEFINITION SECTION
______________________________________________________________
GLOBAL DECLARATION SECTION
______________________________________________________________
main()
{
Declaration Part
Executable Part
}
______________________________________________________________
Sub program section
Function 1
Function 2

9
Function n
1. DOCUMENTATION SECTION

The documentation section contains a set of comment lines giving the name of the program and
other details. There are two types of comment lines.
To give instructions to the programmer.
Comment Line does not executed.
1. Single Line Comment
2. Multi Line Comment

Single Line Comment Multi Line Comment


o The single line comment starts with // o Multi line comments start with /* and
and continue until the end of line. end with */. All the statements between
o Ex: these symbols are not executed.
o Ex:

10
 The link section provides instructions to the compiler to link the
functions from system library.
 C program depends on some header files. Each header file
extension is .h
 These header files are included at the beginning of the program in
the c language.
 Ex: #include <stdio.h> #include <conio.h>
#include <math.h>
#include <string.h> # - preprocessor

11
 This section is used to define all symbolic constants.
 A #define instruction defines value to a symbolic constant. Whenever the symbol
name is encountered in the program, the compiler substitutes the value associated
with the name automatically.
 Note: We can’t change the value of constant in program.

 Ex: #define pi 3.14


#define a 100

12
 Some variables are declared outside of the main function.
 These variables can be used by main function and all functions in the
program.
 The default value of the global variable is 0.

13
5. main( ) function:
 Every c program must and should have one main( ) function.
 This function does not take any arguments.
 The main( ) functions consists of statements which are enclosed within the braces.
opening brace { and closing brace }
 In this two braces there are two parts
 Declaration part
 Executable part

14
 It consists of all user defined functions.
 We can write any number of functions to a program.
 Functions are useful for code reusability.

main( )

Function 1 Function 2 Function n

15
16
 Data types are defined as the type of data storage format that a
variable can store.
 These are used to define a variable before to use in a program.
 There are three types of data types available in C
 Primary data type
 Derived data type
 User-defined data type
 The difference between these data types is the number of bytes they
occupy and the range of values.

17
 These are the basic data types in C.
 There are 4 types of primary data types available. They are:
 Integer
 Float
 Character
 void
 Using these data types, derived and user defined data types are
obtained.

18
 There are different integer data types available. They are int, short int, long int.

TYPE SIZE RANGE


(BYTES)
int 4 -32768 to 32767
short int 2 -32768 to 32768
long int 8 -2147483848 to 2147483847
Unsigned int 4 0 to 65535
Unsigned short int 2 0 to 65535
Unsigned long int 8 0 to 4294967295

19
 These are the values with decimals. It can also hold integer values.
 It consists of  float
 double
 long double

TYPE SIZE (BYTES) RANGE

float 4 3.4E – 38 to 3.4E + 38

double 8 1.7E – 308 to 1.7E + 308

long double 16 3.4E – 4932 to 3.4E + 4932

20
 There are two types of char
 They are 1) signed char, 2) unsigned char

TYPE SIZE (BYTES) RANGE


signed char 1 -128 to 128
unsigned char 1 0 to 255

21
2. DERIVED DATA TYPES :
These data types are derived from primary data types
Ex: arrays pointers

3. USER DEFINED DATA TYPES :


C allows users to define their own data types which is a combination of primary data
types and user defined data types.
Ex: structures, unions, enumerations

22
 C tokens are the smallest individual units
 We cannot create a sentence using words, Similarly we cannot write a C program
without C Tokens.
 So these are the basic building blocks of C Language.
 There are 6 types of C Tokens
1. Key Words
2. Identifiers
3. Constants
4. Strings
5. Operators

23
 Key words are the reserved and predefined words.
 They have some special meaning and we can’t change its meaning.
 Each of them are associated with specific feature.
 All keywords must be written in lower case only.
 Keywords cannot be used as identifiers.
 There are 32 keywords in C. They are

auto double int struct


break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

24
 Identifiers represent a name in a program.
 It consists of letters, digits and sequence of characters.
 Identifiers allow both uppercase and lowercase letters.
 Underscore ( _ ) is also used as an identifier. Generally it is used to link two long
identifiers
Rules to declare identifiers :
o Identifier must start with an alphabet.
o Special characters are not allowed except underscore.
o Key words can’t be used as identifiers

25
 Constants are the fixed values which can’t be changed during the execution of the
program.

CONSTANTS

NUMERIC CHARACTER

SINGLE STRING
INTEGER REAL
CHARACTER

HEXA
DECIMAL OCTAL
DECIMAL
26
Integer Constants :
 Decimal Integer Constant:
Consists of set of values from 0 to 9, preceded by an option + or – sign.
Ex: 123 +123 -123
Note: Spaces, commas, non digit characters are not allowed
like 10,000 $ 500 25 000
 Octal Integer Constant:
Consists of set of values from 0 to 7, leading with 0
Ex: 010 ( 8 in decimal )
 Hexa Decimal Constant:
Consists of set of values from 0 to F ( 0 to 9, A to F ) and leading with 0x
Ex: 0x9, 0xA

27
 Real Constants :
These are used to represent floating point ( which have fractions )
Ex : 5.034 0.129

 Character Constants :
Single Character Constants :
It consists of single character enclosed within single quotes (‘ ‘)
Ex : ‘A’ ‘d’
String Constant :
It consists of a sequence of character enclosed within double
quotes (“ “)
Ex: “Hello World” “Welcome 123”

28
 Strings are used to store group of characters, which are usually enclosed in double
quotations ( “ “ )
 The compiler appends Null Character – ‘\0’ at the end of string by default.
 String can consist of alphabets, numerical, special character and space.
Ex : char str[5] = “Hello”;

str H e l l o \0

Length of str is 5

29
Operator is a symbol which performs certain mathematical or logical operations.
C supports a rich set of operators. They are
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators

30
1. Arithmetic operators:
Arithmetic Operators performs numerical calculations.

OPERATOR MEANING
+ Addition or unary plus
- Subtraction or unary minus
* Multiplication
/ Division
% Modulus or Remainder

 In modulo division, the sign of result is always the sign of first operand (dividend).
Ex: 10 % 3 = 1 10 % -3 = 1
-10 % 3 = -1 -10 % -3 = -1

31
2. Relational operators:
 Relational operators are used to compare two quantities depending upon their
relation.

OPERATOR MEANING
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to

 Relational operators are complement to each other.


> is complement to <=
< is complement to >=
== is complement to !=
32
 In addition to relational operators, C provides logical operators.
Operator Meaning
&& logical AND
|| logical OR
! logical NOT

A B A && B A || B A!
T T T T F
T F F T F
F T F T T
F F F F T

33
 The assignment operator is used to assign the value to a variable.
Syntax:
a = 10
variable assignment operator value

 In addition to assignment operator c provides set of short hand assignment operators.

short hand assignment operator normal assignment operator


a += 1 a=a+1
a %= 1 a=a%1
a *= n + 1 a=a*n+1

34
 The C language provides two operators, increment and decrement operators.
 These are classified into 4 types.
1. Postfix increment : a = b++
2. Postfix decrement : a = b - -
3. Prefix increment : a = ++b
4. Prefix decrement : a = --b

POSTFIX POSTFIX PREFIX PREFIX


INCREMENT DECREMENT INCREMENT DECREMENT
If a = 5, If a = 5, If a = 5, If a = 5,
b=a++ b=a-- b= ++a b=--a
O/P : a = 6, b = 5 O/P : a = 4, b = 5 O/P : a = 6, b = 6 O/P : a = 4, b = 4

35
 The operator which consists of ? Followed by : is known as conditional operator.
 It is also known as Ternary operator.
expression 1 ? expression 2 : expression 3
 In this expression 1 is evaluated first. If it is TRUE, expression 2 is evaluated. It is
FALSE, expression 3 is evaluated.
 Ex:
a > b ? a :b
 if a = 10, b = 20, OUTPUT = 20
 if a = 45, b = 30, OUTPUT = 45

36
 These operators are used to perform operations on bits ( 0’s and 1’s )

OPERATOR MEANING

& Bitwise AND

| Bitwise OR

^ Bitwise Exclusive OR

~ One’s Complement

<< Shift LEFT

>> Shift RIGHT

37
1. Bitwise AND ( & ) :
If a = 12 and b = 10, Then a & b = 8
12 1100 ( binary representation of 12 )
10 1010
12 & 10  1 0 0 0 = 8
2 . Bitwise OR ( | ) :
If a = 12 and b = 10, Then a | b = 14
12  1 1 0 0 ( binary representation of 12 )
10  1 0 1 0
12 | 10  1 1 1 0 = 14

38
3. Bitwise Exclusive OR ( ^ ) :
If a = 12 and b = 10, Then a ^ b = 9
12 1100 ( binary representation of 12 )
10 1010
12 ^ 10  0 1 1 0 = 6

4. One’s Complement ( ~ ) :
One’s complement of a is - (a+1)
If a = 10, ~ a = -11
~a = - (a+1)
= - (10+1)
= -11

39
5. Shift LEFT ( << ):
The bits are shifted to left side. In this the output is the double of given input.

40
6. Shift RIGHT ( >> ):
The bits are shifted to right side. In this the output is the half of the given input.

41
 The c language consists of 3 Special Operators
 They are comma, address, sizeof( ) operators
 Comma operator:
It is used to separate variables or statements.
Ex: a = 10, b = 20
 Address Operator :
It is used to obtain the address of a variable.
Ex: &a
 sizeof( ) operator:
It is used to obtain the size of data type of a variable
Ex: int a = 5;
printf(“%d”, sizeof(a));

42
The combination of Operators and Operands is known as Expression.
Different types of expressions are
1. Simple Expression
2. Complex Expression
3. Unary Expression
4. Ternary or Conditional Expression
5. Postfix Expression
6. Prefix Expression

43
 Simple Expression:
Expression containing single operator followed by operands.
Ex: a+b a/b a%b
 Complex Expression:
Expression containing more than one operator followed by operands.
Ex: a+b*c a%b*c+d
 Unary Expression:
Expression containing single operator followed by single operand.
Ex: +a -b
 Ternary or Conditional Expression:
Expression containing question mark ( ? ) followed by ( : )
Ex: a < b ? a :b
 Postfix Expression:
Expression containing operand followed by postfix operator.
Ex: a++ a--
 Prefix Expression:
Expression containing prefix operator followed by operand.
Ex: ++a --a
44
If any expression containing multiple operators, then they are evaluated according to the
order of their Precedence and Associativity.
 Operator Precedence :
If an expression has more than one operator, then operator precedence determines which operator is
evaluated first.
EX: 4 * 5 + 10
In this multiplication is having highest priority than addition. So 4 * 5 is evaluated first and then result is
added to 10.
 Operator Associativity :

It is used when two operators having same precedence occurred in an expression. It can be Right to Left
or Left to Right.
Ex : 10 / 2 * 5
In this / and * have same priority and their associativity is Left to Right, So 10 / 2 is performed first and
then multiplication.

45
Category Operator Associativity
Postfix ( ) [ ] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & Right to left
sizeof
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= Right to left
<<= &= ^= |=
46
Comma , Left to right
 Escape sequence characters perform alternate operation on the character followed
by \ ( it escapes from original function )
 \n new line character
 \t horizontal tab space
 \v vertical tab space
 \a alert
 \b backspace
 \r carriage return
 \” prints “
 \’ prints ‘
 \? prints ?
 \\ prints \

47
It is the way of converting one data type into another data type.
There are two types
1. Implicit Type Conversion :
This type of conversion is performed by compiler on its own.
2. Explicit Type Conversion :
This type of conversion is performed by the programmer.

48
 A control statement is a statement that decides whether some statements will
execute or not. There are two types of control statements available.
1. Decision making or Selective statements.
2. Looping or Iterative statements.
 Decision making statements:
These statements will allow us to make to decision, whether to execute some
statements of not.
These are Two Types.
1. Conditional statements,
2. Unconditional statements.

49
 Different types of conditional statements are
1. if statement
2. if else statement
3. else if ladder
4. Nested if statement
5. switch statement

50
if condition :
We have to give an if condition, if the condition is TRUE, then the statements inside if
loop will execute. If it is FALSE, the statements will not execute.
Syntax:

if(condition) {
statements;
}

51
if else condition:
We have to give an if condition.
if the condition is TRUE, then the statements inside if block will execute.
If it is FALSE, the statements inside else block will execute.
Syntax:

if(condition) {
statements;
}
else {
statements;
}

52
else if ladder :
 The else if ladder statement executes one condition from multiple statements.
 The execution starts from top and checked for each if condition.
 The statement of if block is executed first. If the condition is TRUE, the statements in if block is executed
first.
 If it is FALSE, next else if condition is executed.
Syntax :
if (condition) {
statements;
}
else if (condition) {
statements;
}
else if (condition) {
statements;
}
.
.
else {
statements; 53
}
Nested if statement:
 An if statement within another if statement is known as Nested if statement.
 Syntax:
if (condition) {
if (condition) {
statements;
}
else {
statements;
}
}
else {
statements;
}
54
switch statement :
 A switch statement is a type of selection, used to allow the value of a variable to change the
control flow of program execution.
 It allows to choose only one choice among many choices.
 It consists of optional default statement.
 break keyword is used inside cases to terminate from switch.
Syntax :
switch (expression) {
case label 1: statements;
break;
case label 2: statements;
break;
.
.
case label n: statements;
break;
default : statements;
break;
}
55
An iterative statement repeatedly executes some statements which are inside the
loop until the control statement fails.
These are of 3 types
1. while loop
2. do – while loop
3. for loop

56
while loop :
 It is also known as entry controlled loop.
 Syntax :
while (condition) {
statements / body of loop; Repeat
}
 First the while condition is evaluated.
 If it is TRUE, then the body of while loop will execute. After that the control again
transfer to while condition and once again the while condition is evaluated.
 This process repeats until while condition is FALSE.
 If it is FALSE, the statements after while block will execute.
 To repeat the loop we have to give an updating statement, otherwise it will be an
infinite loop.
 Infinite while loop: if the while condition is always true, then the loop will execute
forever.
57
do – while loop :
 Usually for and while loop checks the condition at the starting of the loop. But the
do – while loop checks the condition at the ending (bottom) of the loop.
 So it is also known as Exit controlled statement.
 do – while loop will execute at least one time.
 Syntax :
….
do {
statements / body of loop;
} while (condition);
 First the statements inside do while loop will execute, after that the while condition
is evaluated. If the while condition is TRUE, then the body will execute otherwise
the statements after the loop will execute.
 To repeat the loop we have to give an updating statement, otherwise it will be an
infinite loop.
 Infinite do – while loop : if the do - while condition is always true, then the loop
will execute forever.
58
for loop :
 Syntax :

for ( initialization ; condition ; increment / decrement ) {


statements / body of the loop;
}
 The initialization statement is executed only once.
 Then the condition is evaluated. If it is FALSE, the loop for loop will terminate.
 If it is TRUE, then body of loop will execute. Then it will go to increment /
decrement.
 Again the loop will repeat until the condition is FALSE.
 Infinite for loop : if the condition in for loop is always true, then the loop will
execute forever.

59
It is a Keyword which is used to terminate from a loop / block and the statements
after the loop / block will execute.
1. break
2. continue
3. goto
For example,
If we use break inside a while loop, then the loop will terminate.
If we use break inside a nested while loop, then the inner while loop only will
terminate.

60
break :
 The break keyword is used to get control out of the loop.
 It is used inside loops or switch statement.
 It breaks one loop and executes the statement after the loop.
 If it is a nested loop, then only inside loop will break.
EX:
while(i<=5) { //i=1;
if (i==3)
break;
printf(“%d”,i);
i++;
}
Output : 1 2

61
continue :
 It is similar to break keyword.
 But instead of terminating the loop, it will just go to the next iteration.
 That means, it skips the current iteration and proceeds to the next.
 It is also used inside of loops.
EX :
while(i<=5) { //i=1
if (i==3)
continue;
printf(“%d”,i);
i++;
}
Output : 1 2 4 5

62
goto :
 It is used to transfer the control from one place to another statement.
 In this we have to use a label.
 Label purpose is to identify the place where the control has to be transferred.
 There are two ways to use label
goto label;
….
….
label :
….
….

63
label;
….
….
goto label :
….
….

64
Array is a collection of homogeneous data item that share a common name and
stores in continuous memory locations.
Why Arrays:
 we can use variables for small number of objects. In case if you want 1000
variables, you have to use 1000 scanf statements to read those values and 1000
printf values to print output.
 Then it becomes difficult to manage. In this case Arrays are useful.
 We can use many instances in one variable.
Ex: int a[1000] ( square bracket [ ] – subscript )

index

a[0] a[1] a[2] a[4] a[5] …. a[999]

65
Advantages of Arrays :
 Arrays can represent multiple data items of same type using a single name.
 Elements in arrays can be easily accessed by using index number.
 Matrices can be implemented by using 2 Dimensional arrays.
 Using arrays we can also implement data structures like Linked Lists, Stacks,
Queues, Graphs etc.
 Searching and sorting can be done efficiently.
Disadvantages of Arrays :
 The number of elements to be used in array have to be declared before.
 Arrays are static data type. Once the size of array is declared, we can’t modify it
again.
 Insertion and deletion of elements are slightly difficult as they are stored in
continuous memory locations.
 More memory allocation leads to wastage of memory.

66
Types of Arrays:
1. One dimensional arrays a[ ]
2. Two dimensional arrays a[ ][ ]
3. Multi dimensional arrays a[ ][ ][ ]…[ ]
One Dimensional Array :
It is a linear array, in which accessing elements is done by using single subscript.
Declaration:
syntax: type array_name[ size ];
Ex: int a[5]; // creates an array of integer type with size 5
float b[5];
char c[5]; // strings

67
Initialization of Array :
Static input :
1. int a[5] = { 1, 2, 3, 4, 5 };
2. int a[ ] = { 1, 2, 3, 4, 5 };
3. int a[5] = { }; // int a[5] = { 0, 0, 0, 0, 0 };
4. int a[5] = { 0 }; // int a[5] = { 0, 0, 0, 0, 0 };
5. int a[5] = { 1 }; // int a[5] = { 1, 0 ,0,0,0};
Dynamic input : (using loops)
printf(“Enter array elements: “);
for (i=0 ; i<n ; i++) {
printf(“%d”, &a[i] );
}
Printing of Arrays :
printf(“The elements in the array are: “);
for (i=0 ; i<n ; i++) {
printf(“%d”, a[i] );
}

68
Searching Techniques are used to search for a given element in the array.
There are two types of techniques.
1. Linear Search
2. Binary Search

1. LINEAR SEARCH :
This technique searches for the given element in a linear way. So it is also known as
Sequential search.
This technique keep on searching for the element until it is found or the array ends.

69
2. BINARY SEARCH
 This technique is applicable for sorted array only.
 It searches for the required element with the help of middle value. Based on the
comparison, it discards the array into half.
 This procedure is continued until the element is found or the array ends.
 Binary search mainly requires 3 things: low, mid, high.
 At first, the search element is compared with mid element. If both are equal, then it
is found.
 Else, it checks whether the search element is less than the mid element. If it is, then
the element is present at the first half of the array.
 Else, it checks whether the search element is greater than the mid element. If it is,
then the element is present at the second half of the array.

70
 These techniques are used to sort the array.
 There are different types of sorting techniques available.
i. Selection sort,
ii. bubble sort,
iii. insertion sort,
iv. merge sort,
v. radix sort,
vi. Quick sort etc..

71
 In this technique we select the smallest element in each pass and place it in
appropriate position.
 If we have ‘n’ elements, then it requires (n-1) passes to sort the elements.
 In pass 1, smallest element is searched between a[0] to a[n-1] and swapped with
a[0].
 In pass 2, smallest element is searched between a[1] to a[n-1] and swapped with
a[1].
 Similarly, this process is carried out n-1 times.

72
 In this technique we sort by comparing two adjacent elements at a time and
places them in appropriate position.
 If we have ‘n’ elements, then it requires (n-1) passes to sort the elements.
 In pass 1, largest element is searched between a[0] to a[n-1] and swapped with
a[n-1].
 In pass 2, smallest element is searched between a[1] to a[n-2] and swapped with
a[n-2].
 Similarly, this process is carried out n-1 times.

73
 The 2-dimensional array is also known as array of arrays.
 It is used for matrices which can be represented as rows and columns.
 It consists of two indices ( two subscripts ).
Declaration :
type array_name[size] [size];
Ex: int a[3][3];
INITIALIZATION :
int a[2][3] = { {1, 2, 3} , { 4, 5, 6} };
int a[2][3] = { 1, 2, 3, 4, 5, 6 };

74
 Read operation of 2D array:
for( i=0 ; i<r ; i++ ) {
for( j=0; j<c ; j++ ) {
scanf(“%d”, &a[i][j] );
}
}
 Write operation of 2D array:
for( i=0 ; i<r ; i++ ) {
for( j=0; j<c ; j++ ) {
printf(“%d”, &a[i][j] );
}
printf(“ \n “);
}

75
 A string is a sequence of characters terminated with a null character – ‘\0’
 The compiler appends null character by default when it founds a sequence of
characters ( which are enclosed within double quotations ).
 string.h is the header file which consists of string manipulation functions.
Syntax : char a[10];
a[0] a[1] a[2] a[3] a[4]

Input and output :


scanf(“%s”, a) ;(or) gets(a); // read input
printf(“%s”, a) ; (or) puts(a); // write or to print output

76
 Sometimes we need to manipulate strings in order to solve the problem.
 C provides some set of predefined string handling functions in the library string.h

1. strlen( ) :
It returns the length of the string.
Syntax : length = strlen(variable); // hello - 5
Without using string handling:
while( a[i] != ‘\0’ )
i++;
printf(“The length of string = %d”, i );

77
2. strrev( ) :
It reverses the string.
Syntax: strrev(variable);
Without using string handling:
while( a[i] != ‘\0’ )
i++;
while( --i >= 0 ) {
b[j] = a[i];
j++;
}
b[j] = ‘\0’;
printf(“The reverse string is %s”, b);

78
3. strcpy( ) :
It copies a string and stores it into another string.
Syntax: strcpy(destination_variable, source_variable );
Without using string handling:
while( a[i] != ‘\0’ ) {
b[j] = a[i];
i++;
j++;
}
b[j] = ‘\0’;
printf(“ b = %s”, b);

79
4. strcat( ) :
It concatenates or adds two strings.
Syntax: strcat(destination_variable, source_variable );
// concatenates and assigns it to destination_variable
Without using string handling:
while( a[i] != ‘\0’ )
i++;
while( b[j] != ‘\0’ ) {
a[i] = b[j];
i++;
j++;
}
a[j] = ‘\0’;
printf(“ a = %s”, a);

80
5. strcmp( ) :
It compares two strings equal or not. If they are equal it returns 0.
Syntax: strcmp( v1, v2 );
Without using string handling:
while(a[i] == b[j] && b[j] != ‘\0’ ) {
i++;
j++;
}
if (a[i] == b[j] )
printf(“Equal “ );
else
printf(“ Not equal “);

81
6. strlwr( ) :
It converts the given string into lower case.
Syntax :
strlwr (variable );

7. strupr( ) :
It converts the given string into upper case.
Syntax :
strupr (variable );

82
 Functions improves readability and reusability of code.
 Functions are useful when some block of statements have to be executed / written
again and again.
 It is easy to debug a program which has functions.
 It is easy to understand the program.
There are three important parts in functions
1. Function declaration
2. Function definition
3. Function calling

83
1. Function declaration ( Prototype ) :
A function declaration tells compiler that about the return type, name and arguments
which we are going to use in a program.
Syntax : return_type function_name ( list of arguments );
2. Function definition :
A function definition tells what a function has to do.
It consists of set of line which have to be executed when a function is called.
Syntax : return_type function_name ( list of arguments ) {
block of code / statements;
}
3. Function calling :
To invoke a function definition, we have to call the function.
Syntax : function_name ( list of arguments );

84
1. Function with no arguments and no return value :
In this type we don’t pass any arguments to the function. And it does not return any
value to the main function.
2. Function with arguments and no return value :
In this type we pass some arguments to the function. And it does not return any value
to the main function.
3. Function with no arguments and return value :
In this type we don’t pass any arguments to the function. And it returns some value to
the main function.
4. Function with arguments and return value :
In this type we pass some arguments to the function. And it returns some value to the
main function.

85
To pass an entire array to a function, only the name of the array is passed as an
argument.

86
1. Call by value :
 The value is passed from one function / main program to function.
 In call by value, only value of a variable is passes into formal parameters of
function.
So that, changes made inside the function has no effect on the argument.
2. Call by reference :
 The address of a variable is passed from one function / main program to function.
 In call by reference, it copies the address of an argument into formal parameter.
Inside the function, the address is used to access the actual argument. So that,
changes made inside the function effects on the arguments

87
 A function calling itself is known as recursion. The corresponding function is called
recursive function.
 While using recursion, be careful to write an exit condition, otherwise it will be an
infinite loop.
Advantages :
 Recursion reduces time complexity.
 Needs less time to code and to debug also.
 It more useful for data structures like trees, graphs etc.
Disadvantages :
 Recursion uses more memory.
 Compared to iteration, recursion can be slow. (as it requires new stacks every time)

88
Iteration vs Recursion :

Both iteration and recursion are repetitive process. Both will repeat some code until a
certain condition is met.
Iteration: A function repeats a block of code until the condition fails.
Iteration can be achieved by a loop having a condition that will fail. An infinite loop
for iteration occurs when the condition never fails.
Recursion: Instead of repeating a block of code, the function calls itself repeatedly
until a certain condition is met.
That condition is generally the exit condition of the recursion.
An infinite recursive loop occurs when the function does not reduce its input in a way
that it will reach the base case (exit condition )

89
fact(1) = 1
2*fact(1) 2*fact(1)
3*fact(2) 3*fact(2) 3*fact(2)
4*fact(3) 4*fact(3) 4*fact(3) 4*fact(3)
5*fact(4) 5*fact(4) 5*fact(4) 5*fact(4) 5*fact(4)

fact(1) = 1
2*fact(1) 2*1=2
3*fact(2) 3*fact(2) 3*2=6
4*fact(3) 4*fact(3) 4*fact(3) 4*6 = 24
5*fact(4) 5*fact(4) 5*fact(4) 5*fact(4) 5*24=120

90
 Pointer is a variable that stores the address of another variable.
 Pointer variable points to the address of another variable.
 Like normal variables, we have to declare the pointer variable.
type *pointer_variable;
 Next, we have to assign the address of other variable to pointer variable.
pointer_variable = &variable;
Note:
 & is known as reference operator ( address operator ). & operator is used to get
the address of a variable.
 * is known as dereference operator. * is used to get the value of variable located
at that address.

91
Null pointer :
A pointer that is assigned NULL is called a Null pointer.
In case if we don’t know which address to be assigned to a pointer variable, it is
better to assign NULL. (Most of the standard libraries defined the NULL value as 0)
DOUBLE POINTERS ( POINTER TO POINTER )
a *p **q
10 100 200

100 200 300

VARIABLE SINGLE POINTER DOUBLE POINTER


Value of a = a (10) Value of p = p (100) Value of q = q (200)
Address of a = &a (200) Address of p = &p (200) Address of q = &q (300)
Address of a = p (100) Address of p = q (200)
Value of a = *p (10) Value of p = *q (100)
Address of a = *q (100)
Value of a = **q (10)

92
 A pointer in c is an address, which is a numeric value. So that it is possible perform
arithmetic operations on a pointer. There are four arithmetic operators that can
be used on pointers: ++, --, +, and -
 For example,
Let us assume the address of ptr is 100 of type int.
ptr ++;
Then the value of ptr will goes to 104, as it is the next pointer available and the type
of ptr is int.
 If ptr is a character pointer, then ptr++ will results in 101.

93
 Accessing array elements can be possible with pointers in two ways.
1. Pointer to an array: In this we assign the address of array to a pointer variable. By incrementing
the value of pointer we can access array elements.
2. Array of pointers : In this we assign the address of each element of array to a pointer array

Pointer to an array Array of pointers

94
 In arrays, it is not possible to modify the size of array.
 But c provides a procedure to change size of data using memory allocation
functions.
 These functions are provided under stdlib.h header file.
 These functions allows you to increase / decrease / delete the memory.
1. malloc( )
2. calloc( )
3. free( )
4. realloc( )

95
1. malloc ( ) method :
malloc or memory allocation is used to dynamically allocate a single large block of
memory with the specified size.
It returns the address of first byte in the allocated memory.
It initializes each block with some default garbage value.
Syntax :
ptr = (cast-type *)malloc(byte-size);
Ex: ptr = (int *)malloc(10*sizeof(int));
10 blocks of type int is created as a single block ( total size – 40 bytes )
a large single block of 40 bytes of memory
ptr

96
2. calloc ( ) method :
calloc or contiguous allocation is used to dynamically allocate specified number of
blocks of memory of specified type.
It returns the address of first byte in the allocated memory.
It initializes each block with zero ( 0 ).
Syntax :
ptr = (cast-type *)calloc(n,element-size);
Ex: ptr = (int *)calloc(5,sizeof(int));
5 blocks of type int is created with contiguous space( total size – 20 bytes )
4 bytes 4 bytes 4 bytes 4 bytes 4 bytes
ptr
20 bytes of contiguous memory

97
3. realloc( ) method :
Realloc or re – allocation is used to dynamically change the previously allocated
memory ( by using malloc, calloc ).
If the previously allocated memory is not sufficient, then realloc is used to modify it.
Reallocation maintains the same previous data and initializes the newly created
blocks with default garbage value.
Syntax:
ptr = realloc(ptr, newsize);
Ex: 20 bytes of memory
ptr = (int *)malloc(5*sizeof(int));
… 40 bytes of memory
ptr = realloc(ptr, 10*sizeof(int));

98
4. free ( ) method :
free method is used to dynamically de – allocate the memory.
The memory created by using malloc( ), calloc( ) and realloc( ) are de – allocated
with the help of free( ) method.
It helps us to reduce the wastage of memory by freeing it.
Syntax:
free(ptr);
Ex:
Ptr = (int *) calloc(10, sizeof(int));

free(ptr);

99
 A structure is a user defined data type in c, used to create user defined data type which
is used to group items of different types into a single type.
Creating/ declaring struct :
A structure data type is created by using struct keyword followed by name of the
structure.
struct name {
structure member;
structure member;
} structure variables;
Ex :
struct example { struct example {
int a; int a;
float b; float b;
}; } e1, e2;
100
Initializing structure members :
Initializing structure elements can’t be done during struct declaration. Since the
memory is not allocated for it. Memory is allocated only when variables are created.
 Members can be initialised by using curly braces.
 Or by accessing individual struct element by dot operator and assign a value.

Accessing structure members :


For normal variables, accessing structure elements can be done with dot ( . )
operator.
For pointer variables, accessing structure elements can be done with arrow ( -> )
operator.

101
Declaring, initializing and accessing struct members

102
Accessing struct members with pointers

103
Self referential structure :
 Self referential structures are those structures that can have one or more pointer
which points to the same type of structure as their member.
Ex :

 Struct student{
int id;
char name[30];
struct student *next;
};

104
 A union is a special data type available in C, which is similar to structure.
 Unions allows to store different data types in the same memory location.
 You can define a union with many members, but only one member can contain a value
at any given time.
 Unions provide an efficient way of using the same memory location for multiple-
purpose.
 The memory occupied by an union will be large enough to hold the largest member of
the union.
Declaring:
Declaration of a union is similar to structure. The only difference is we have to use union
in place of struct keyword.
union name {
union member 1;
union member 2;
} union variables;

105
 The memory occupied by a union will be large enough to hold the largest member
of the union.
Example :
union example {
int a;
float b;
char c[30];
};
In the above example, among int, float, char (string of 30 bytes), char occupies more
space. So the size of the union is 30 bytes.
 Initializing union members can’t be done during its declaration.
 Accessing union members is same as in struct members. i.e.. Using dot operator( . )
or arrow ( -> ) operator.

106
 In the given example, the output of a
and b values are showing some
other value other than what we have
assigned.
 Because the final value assigned to
the variable has occupied the
memory location (char c[30] )
 this is the reason that the value of a
and b are not printed well.

107
 A storage class represents the visibility and a location of a variable. It tells from
what part of code we can access a variable. A storage class in C is used to describe
the following things:
• The variable scope.
• The location where the variable will be stored.
• The initial value(default value) of a variable.
• A lifetime of a variable.
TYPE INITIAL VALUE MEMORY ACCESSING LIFETIME
(SCOPE)
Auto Garbage value Main memory Block Block
Static Zero – 0 Static memory Block / multiple Program
files
Register Garbage value Registers Block Block
Extern (global) Zero - 0 Main memory Block program
108
 Enumeration (or enum) is a user defined data type in C.
 It is mainly used to assign names to integral constants, the names make a
program easy to read and maintain.
 enum keyword is used to declare enumerations.
Declaration :
enum name {value1, value2, value3,....};
Value1, value2, value3 .. Creates set of values of enum
Ex : enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
It is start with 0 (zero) by default and value is incremented by 1 for the sequential
identifiers in the list.

109
110
 Typedef is used to give a type a new name.
 It is similar to nick name or alias name.
 We can abbreviate it with new name.
 It is similar to #define. But typedef is limited to symbolic names to types only
 typedef is a keyword used to declare in this.
 Example

111
 The primary purpose of a file is to keep record of data. Record is a group of related
fields. Field is a group of characters. File handling is very important for applications.

 Data can be created by one program, stored on devices and then accessed or modified
by the other programs when necessary. The data on storage devices is stored as files.

 Buffer: A Buffer is a temporary storage area that holds data while it is being transmitted
to or from memory.

 EOF: when all the data has been read. At this point the file is said to be at the end of
file(EOF). The EOF is a constant defined in the header file stdio.h.

 A Stream is a channel on which data is passed from sender to receiver .So Stream is a
linear queue which connect file to program and passes block of data in both directions

112
Opening and defining a FILE :
Files can be accessed with pointers. So a pointer variable has to point a file.
Declaration : FILE *fp;
Opening : fp = fopen ( filename, “mode”);

MODE DESCRIPTION

Read mode – r opens a file in reading mode.


 If the file exists, sets up the pointer that points to the first character.
 If the file doesn’t exist, NULL is returned.
Write mode – w Opens a file in write mode.
 If the file exists, the contents are overwritten.
 If the file doesn’t exist, a new file is created.
Append mode - a opens a file in append mode.
 If the file exists, sets up the pointer that points to the last character.
 If the file doesn’t exist, a new file is created.
113
 r+ : opens a file in read and write mode. File pointer starts at
beginning of the file.
 w+ : opens a file in read and write mode. ( In w mode, if we try to
read, it is not possible )
 rw+ : opens a file in read and write mode. File pointer starts at the
beginning of the file.
Closing a file :
 File has to be closed after performing operations on a file.
 It can be done with fclose function.
Syntax : fclose (fp);

114
Input functions :
1. scanf( ) :
scanf(“control strings”, address of variable);
2. fscanf( ) :
Receives data from keyboard or from a file using fscanf()
Syntax : fscanf ( fp, “control strings”,address list );
Output funcitons :
1. printf()
2. fprintf() : Prints the data either to terminal or to the file.
fprintf(filepointer, “control string”, variable list );

115
1. getc ( ) or fgetc ( ) :
These functions are used to read a character from the file.
2. putc ( ) or fputc ( ) :
These functions are used to write a character into the file.

116
FUNCTION DESCRIPTION
fopen( ) Create a new file or opens an existing file
fclose( ) Closes a file
getc( ) Reads a character from a file
putc( ) Writes a character into a file
fscanf( ) Reads a set of data from a file
fprintf( ) Writes a set of data into a file
getw( ) Reads an integer from a file
putw( ) Writes an integer into a file
fseek( ) Set the position to desire point
ftell( ) Gives current positions in the file
rewind( ) Set the position to the beginning point

117
 Generally, in functions we give arguments. But main( ) function is mostly defined
without parameters.
 Command line arguments are given after the name of the program in command-line
shell of operating systems.
 To pass command line arguments, we define main( ) function with two parameters.
First argument is number of command line arguments and second one is list of
command line arguments.
void main ( int argc, char *argv [ ] ) { }
 Argument count (argc) stores number of command line arguments passed by the user
including the name of program. argc must be non negative.
 Argument vector (argv) is array of character pointers listing all the arguments.
If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain
pointers to strings.
argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.

118
C program to copy contents of one file into another file using
command line arguments

119

You might also like