CP Full
CP Full
CP Full
C Programming
MODULE I
Topics:
Introduction to computer programming; Various I/O functions; Data types; Constants and
Variables; Escape Sequences; Type Casting; Preprocessor Directive; Storage Classes; Scope of
Variables; Mathematical Operators; Relational Operators; Branching Instructions; Logical
Operators; Conditional Operator; Precedence of Operators; Loops – for, while and do-
while, break and continue instructions, Nested Loops; Switch statement; Evaluation of ex
,sin(x), cos(x) ,Numerical Integration using Trapezoidal and Simpson’s rules.
Input statements
getchar()
gets()
scanf()
Output statements
putchar()
puts()
printf()
getchar () – single character input function:
getchar () is used to get or read a single character from the keyboard.
The function does not require any arguments, through a pair of empty parenthesis must
follow the word getchar.
Syntax:
Character variable = getchar ();
char ch;
ch = getchar ();
Page 1 of 74
faizi_+918137088810
C Programming
d integer
f float
c char
s string
ld Long int
lf double
int a;
float b;
scanf (“%d %f”,&a,&b);
int a;
float b;
scanf (“%d %f”, &a, &b);
printf (“%d %d”, a,b);
gets () and puts () functions
The gets () and puts () functions, which facilitate the transfer of strings between the
computer and the standard input-output devices.
Each of these functions accepts a single argument.
The argument must be a data item that represents a string. The string may include
whitespace characters.
char s [10];
Page 2 of 74
faizi_+918137088810
C Programming
gets(s);
puts(s);
Data types:
'Data types’ means type of data, which are used to define a variable before its use. The
definition of a variable will assign storage for the variable and define the type of data that will
be held in the location.
C supports three classes of data types
Data Types
The usual memory requirement for short and long are 1 byte and 4 bytes respectively.
Floating-point type (float)
The floating point data type is used to represent real numbers.
The keyword float is used to declare floating point variables in programs.
Floating point numbers are stored in 4 bytes (32 bits) with 6 digits of precision
Double
Page 3 of 74
faizi_+918137088810
C Programming
When the accuracy provided by a float number is not sufficient, the type double can be used
to define the number.
A double data type number uses 64 bits giving a precision of 14 digits.
Double type represents the same data type that float represents, but with a great precision. To
extend the precision further, we may use long double which uses 80 bits.
float 4 bytes
8 bytes
double
long double
10 bytes
Constants
Integer Constants
Integer constant is an integer valued number
4
Page 4 of 74
faizi_+918137088810
C Programming
Page 5 of 74
faizi_+918137088810
C Programming
Variable Declaration
• Any variable must be declared (defined) before it can be used in the program.
Declaration does two things
It tells the compiler what the variable name is
It specifies what type of data the variable will hold
Syntax:
datatype variable_ name;
Examples: int a;
float b;
int a,b,c;
Page 6 of 74
faizi_+918137088810
C Programming
C supports some special back slash character constants that are used in output functions.
It beginning with a back ward slash and is followed by one or more special characters.
\b back space
\n new line
\t horizontal tab
\v vertical tab
\0 null
Type Casting:
Type casting is a way to convert a variable from one data type to another data type.
Syntax:
(type_name) expression
Example:
Without type casting Type casting
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int a=5,b=2; int a=5,b=2;
float c; float c;
c= a/b; c= (float)a/(float)b;
printf("C =%f",c); printf("C =%f",c);
getch(); getch();
} }
Output Output
C = 2.000000 C = 2.500000
Preprocessor Directive:
The C pre-processor is a collection of statements, called directives that are executed at the
beginning of the compilation process. All preprocessor directives begin with #.
Example: #include, #define
Storage Classes:
There are four storage classes in C.
1. Automatic
2. Register
3. Static
4. External
Page 7 of 74
faizi_+918137088810
C Programming
Automatic
The keyword for this storage class is auto
Storage Memory
Default initial value Garbage value
Scope Local to the block in which the variable is defined
Life Till the control remains within the block in which the
variable is defined.
Register
Storage CPU registers
Default initial value Garbage value
Scope Local to the block in which the variable is defined
Life Till the control remains within the block in which the variable is
defined.
Static
Storage Memory
Default initial value Zero
Scope Local to the block in which the variable is defined
Life Value of the variable persists between different function
calls
External
An external variable can be assigned a value within one function, and this value can
be used within another function. The keyword for this storage class is extern.
Storage Memory
Default initial value Zero
Scope Global
Life As long as the programs execution come to an end
Operators
Arithmetic operators
Unary operators
Binary operators
Assignment operators
Equalities and relational operators
Logical operators
Conditional operator
Arithmetic operators
Page 8 of 74
faizi_+918137088810
C Programming
Operation Operator
Addition +
Subtraction _
Multiplication *
Division /
Modulus %
Unary operators:
C includes a class of operators that act upon a single operand to produce a new value. Such
operators are known as Unary operators:
There are two types of unary operators
Increment Operator
Decrement Operator
The increment operator causes its operand to be increased by 1
The decrement operator causes its operand to be decreased by 1
i++ is equivalent to i = i + 1
i-- is equivalent to i = i-1
The increment and decrement operators can each be utilized two different ways, depending
on whether the operator is written before or after the operand.
If the operator precedes the operand (++ i), then it is called as pre-increment operator and
the operand will be altered in value before it is utilized for its intended purpose within the
program.
If the operator follows the operand (i++), then it is known as post-increment operator and
the value of the operand will be altered after it is utilized.
• Consider this example:
int a = 9;
printf(“%d\n”, a++);
printf(“%d”, a);
Page 9 of 74
faizi_+918137088810
C Programming
int a = 9;
printf(“%d\n”, ++a);
printf(“%d”, a);
The output would be:
10
10
a++ would return the current value of a and then increment the value of a
++a on the other hand increment the value of a before returning the value
Relational Operator
Operator Meaning
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
Equality Operators
Operator Meaning
== Equal to
!= Not equal to
Logical Operator
Assignment Operators
These are used to form assignment expressions, which assign the value of an expression to an
identifier.
The most commonly used assignment operator is ’=’
Assignment operator = and equality operator = = are distinctly different
Identifier = expression;
Conditional operator
10
Page 10 of 74
faizi_+918137088810
C Programming
Example:
total > 60? grade = ‘P’: grade = ‘F’;
OR
grade = total > 60? ‘P’: ‘F’;
Control statements:
Control statements control the flow of execution depending upon certain conditions is true or
false.
There are three types of control statements:
Conditional statements/ Branching statements
Looping statements
Jumping statements
Control statements
Conditional Statements:
if statement – The if statement helps us to make a decision.
Syntax:
if (condition)
{
11
Page 11 of 74
faizi_+918137088810
C Programming
Statements;
}
In the ( ) of if, the expression is checked for true or false. If the value within the ( ) comes to
be true, then the statements within the if block { } is executed otherwise not.
true false
if (condition)
{
Statements
}
Statements
}
12
Page 12 of 74
faizi_+918137088810
C Programming
Statements;
}
else
{
Statements;
}
#include<stdio.h>
#include<conio.h>
void main ()
{
int num;
clrscr ();
printf (“enter a number:”);
scanf(“%d”,&num);
if (num % 2==0)
printf (“%d is even”,num);
else
printf(“%d is odd”,num);
getch ();
}
Nested if – else
Syntax:
if (condition 1)
true {
if (condition 2)
true {
statement 1
} false
else false
{
statements 2
}
}
else
{
statement 3
13
Page 13 of 74
faizi_+918137088810
C Programming
#include<stdio.h>
#include<conio.h>
void main ()
{
int num1, num2, num3;
clrscr ();
printf(“enter three numbers:”);
scanf(“%d %d %d”,&num1,&num2,&num3);
if (num1 > num2)
{
if (num1 > num3)
{
printf(“greatest is %d”,num1);
}
else
{
printf(“greatest is %d”,num3);
}
}
else
{
if (num2 > num3)
{
printf(“greatest is %d”,num2);
}
else
{
printf (“greatest is %d”,num3) ;
}
}
}
else – if
When we want to select one option out of one, we use “if”. When we want to select one
option out of two, we use “if- else” and if we want to select one option out of many we
use “else - if”
14
Page 14 of 74
faizi_+918137088810
C Programming
if (condition)
true { false
statement1
}
else if (condition)
true {
statement2
} false
else if (condition)
true {
statement3
}
else false
{
statement4
}
#include<stdio.h>
#include<conio.h>
void main ()
{
float mark;
clrscr();
printf(“enter mark:”);
scanf (“%f”,&mark);
if(mark>=80 && marks<=100)
printf(“grade: a”);
else if(mark>=60 && marks<=80)
printf(“grade: b”);
else if(mark>=40 && marks<=60)
printf(“grade: c”);
else if(mark>=0 && marks<=40)
printf(“grade: d”);
else
15
Page 15 of 74
faizi_+918137088810
C Programming
switch (expression)
{
case value1:
statements
break;
case value2:
statements
break;
case value3:
statements
break;
default:
statements
}
The expression is an integer or character
Value1 and value2 are constants or constant expressions and are known as case labels
Case labels ends with a colon (:)
When the switch is executed, the value of the expression is compared against the values
value1, value2……..if a case is found whose value matches with the value of the
expression then the block that follows the case are executed.
The break statement at the end of each block causes an exit from the switch statement
The default is an optional case. When present, it will be executed, if the value of the
expression does not match with any of the case values.
#include<stdio.h>
#include<conio.h>
void main ()
{
int n;
clrscr();
16
Page 16 of 74
faizi_+918137088810
C Programming
Looping Statements:
The loop statement instructs the system to execute the statement n number of times without
having to write the code again and again.
Loop is divided into two segments:
Control statement – It is given to govern the no: of times we need to repeat a set
of statements
Body – It contain the statements that we need to repeat.
The loop statements are categories into two parts:
Entry controlled
Exit controlled
17
Page 17 of 74
faizi_+918137088810
C Programming
Loop statements
Entry controlled loops – By entry controlled loop we mean that the control statement of the
loop is preceded by the body of the loop
Exit controlled loops - By exit controlled loop we mean that the control statement of the
loop comes after the body of the loop
while loop
while (condition)
{
Block of statements;
}
18
Page 18 of 74
faizi_+918137088810
C Programming
After the execution of the body, test condition is once again evaluated and if it is true, the
body is executed once again. This process of repeated execution of the body continues until
the test condition finally becomes false and the control is transferred out of the loop.
a=10;
while (a! = 0) Output: 10987654321
{
printf(“%d”,a);
a- -;
}
do- while
“while” loop first checks the condition and then executes the statements within it. If the
condition evaluates to false on the very first time, loop will terminate.
A “do-while” loop first executes the statements at least once and then checks the condition.
do
{
Statements;
} while (condition);
On reaching the do- statement, the program proceeds to evaluate the body of the loop first
At the end of the loop, the test condition in the while statement is evaluated.
If the condition is true, the program continues to evaluate the body of the loop once again.
This process continues as long as the condition is true. When the condition becomes false,
the loop will be terminated.
Since the test condition is evaluated at the end of the loop, the do-while statement provides
an exit controlled loop and therefore the body of the loop is always executed at least once.
19
Page 19 of 74
faizi_+918137088810
C Programming
do-while while
int a = 5; int a= 5;
do while(a>5 && a<10)
{ {
printf(“%d”,a); printf(“%d”,a);
a= a+1; a= a+1;
}while(a>5 && a<10); }
Output: Output:
56789 No result
for loop
For loop often referred to as iterative loop
It is an entry controlled loop
Syntax:
20
Page 20 of 74
faizi_+918137088810
C Programming
Initialization of the control variables is done first, using assignment statements such as i =1
and count = 0. The variables i and count are known as loop control variables
The value of the control variable is tested using the test condition. The test condition is a
relational expression, such as i< 0 that determines when the loop will exit. If the condition is
true, the body of the loop is executed, otherwise the loop is terminated.
When the body of the loop is executed, the control is transferred back to the for statement
after evaluating the last statement in the loop. Now, the control variable is incremented using
an assignment statement such as i=i+1 and the new value of the control variable is again
tested to see whether it satisfies the loop condition. If the condition is satisfied, the body of
the loop is again executed. This process continues till the value of the control variable fails
to satisfy the test condition.
Nested for loop
Nested loop means a loop inside another loop
Syntax:
Statements;
}
}
Jumping Statements
These statements are used to transfer the execution control of a program from one statement to
another.
21
Page 21 of 74
faizi_+918137088810
C Programming
break statement
The break keyword is used to exit from a loop based on some condition given by the
programmer.
for(condition)
{
statement 1;
if(condition)
{
statement 2;
break;
}
statement 3;
}
statement 4;
continue statement
The continue statement skips the remaining statements in the body of the loop, and continue
with next iteration of the loop from first line.
for(condition)
{
statement 1;
statement 2;
if(condition)
{
continue;
statement 3;
statement 4;
}
break continue
22
Page 22 of 74
faizi_+918137088810
C Programming
Output Output
1 2 3 4 5 6 1 2 3 4 5 6 8 9 10
return statement
Return statement is used to exit from a function and return to the next statement of the calling
function that called the function. Unlike break statement that only exits the loop, return forces
the control to leave the function.
PROGRAMS:
Sum of two numbers:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,sum;
printf(“Enter two numbers:”);
scanf(“%d %d”,&a,&b);
sum = a+b;
printf(“Sum is %d”,s);
getch();
}
ci = 2 * PI * rad;
printf("Circumference : %f ",ci);
getch();
}
23
Page 23 of 74
faizi_+918137088810
C Programming
Area of Square
#include<stdio.h>
#include<conio.h>
void main()
{
int side,area;
clrscr();
printf("Enter the Length of Side : ");
scanf("%d",&side);
area = side * side ;
printf(" Area of Square : %d",area);
getch();
}
Area of Right Angled Triangle
#include<stdio.h>
#include<conio.h>
void main()
{
int base,height;
float area;
clrscr();
printf(“Enter the base of Right Angle Triangle : ");
scanf("%d",&base);
printf("Enter the height of Right Angle Triangle : ");
scanf("%d",&height);
area = 0.5 * radius * radius;
printf("Area of Right Angle Triangle : %f",area);
getch();
}
Area of Rectangle
24
Page 24 of 74
faizi_+918137088810
C Programming
#include<stdio.h>
#include<conio.h>
void main()
{
int length,breadth,side;
clrscr();
printf(" Enter the Length of Rectangle : ");
scanf("%d",&length);
printf("Enter the Breadth of Rectangle : ");
scanf("%d",&breadth);
area = length * breadth;
printf("Area of Rectangle : %d",area);
getch();
}
Swapping of two numbers:
#include<stdio.h>
#include<conio.h>
void main ()
{
int a,b,c;
clrscr();
printf(“Enter two numbers:”);
scanf(“%d %d”,&a,&b);
c=a;
a=b;
b=a;
printf(“After swapping a=%d b=%d”,a,b);
getch();
}
#include<stdio.h>
#include<conio.h>
void main ()
25
Page 25 of 74
faizi_+918137088810
C Programming
{
int a,b;
clrscr();
printf(“Enter two numbers:”);
scanf(“%d %d”,&a,&b);
a=a + b;
b=a - b;
a= a - b;
printf(“After swapping a=%d b=%d”,a,b);
getch();
}
void main()
{
int a,b,c;
clrscr();
printf("\n Enter value of a, b & c: ");
scanf("%d %d %d",&a,&b,&c);
if((a>b)&&(a>c))
printf("\n a is greatest");
else if((b>c)&&(b>a))
printf("\n b is greatest");
else if((c>a)&&(c>b))
printf("\n c is greatest");
getch();
}
Calculate sum of ‘n’ numbers:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,num,sum =0;
clrscr();
printf(“enter the limit:”);
scanf(“%d”,&n);
printf(“enter %d numbers”,n);
for(i=1;i<=n;i++)
{
scanf(“%d”,&num);
26
Page 26 of 74
faizi_+918137088810
C Programming
sum = sum+num;
}
printf(“the sum is %d”,sum);
getch();
}
Fibonacci Series:
#include<stdio.h>
#include<conio.h>
void main ()
{
int a=0,b=1,s=0,n,i=3;
clrscr();
printf(“enter the limit:”);
scanf(“%d”,&n);
printf(“%d %d”,a,b);
while(i<=n)
{
s= a+b;
a=b;
b=s;
i++;
printf(“%d”,s);
}
getch();
}
#include<stdio.h>
#include<conio.h>
27
Page 27 of 74
faizi_+918137088810
C Programming
void main()
{
int num,rem,rev=0;
clrscr();
printf("\n Enter any no to be reversed : ");
scanf("%d",&num);
while (num>=1)
{
rem = num % 10;
rev = rev * 10 + rem;
num = num / 10;
}
printf("\n Reversed Number : %d",rev);
getch();
}
Sum of digits:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,r,s=0;
clrscr();
printf("\n Enter the number : ");
scanf("%d",&n);
while (n!=0)
{
r = n % 10;
n = n / 10;
s= r + s;
}
printf("\n sum=%d",s);
getch();
}
To check the given number is palindrome or not
#include<stdio.h>
#include<conio.h>
void main()
{
int num,b=0,c=0,d=0;
clrscr();
28
Page 28 of 74
faizi_+918137088810
C Programming
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("\n Enter the year : ");
scanf("%d",&n);
if((n%4 = =0) && (n%100!=0) !! (n%400 = =0))
{
printf(“the given year is leap year”);
}
else
{
printf(“the given year is leap year”);
}
getch();
}
Check the given number is Armstrong or not
#include<stdio.h>
#include<conio.h>
void main()
{
int num,d,dup,sum =0;
clrscr();
printf("\n Enter the number : ");
scanf("%d",&num);
dup = n;
29
Page 29 of 74
faizi_+918137088810
C Programming
while (num>=1)
{
d = num % 10;
sum = sum + d*d*d;
num = num / 10;
}
if(sum= =dup)
printf(“It is an armstrong number”);
else
printf(“It is not an armstrong number”);
getch();
}
To check whether a number is prime or not
#include<stdio.h>
#include<conio.h>
void main()
{
int n,b=2,flag=0;
printf("Enter the no:");
scanf("%d",&n);
while(flag==0 && b<=n/2)
{
if(n%b==0)
{
flag=1;
break;
}
b++;
}
if(flag==0)
printf("number is prime");
else
printf("number is not prime");
getch();
}
30
Page 30 of 74
faizi_+918137088810
MODILE II
Array:
An array is a collection of similar type of elements with same name and different index number.
Page 31 of 74
faizi_+918137088810
Page 32 of 74
faizi_+918137088810
#include<stdio.h>
#include<conio.h>
void main ()
{
int a[10][10],b[10][10],c[10][10,]r,c,i,j;
printf(“enter row size and column size:”);
scanf(“%d %d”,&r,&c);
printf(“enter the first matrix:”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“enter the second matrix:”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”, &b[i][j]);
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
c[i][j] = a[i][j]+b[i][j];
}
}
printf(“The resultant matrix is: ”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(“%d”, c[i][j]);
Page 33 of 74
faizi_+918137088810
}
printf(“\n”);
}
getch ();
}
Multiplication of two matrices:
#include <stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,r1,c1,r2,c2,k;
clrscr();
printf("Enter row & column size of 1st matrix: ");
scanf("%d %d",&r1,&c1);
printf("Enter row & column size of 2nd matrix: ");
scanf("%d %d",&r2,&c2);
if(c1!= r2)
printf("multiplication not possible");
else
{
printf("Enter elements of 1st matrix");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter elements of 2nd matrix");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d", &b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
Page 34 of 74
faizi_+918137088810
{
c[i][j]=0;
for(k=0;k<c1;k++)
{ c[i][j]= c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("Product of the matrices");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
printf(" %d", c[i][j]);
}
printf("\n");
}
getch();
}
Transpose of a Matrix:
#include<stdio.h>
#include<conio.h>
void main ()
{
int a[10][10],r,c,i,j;
printf(“enter row size and column size:”);
scanf(“%d %d”,&r,&c);
printf(“enter the elements:”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“The matrix is ”);
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf(“%d \t”, a[i][j]);
Page 35 of 74
faizi_+918137088810
}
printf(“\n”);
}
printf(“Transpose of the matrix is ”);
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
printf(“%d \t”, a[j][i]);
}
printf(“\n”);
}
getch ();
}
Strings:
Strings are collection of characters terminated by the character ‘\0’
Strings are also defined as the array of characters
C does not support strings as a data type. It allows us to represent strings as character
arrays
strlen () function
This function is used to find the length of the string
Syntax:
Page 36 of 74
faizi_+918137088810
n = strlen (string); where n is an integer variable, which receives the value of the length of
the string
Example: To find the length of the string using strlen () function
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char str [10];
int n;
printf (“Enter the string :”);
gets (str);
n = strlen(str);
printf(“The length of the string is %d”,n);
getch();
}
strcat () function
The strcat () is used to append one string at the end of another
Syntax:
strcat (string1, string2);
string1 and string 2 are character arrays. When the function strcat is executed, string2 is
appended to string1. It does so by removing the null character at the end of string1 and placing
string2 from there. The string at string2 remains unchanged.
Str1
0 1 2 3 4 5 6 7 8 9
V E R Y \0 \0 \0 \0 \0
Str2
0 1 2 3 4 5
G O O D \0 \0
Str1
0 1 2 3 4 5 6 7 8 9
V E R Y G O O D \0
Page 37 of 74
faizi_+918137088810
Str2
0 1 2 3 4 5
G O O D \0 \0
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char str1[10],str2[10];
printf(“enter the first string:”);
gets(str1);
printf(“enter the second string:”);
gets(str2);
strcat(str1,str2);
printf(“The combined string is %s”,str1);
getch ();
}
strcmp() function
The strcmp () is used to compare one string with another. If both are same, the function returns
0, else it returns the numeric difference between the first nonmatching characters in the
strings.
Syntax:
strcmp(string1,string2);
Example:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char str1[10],str2[10];
printf(“enter the first string:”);
gets(str1);
printf(“enter the second string:”);
gets(str2);
if(strcmp(str1,str2)= =0)
printf(“Strings are equal”);
else
printf(“Strings are not equal”);
getch();
Page 38 of 74
faizi_+918137088810
}
strcpy () function
The strcpy () is used to copy one string into another.
Syntax:
strcpy(string1,string2);
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char str1[10],str2[10];
int i =0;
printf(“enter the first string:”);
gets(str1);
printf (“enter the second string:”);
gets(str2);
strcpy (str1,str2);
printf (“The copied string is %s”, str1);
getch ();
}
Array of strings:
We can have multiple strings in a single array. This is two dimensional array of characters.
First dimension specifies the maximum number of strings that the array can have and second
specifies the maximum characters that a sting can have.
An array of strings can be declared as:
char a[10][20];
This array can have 10 strings with each string containing maximum 20 characters.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
Page 39 of 74
faizi_+918137088810
{
int i,j,n;
char a[20][20],b[20];
printf(“Enter total number of names:”);
scanf(“%d”,&n);
printf(“Enter %d names”,n);
for(i =0;i<n;i++)
{
scanf(“%s”,a[i]);
}
printf(“original array is:”);
for(i =0;i<n;i++)
{
for(j =0;j<n-i-1;j++)
{
if(strcmp(a[j],a[j+1])>0)
{
strcpy(b,a[i]);
strcpy (a[j],a[j+1]);
strcpy(a[j+1],b);
}
}
}
printf(“sorted array \n ”);
for(i=0;i<n;i++)
{
printf(“%s”,a[i]);
}
getch();
}
Structure:
Structure is a collection of different types of elements. A single structure might contain integer,
float, double and character data.
Defining a structure:
struct tag
{
data type member1;
data type member2;
.
Page 40 of 74
faizi_+918137088810
.
data type member n;
};
struct is a keyword for structure, tag is the name of structure and member 1,member 2 is the
members of structure.
Defining a Structure Variable:
struct tag
{
data type member1;
data type member2;
.
.
data type member n;
} var;
var is the structure variable
Example:
struct record
{
char name [20];
int age;
char addr [20];
} rec;
name, age, addr are the members of this structure, rec is the structure variable.
Accessing Structure Members:
The members of a structure are processed individually, as separate entities. Therefore we
must be able to access the individual structure members.
A structure member can be accessed by writing
variable. member
where variable refers to the name of a structure type variable and member refers to the name
of a member within the structure. The dot (.) operator separates the variable name from
member name.
Example:
struct record
{
char name [20];
int age;
char addr [20];
} person;
Page 41 of 74
faizi_+918137088810
In this example, person is a structure variable of type record. if we want to access the person’s
name, we would write
person.name
Similarly person’s age and address
person. age person.addr
The members themselves are not variables. They should be linked to the structure variables in
order to make them meaningful members.
For example the word name has no meaning, where as the phrase ‘name of person’ has a
meaning. The link between a member and a variable is established using the dot (.) operator.
Example:
struct person
{
char name [20];
int age;
char addr [20];
} rec;
void main()
{
printf(“Enter values:”);
scanf(“%s %d %s”,rec.name,&rec.age,rec.addr);
printf(“%s %d %s”,rec.name,rec.age,rec.addr);
getch();
}
Array of Structures:
We can declare the array of structures where every element of array is structure type.
struct record
{
char name [20];
int age;
char addr [20];
} person[10];
Here person is an array of 10 elements and each element of person has 3 member elements
which are name, age and addr.
#include<stdio.h>
#include<conio.h>
struct student
Page 42 of 74
faizi_+918137088810
{
int rollno;
char name [10];
int age;
}std[10];
void main ()
{
int n,i;
printf(“enter the limit:”);
scanf(“%d”,&n);
printf(“enter details of students \n”);
for(i=0;i<n;i++)
{
printf(“Enter rollno”);
scanf(“%s”,&std[i].rollno);
printf(“Enter name:”);
scanf(“%s”,std[i].name);
printf(“Enter age:”);
scanf(“%d”,&std[i].age);
}
printf(“Details of students \n”);
for(i=0;i<n;i++)
{
printf(“\n roll no: %d name :%s age:%d”,std[i].rollno,std[i].name,std[i].age);
}
getch();
}
1) Write a program to enter the rollno, name and marks of students and to print the details of
students who scored more than 75.
#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name [10];
int mark;
}std[10];
void main ()
Page 43 of 74
faizi_+918137088810
{
int n,i;
printf(“Enter the limit:”);
scanf(“%d”,&n);
printf(“Enter details of students \n”);
for(i=0;i<n;i++)
{
printf(“Enter rollno”);
scanf(“%s”,&std[i].rollno);
printf(“Enter name:”);
scanf(“%s”,std[i].name);
printf(“Enter mark:”);
scanf(“%d”,&std[i].mark);
}
printf(“The students who have score more than 75 are \n”);
for(i=0;i<n;i++)
{
if(std[i].mark > = 75)
{
printf(“\n roll no: %d name :%s mark:%d”,std[i].rollno,std[i].name,std[i].mark);
}
}
getch();
}
2) Define the structure student with the following details rollno, name and marks. Read the
details of ‘n’ students and display this in the order of their marks
#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name [10];
int mark;
}std[10];
void main ()
{
int n,i,j,trn,t;
char tn[10];
printf(“Enter the number of students:”);
scanf(“%d”,&n);
Page 44 of 74
faizi_+918137088810
#include<stdio.h>
#include<conio.h>
struct student
Page 45 of 74
faizi_+918137088810
{
int rollno;
char name [10];
int age;
}s[10];
void main ()
{
int n,i,j,t,temp;
char tn[10];
printf(“Enter the number of students:”);
scanf(“%d”,&n);
printf(“Enter details of students \n”);
for(i=0;i<n;i++)
{
printf(“Enter rollno”);
scanf(“%s”,&s[i].rollno);
printf(“Enter name:”);
scanf(“%s”,s[i].name);
printf(“Enter age:”);
scanf(“%d”,&s[i].mark);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(s[i].name ,s[j].name) >0)
{
strcpy(tn, s[i].name);
strcpy(s[i].name, s[j].name);
strcpy(s[j].name, tn);
t = s[i].rollno;
s[i].rollno = s[j].rollno;
s[j].rollno = t;
temp = s[i].age;
s[i].age = s[i].age;
s[j].age = temp;
}}}
for(i=0;i<n;i++)
{
printf(“\n roll no: %d name :%s mark:%d”,std[i].rollno,std[i].name,std[i].age);
Page 46 of 74
faizi_+918137088810
}
getch();
}
Union:
Union is a collection of different types of elements. Union allocates memory for variable which
variable require more memory. Only one member of union can be accessed at anytime. Thus
the union is used for saving memory.
Syntax:
union union_name
{
datatype element 1;
datatype element 2;
----------
----------
datatype element n;
}union_var;
Example:
rollno name
struct student
{
int rollno;
char name [5]; 1000 1001 1002 1003 1004 1005 1006
};
name
union student
{
int rollno;
char name [5]; rollno
1002 1003 1004 1005 1006
};
In union student both name and rollno store the same memory location.
Access Members:
We can access the union members same as structure use the dot (.) operator.
variable. member
Page 47 of 74
faizi_+918137088810
structure union
1. We can access all the members of 1. Only one member of union can be
structure at anytime. accessed at anytime.
3. All members of structure can be 3. Only the first member of a union can
initialized be initialized.
Page 48 of 74
faizi_+918137088810
MODULE III
Functions:
A function is a self-contained block of program that performs a particular task.
Every C program consists of one or more functions
If a program contains multiple functions, their definitions may appear in any order, though
they must be independent of each other.
We can avoid rewriting of a group of codes by defining them within a function block and
use them by simply calling the function.
A function will process information that is passed to it from the calling portion of the
program and return a single value.
If the function does not require any arguments, an empty pair of parentheses must follow the
name of the function.
Page 49 of 74
faizi_+918137088810
If the function does not return anything, the function access appears by itself.
Example:
display (a, b);
If the function returns a value, the function access is often written as an assignment
statement.
Example:
f = factorial (n);
Function declaration:
The calling program should declare any function that is to be used later in the program. This is
known as the function declaration or function prototype. Function declarations are usually
written at the beginning of a program.
Syntax:
data type function_name (data type arg1, data type arg2 …);
Arguments:
Information is passed to the function via special identifiers are called arguments or
parameters.
Arguments are three types
Actual arguments
Formal arguments
Dummy arguments
Actual arguments:
The arguments appearing in the function call are referred to as actual arguments
Formal arguments:
The arguments appearing in the function definition are referred to as formal arguments
Dummy arguments:
The names of the arguments within the function prototype need not be declared elsewhere in the
program, since these are dummy argument names that are recognized only within the prototype.
Page 50 of 74
faizi_+918137088810
#include<stdio.h>
#include<conio.h>
void pass(int a[], int n);
void main()
{
int a[10],i,n;
printf(“Enter the limit:”);
scanf(“%d”,&n);
printf(“Enter %d elements”,n);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
pass(a,n);
printf(“Now the array elements are”);
Page 51 of 74
faizi_+918137088810
for(i=0;i<n;i++)
{
printf(“%d”,a[i]);
}
getch();
}
void pass(int a[], int n)
{
int i;
for(i=0;i<n;i++)
a[i] = a[i] *10;
}
Example: Two Dimensional Array passing to function. sort the names in alphabetical order using
function
#include<stdio.h>
#include<conio.h>
#include<string.h>
void sort (char [][25],int);
void main()
{
int i,n;
char a[100][25];
printf(“Enter total number of names:”);
scanf(“%d”,&n);
printf(“Enter %d names”,n);
for(i =0;i<n;i++)
{
scanf(“%s”,a[i]);
}
sort(a,n);
printf(“sorted array \n ”);
for(i=0;i<n;i++)
{
printf(“%s \n”,a[i]);
}
getch();
}
void sort (char [][25],int)
{
int i,j;
char x[25];
Page 52 of 74
faizi_+918137088810
for(i =0;i<n;i++)
{
for(j =0;j<n-i-1;j++)
{
if(strcmp(a[j],a[j+1])>0)
{ strcpy(x,a[i]);
strcpy
(a[j],a[j+1]);
strcpy(a[j+1],x);
}
}
}
}
Recursion:
Recursion is a process by which a function calls itself repeatedly, until some specified
condition has been satisfied.
For example consider factorial of a number, n
n! = n*(n-1)*(n-2)*...*2*1, and that 0! = 1.
factorial (3)
3 * factorial (2)
3 * 2 * factorial (1)
3 * 2 * 1 * factorial (0)
3*2*1*1
=> 6
#include<stdio.h>
#include<conio.h>
int factorial(int);
void main()
{
int n,f;
clrscr();
printf("Enter no");
scanf("%d",&n);
Page 53 of 74
faizi_+918137088810
f=factorial(n);
printf("Factorial = %d",f);
getch();
}
int factorial(int k)
{
int fact=1;
if(k>1)
fact=k*factorial(k-1);
return fact;
}
Macro:
Macro is a Preprocessor directive. It is a Single line abbreviation of group of statements.
#define statements are used to define macro.
Syntax:
Definition
#define macroname text
Call
macroname (arguments);
Page 54 of 74
faizi_+918137088810
Example:
#include<stdio.h>
#include<conio.h>
#define area length * breadth
void main()
{
int length, breadth;
printf (“Enter length and breadth:”);
scanf (“%d %d”,&length,&breadth);
printf (“Area = %d”, area);
getch ();
}
Quick Sort:
#include<stdio.h>
#include<conio.h>
int a [20];
void main ()
{
int i, n;
printf ("Enter the limit");
scanf ("%d", &n);
printf ("Enter the elements");
for (i=0; i<n; i++)
scanf ("%d",&a[i]);
qs (0, n-1);
printf ("Sorted array is: \n");
for (i=0; i<n; i++)
printf ("%d", a[i]);
getch ();
}
void qs (int n, int u)
{
int i;
if (u>=n)
{
i =split (n, u);
qs (n, i-1);
qs (i+1, u);
}
Page 55 of 74
faizi_+918137088810
}
int split (int n, int u)
{
int i, p, q, t;
p=n+1;
q=u;
i=a[l];
while (q>=p)
{
while (a[p] <i)
p++;
while (a[q]>i)
q--;
if (q>p)
{
t=a[p];
a[p] =a[q];
a[q] =t;
}
t=a[l];
a[l]=a[q];
a[q] =t;
}
return q;
}
Page 56 of 74
faizi_+918137088810
Module IV
Pointer:
Pointer is a variable that contains the address of another variable.
Declaration of pointer:
Data_type pointer-name;
Example:
int *p; here p is an integer type of pointer. Value at address contained in p is an integer.
a p
int a = 5;
5 1000
int *p;
p = &a;
1000 2000
a=5 &a = 1000
p = 1000 &p = 2000
*(&a) = 5 *p = 5
Call by value:
In call by value the values of the variables are passed. In this, values of variables are not
affected by changing the value of the formal parameter.
Example:
#include<stdio.h>
#include<conio.h>
void value (int, int);
void main()
{
int a= 5,b = 8;
printf(“Before calling function a & b are %d %d”,a,b);
value (a,b);
printf(“After calling function a & b are %d %d”,a,b);
getch();
}
Page 57 of 74
faizi_+918137088810
1000 2000
In function:
p q
5 8
4000 8000
After incrementing p and q:
P q
6 9
4000 8000
After calling function:
a b
5 8
1000 2000
Call by reference:
In call by reference, the addresses of the variables are passed. In this, values of variables are
affected by changing the value of the formal parameter.
Example:
#include<stdio.h>
#include<conio.h>
void ref (int *, int *);
void main()
Page 58 of 74
faizi_+918137088810
{
int a= 5,b = 8;
printf(“Before calling function a & b are %d %d”,a,b);
ref(&a,&b);
printf(“After calling function a & b are %d %d”,a,b);
getch();
}
void ref (int *p, int *q)
{
(*p)++;
(*q)++;
printf (“In function p & q are %d %d”,*p,*q);
}
Output:
Before calling function a & b are 5 8
After calling function a & b are 6 9
In function p & q 6 9
1000 2000
In function:
p q
1000 2000
4000 8000
P q
1000 2000
4000 8000
a b
6 9
1000 2000
Page 59 of 74
faizi_+918137088810
Page 60 of 74
faizi_+918137088810
Array of pointers:
Every element of this array can hold address of any variable. So we can say every element of
this array is a pointer variable. It is same as array but it contains the collection of addresses.
Example:
#include<stdio.h>
#include<conio.h>
void main ()
{
int *arr [3] ;
int a =5,b = 10, c= 15,i;
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;
for(i=0;i<3;i++)
{
printf(“Value = %d”,*(arr[i]));
printf(“Address = %u”,arr[i]);
}
getch ();
}
a b c
5 10 15
Pointer to Pointer:
It means a pointer to be pointing to another pointer.
Let’s suppose we have a pointer ‘p2’ that points to yet another pointer ‘p1’ that point to an
integer ‘a’.
int a = 5;
int *p1 = &a;
int **p2 = &p1; (p2 is a double pointer and hence the two *s in declaration)
Page 61 of 74
faizi_+918137088810
Pointer p2 holds the address of pointer p1. Pointer p1 holds the address of integer ‘a’.
Pointer to structure:
If the variable is of structure type then for accessing the starting address of the structure. We
must declare pointer for a structure variable. These pointers are called structure pointers.
struct record
{
char name [10];
int age;
int salary;
}data,*ptr;
ptr = &data;
data is a structure variable and ptr is a structure pointer that points to the starting address of
structure variable data.
ptr
1000
Page 62 of 74
faizi_+918137088810
There are two ways of accessing the member of structure through the structure pointer
ptr -> age;
(*ptr) .age; (parenthesis is necessary because the dot operator has higher precedence
than * operator)
#include<stdio.h>
#include<conio.h>
struct record
{
char name [10];
int age;
int salary;
}data,*ptr = &data;
void main()
{
printf(“Enter name:”);
scanf(“%s”,ptr -> name);
printf(“Enter age:”);
scanf(“%d”,&ptr ->age);
printf(“Enter salary:”);
scanf(“%d”,&ptr ->salary);
printf(“name: %s age %d salary %d”,ptr ->name,ptr ->age,ptr ->salary);
getch();
}
Find largest and smallest element in an array using pointers
#include <stdio.h>
void main()
{
int a[100],n,i,l,s;
int *p=a;
printf("Enter Limit: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter No. %d: ",i+1);
scanf("%d",&a[i]);
}
l=*p;
s=*p;
for(i=1;i<n;i++)
Page 63 of 74
faizi_+918137088810
{
if(*(p+i)>l)
{
l=*(p+i);
}
if(*(p+i)<s)
{
s=*(p+i);
}
}
printf("Largest Number : %d",l);
printf("Smallest Number: %d",s);
getch();
A structure may have a member whose is same as that of a structure itself. Such structures are
called self-referential. Self-referential Structure is used in data structure such as binary tree,
linked list, stack, Queue etc.
Syntax:
struct tag
};
struct node
int value;
};
Page 64 of 74
faizi_+918137088810
Linked List:
A linked list is a linear collection of data elements, called nodes. Each node is divided into two
parts:
Page 65 of 74
faizi_+918137088810
Parentheses of main function may contain special arguments that allow parameters to be
passed to main from the operating system. Such arguments are called argc and argv.
argv – array of strings. Each string in this array will represent a parameter that is passed to
main.
{…………
In order to pass one or more parameters to the program when it is executed from the operating
system, the parameters must follow the program name on the command line.
Example:
#include<stdio.h>
int i;
printf(“argc = %d”,argc);
for(i=0;i<argc;i++)
printf(“argv[%d]=%s”,i,argv[i]);
10
Page 66 of 74
faizi_+918137088810
MODULE V
Files:
File is a place in the disk where a group of related data is stored. When large volumes of data
are to be handled, it is necessary that data are to be stored on disk and read whenever necessary.
Advantages of using data files:
The data is safely kept for any future use and modification.
When large amount of data is to be processed, data is taken from the secondary storage
and processed.
Different types of files:
There are two types of data files.
Binary file
Text file
Opening a file:
Opening a file consists of two steps.
Allocating a buffer area
Allocating a name
Allocating a buffer area:
When working with a data file, the first step is to establish a buffer area, where information is
temporarily stored while being transferred between the computer’s memory and the data file.
The buffer area is established by writing
FILE *ptr_variable;
Where FILE is a special structure type that establishes the buffer area. Pointer variable
indicates the beginning of the buffer area. The structure type FILE is defined in stdio.h.
Example:
FILE *p;
Allocating a name:
A data file must be opened before it can be processed or created. This associates the file name
with the buffer area. It also specifies how the data file will be utilized, that is a read only file, a
write only file, or a read/write file, in which both operations are permitted.
fopen ( ) – The fopen ( ) function is used to open a file to be used. The return value of the
function is a FILE pointer that refers to the memory address of the file. A NULL value is
returned, if the file cannot be opened.
Example:
ptr = fopen (“file name”, “file type”);
where file name and file type are strings that represents the name of the data file and the
manner in which the data file will be utilized.
File type specifications:
“r” Opening an existing file for reading only.
“w” Open a new file for writing only. If a file with the specified filename
currently exists, it will be destroyed and a new file created in its place.
Page 67 of 74
faizi_+918137088810
“a” Open an existing file for appending. A new file will be created if the
file with the specified filename does not exist.
“r+” Opening an existing file for reading and writing.
“w+” Open a new file for both writing and reading
“a+” Open an existing file for reading and appending. A new file will be
created if the file with the specified filename does not exist.
putc() – This function writes a single character to the file. It takes two arguments, first the
character and second the file pointer.
Syntax:
putc (variable,filepointer);
Example:
#include<stdio.h>
void main()
{
FILE *p;
char c;
p = fopen(“sample.dat”,”w”);
do
{
c=getchar();
putc(c,p);
}while(c!=’\n’);
fclose(p);
}
Page 68 of 74
faizi_+918137088810
fputc() - This function writes a single character to the buffer. The data in buffer is written to
the file if the buffer is full or writing data to the buffer is finished. It takes two arguments, first
the character and second the file pointer.
Syntax:
fputc (variable,filepointer);
Example:
#include<stdio.h>
void main()
{
FILE *p;
char c;
p = fopen(“sample.dat”,”w”);
do
{
c=getchar();
fputc(c,p);
}while(c!=’\n’);
fclose(p);
}
fprintf() – This function writes formatted data to the file.
Syntax:
fprintf (filepointer,”control string”,arg1,arg2…);
Example:
void main()
{
FILE *p;
char c[] = “This is an array”;
int value = 10;
float f=5.6;
p=fopen(“sample.txt”,”w”);
fprintf(p,”%s %d %f”,c,value,f);
fclose(p);
getch();
}
Reading from a file:
To read data from a file, we will open the file in read mode.
FILE *p;
P= fopen (“abc.dat”,”r”);
Now to read data from the above opened file, we can use the following functions.
getc()
Page 69 of 74
faizi_+918137088810
fgetc()
fscanf()
getc() – This function reads one character at a time from the file. It takes one argument that is
the file pointer.
Syntax:
variable = getc(file_pointer);
Example:
#include<stdio.h>
void main()
{
FILE *p;
char c;
p = fopen(“sample.txt”,”r”);
if(p = =NULL)
{
printf(“Error: can’t open the file”);
}
else
{
do
{
c=getc(p);
putch(c);
}while(c!=EOF);
}
fclose(p);
getch();
}
fgetc() – This function reads one character at a time from the file with the help of file pointer.
It takes one argument that is the file pointer.
Syntax:
variable = fgetc(file_pointer);
Example:
#include<stdio.h>
void main()
{
FILE *p;
char c;
p = fopen(“sample.txt”,”r”);
if(p = =NULL)
Page 70 of 74
faizi_+918137088810
{
printf(“Error: can’t open the file”);
}
else
{
do
{c=fgetc(p);
putch(c);
}while(c!=EOF);
}
fclose(p);
getch();
}
fscanf() – This function reads formatted data from the file.
Syntax:
fscanf (filepointer,”control string”,&arg1,&arg2…);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *p;
char name[10];
int i,age,mark;
clrscr();
p=fopen("text1.txt","w");
for(i=1;i<=3;i++)
{
printf("Enter details:");
scanf("%s %d %d",name,&age,&mark);
fprintf(p,"%s %d %d",name,age,mark);
}
fclose(p);
p=fopen("text1.txt","r");
for(i=1;i<=3;i++)
{
fscanf(p,"%s %d %d",name,&age,&mark);
printf("%s %d %d",name,age,mark);
}
fclose(p);
Page 71 of 74
faizi_+918137088810
getch();
}
Read a line of lower case text and store in uppercase within a file
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *p;
char c;
p=fopen("sample.txt","w");
do
{
c=getchar();
putc(toupper(c),p);
}while(c!='\n');
fclose(p);
getch();
}
Page 72 of 74
faizi_+918137088810
f2=fopen("second.dat","r");
f3=fopen("merge.dat","w");
while(!feof(f1))
{ s=getc(f1);
putc(s,f3);
}
while(!feof(f2))
{ s=getc(f2);
putc(s,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
f3=fopen("merge.dat","r");
printf("Merged data \n ");
while(!feof(f3))
{ s=getc(f3);
printf("%c",s);
}
fclose(f3);
getch();
}
Bitwise Operators:
Operators that allow bitwise operators are called bitwise operators. Bitwise operators can be
classified into three categories.
One’s complement operator
Bitwise OR
Bitwise XOR
Page 73 of 74
faizi_+918137088810
Page 74 of 74