C Programming PDF
C Programming PDF
Module(1&2) e-notes
What is a Computer?
• Computer
– Device capable of performing computations and making logical decisions
– Computers process the data under the control of sets of instructions called
n
computer programs
Computer Consists of two parts they are Hardware and Software
•
tio
Hardware
– Various devices comprising a computer
– Keyboard, screen, mouse, disks, memory, CD-ROM, and processing units, mother
board etc..
• Software
– Programs that run on a computer
lu
Typical structure of a computer looks like
So
U
Instruction phase
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
Naturally a language is the source of communication between two persons, and also
between person to machine like computer. The languages we can use to
tio
communicate with the computer are known as Computer programming languages.
Generally there are three major types of languages are available and as follows:
1. Machine languages
• Strings of numbers giving machine specific instructions
• Example:
+1300042774
2. Assembly languages
+1400593419
+1200274027 lu
• English-like abbreviations representing elementary computer
So
operations (translated via assemblers)
• Example:
Load BASic
Add Basic,da,gross
Move gross,total
easy to understand.
• Code is similar to everyday use of English sentence
• Use mathematical notations (translated via compilers)
• Example:
VT
Totalsal = basic + da
“High-level” is a relative term, C programming language is a relatively low-level and also
high-level language. Pascal, Fortran, COBOL, Java etc are typical examples for high-level
languages. Application specific languages are Matlab, Javascript, VBScript etc.
What is Programming ?
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
• Computers are based on the stored program concept given by Von Neumann. It consists of
Central Processing Unit(CPU) main memory, input output devices, ports, buses etc.,
• Actions performed by CPU are written through program. Hence Program is a sequence of
instructions.
n
tio
lu
Tools such as flowcharts, Algorithm and pseudocodes are used to develop program
So
Pseudocodes:
Since each programming language uses a unique syntax structure, understanding the code
of multiple languages can be difficult. Pseudocode helps this problem by using
conventional syntax and basic English phrases that are universally understood
Pseudocode is an informal program description that does not contain code syntax or
U
Example
• Algorithm:
It is an effective step-by-step procedure to perform the solution to a given problem.
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
It can be expressed using notations. Natural language like English is used to write these
steps.
• Flowcharts:
• It is a diagram showing a sequence of activities to be performed for the solution of a
problem.
• A set of conventional symbols are used to draw flowcharts
n
• Graphically depicts the logical steps to carry out a task and shows how the steps relate to
each other.
• An organized combination of shapes, lines, and text that graphically illustrates a process or
tio
structure
• Flowchart is a pictorial representation showing all the steps of a process
Some of the symbols used do design flowcharts are
lu
So
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
1.
n
tio
lu
So
U
VT
2.
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
Get the next Grade
tio
Increment the Counter
Loop
Display Average
Flowchart representation lu
So
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
tio
•
ALGOL 60 (1960
C is a general-purpose language which has been closely associated with the UNIX OS for
which it was developed - since the system and most of the programs are written in C.
U
C Standards
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
C was invented to write operating system called UNIX
The language was formalized by American National Standard Institute
(ANSI) 1988
tio
Unix is written using C
C is widely used to develop system softwares
C is a case sensitive program
Compilation Model: lu
So
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
cc program.c
n
If you don’t like this name, choose another using the –o option:
cc program.c –o exciting_executable
tio
Compilation process in Turbo C environment:
To type c Program: click File -> open -> noname.cpp is created (cpp stands for c plus plus)
lu
So
U
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
tio
lu
Output of the program will be displayed as shown below:
So
U
Pre-processor directives(#include..)
int main()
Declaration statements;
executable statements;
return 0;
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example Programs:
1.
#include <stdio.h>
Int main() {
n
printf ("Hello C world!");
tio
return 0;
Header files: lu
• The files that are specified in the include section is called as header file
So
• These are precompiled files that has some functions defined in them
main ()
• This is the entry point of a program
• From main function the flow goes as per the programmers instructions.
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
– // (double slash)
n
/*….
tio
…….*/
%d (print as integer),
%f (print as floating-point)
– \n indicates a newline character
Example: printf( "Original input : %s\n", input );
VT
Example program:
#include <stdio.h>
// program prints a number of type int
int main() {
int number = 10;
printf (“The Number is %d”, number);
return 0;
}
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
scanf(“%d”, &a);
n
Some of the format specifier
tio
%d for The integer format specifier.
%f for The floating-point format specifier.
%s for The string format specifier.
Example:
• Input
scanf(“%d”,&a);
lu
So
Gets an integer value from the user and stores it under the name “a”
• Output
printf(“%d”,a);
Prints the value present in variable a on the screen
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Variables:
Variables are data that will keep on changing
Declaration
int a;
Initialization
n
<<varname>>=<<value>>;
a=10;
tio
Usage (updation)
<<varname>>
•
lu
Should not be a reserved words like int, float, sin etc..
– Choose a name that reflects the role of the variable in a program, e.g.
• The value of a variable can change; A constant always has the same value
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Tokens:
• Token is a sequence of one or more characters that is significant as a group
n
Constants: integer, floating and character example: 10,10.0
tio
Operators: arithmetic, relational, logical example: < ,==, !=,&&,||
•
Data type size and its range
Primary : int, float, char
lu
– int (signed/unsigned)(2,4Bytes): used to store integers.
– char (signed/unsigned)(1Byte): used to store characters
So
– float, double(4,8Bytes): used to store a decimal number.
• User Defined:
– typedef: used to rename a data type
• typedef int integer; can use integer to declare an int.
– enum, struct, union
Unsigned: 0 to 255
VT
Unsigned: 0 to 65535
Double double 8
precision
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Constants
• Constant is a quantity whose value cannot be changed during program execution.
Integer Constant
n
• Represents a signed integer of typically 2 or 4 or 8 bytes (16 or 32 or 64 bits)
tio
• It is a number that has an integer value.
example: 5, 125,
•
Floating Constant
lu
Floating constant have matissa and exponent part(optional includes the letter e or E)
So
ddd.dddE(+/-)dd
453.678
Character Constant
• It is grouped into two categories: integer character, wide character
U
• The character within the single quote may be any character (except backslash or
newline or single quote)
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
• Comments are ignored by the compiler
tio
Invisible Characters in C language
• Some special characters are not visible directly in the output stream. These all begin
with an escape character (i.e. \);
– \n newline
– \t horizontal tab
– \a alert bell
lu
So
– \v vertical tab
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Conditional operators
Bitwise operators
n
Relational operators
tio
Logical operators
Assignment operators
Special operators
lu
So
1. Arithmetic Operator: arithmetic operations are performed
on integer or floating point data i.e.
Integer Arithmetic
Operands in a single arithmetic expression
Operation is integer arithmetic
U
a%b=2
Real Arithmetic :
x=6.0/7.0=0.857143
y=-2.0/3.0=-0.666667
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
For example
19/10.0=1.9
Assignment Operator:
In addition, C has a set of shorthand assignment operators of the form.
n
var oper = exp;
Example
tio
x=a+b
Simple Programs
#include<stdio.h>
int main()
lu
1. Write a program to calculate area of triangle
So
{ int len,bre,area;
scanf(“%d%d”,&len,&bre);
area=0.5*len*bre;
printf(“\narea of triangle=%d”,area);
U
return 0;
}
VT
OUT PUT
area of triangle=10
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
#define pi 3.14
int main()
int r;
n
float area;
tio
printf(“ enter radius of the circle\n”);
scanf(“%d”,&r);
area= pi * r * r;
}
return 0;
lu
So
#include<stdio.h>
#define pi 3.14
VT
int main()
int r;
float area,peri;
scanf(“%d”,&r);
area= pi * r * r;
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
peri = 2*pi*r;
return 0;
n
tio
4. Write a program to calculate simple interest
#include<stdio.h>
int main()
{ int p;
float r,t,interest,total;
lu
So
printf(“ enter principal amount “);
scanf(“%d”,&p);
scanf(“%f%f”,&r,&t);
interest=(p*r*t)/100.0;
U
total=p+interest;
return 0;
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
In order to calculate mathematical values of sin(), cos(),exp() etc. C language provides built-in
library functions.
• Library facilities are usually provided in the languages to keep the language simple and to do
many mathematical calculations.
n
input/output facility <stdio.h> (scanf,printf,gets,puts….)
tio
string manipulation oper <string.h>(strcpy,strcat,strlen..)
ex:
•
#include<math.h> lu
This header file gives many built in mathematical library functions such as trigonometric,
logarithmic, exponential etc..
So
Function Name C function call meaning
exponential exp(x)
log10 log10(x)
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
tio
lu
So
1. Program to calculate area of triangle when sides of triangle is given
#include<stdio.h>
int main()
{ int a,b,c;
U
float area,s;
printf(“ enter three sides length of a triangle”);
scanf(“%d%d%d”,&a,&b,&c);
s=(a+b+c)/2.0
area=sqrt(s * (s-a)* (s-b) * (s-c));
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Relational Operator: In order to find the relation between any two values relational operator are
used for example a is greater than b, result may be true or false depends on the value of a and
b, some of the relational operators are:
n
tio
Control Statements :
The order in which the statements are executed are called control flow
called control statements
lu
The statements that are used to control the flow of execution of program are
If Statement:
Branching is the process of choosing the right branch for execution, depending on the
result of “conditional statement”.
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
tio
1. Write a Program to find biggest among two numbers
#include <stdio.h>
int main()
{
int a, b;
printf( “ enter two numbers:”);
scanf(“%d%d”,&a,&b);
lu
if (a>b) printf(“ a is the biggest number”);
if (b>a) printf(“ b is the biggest number”);
if (a==b) printf (“ a and b are equal”);
So
return 0;
}
U
2. If –else statement:
VT
Unlike “if statement” where you could only specify code for when condition is true; for “if
else statement” you can also specify code for when the condition is not True (false)
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
#include <stdio.h>
int main()
{ int a, b;
printf( “ enter two numbers:”);
scanf(“%d%d”,&a,&b);
if (a>b) printf(“ a is the biggest number”);
else printf(“ b is the biggest number”);
n
return 0;
}
tio
3. Nested- if statement:
lu
So
Using “if…else statement” within another “if…else statement” is called ‘nested if
statement’.
“Nested if statements” is mainly used to test multiple conditions
The if-else constructs can be nested (placed one within another) to any depth.
General forms: if-if-else and if-else-if.
The if-if-else constructs has the following form (3 level of depth example
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
Program to find biggest among two numbers using nested-if statement:
tio
#include <stdio.h>
int main()
{ int a, b;
printf( “ enter two numbers:”);
scanf(“%d%d”,&a,&b);
if (a>b) printf(“ a is the biggest number”);
}
lu
else if (b>a) printf(“ b is the biggest number”);
else printf(“ a and b are equal”);
return 0;
So
U
4. Logical Operator
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Inputs and or
a b a&b a|b
0 0 0 0
0 1 0 1
n
1 0 0 1
1 1 1 1
tio
1. Program to find quadrant for the given co-ordinates
#include<stdio.h>
int main();
{
int x,y;
lu
printf(“Enter the coordinates for quadrants:”);
scanf(“%d%d”,&x,&y);
if(x>0 && y>0) printf(“the co-ordinate lies on 1st quadrant”);
So
else if(x<0 && y>0) printf(“the co-ordinate lies in 2nd quadrant”);
else if(x<0 && y<0) printf(“the co-ordinate lies in 3rd quadrant”);
else ïf(x>0 && y<0) printf(“the co-ordinate lies in 4th quadrant”);
else if(x==0 && y==0) printf(“the co-ordinate is on origin”);
else if(x==0) printf(“the co-ordinate lies in y-axis”);
else printf(“the co-ordinate lies in x-axis”);
}
U
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
int main()
{
int s1,s2,s3;
float avg;
printf( “enter 3 subject marks”);
scanf(“%d%d%d”,&s1,&s2,&s3);
avg=(s1+s2+s3)/3.0;
if ( (s1<35)||(s2<35)||(s3<35)) printf(“ fail”);
n
else if (avg>=70) printf(“ Distinction”);
else if ((avg>=60) && (avg < 70)) printf(“ First class”);
else if ((avg>=50) &&(avg < 60)) printf(“ Second class”);
tio
else printf (“ pass class”);
return 0;
}
lu
So
• Quadratic equation of the form ax^2+bx+c=0 is having two roots. Root is a value of x when it
is substituted to the above equation it satisfies(i.e. LHS=RHS (F(X)=y=0))
VT
• Root is a point on the x-axis where y=0. In quadratic equation it cuts x-axis at two points. (i.e.
two roots)
• Root value depends on the discriminant value(b^2-4ac)
• If discriminant is zero -- roots are equal (i.e. r1=r2)
• If discriminant is greater than zero – roots are distinct
• If discriminant is less than zero – roots are imaginary
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
#include<stdio.h>
#include<math.h>
int main()
{ float a,b,c;
float d,r1,r2,re,ri;
printf(“enter the co-efficients”);
scanf(“%f%f%f”,&a,&b,&c);
d=b*b-4*a*c;
if (d==0){
r1=-b/(2*a);
n
printf(“roots are real and equal”)
printf(“root1=%f\t root2=%f”,r1,r1);
}
else if (d>0){
tio
r1=-b+sqrt(d)/(2*a);
r2=-b-sqrt(d)/(2*a);
printf(“roots are distinct\n”);
printf(“root1=%f\t root2=%f”,r1,r2);
}
else {
re=-b/(2*a);
ri=sqrt(abs(d))/(2*a);
printf(“roots are complex conjugates\n”);
printf(“real part=%f\t img part=%f”,re,ri);
}
lu
So
return 0;
}
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
2. Program to check whether the given year is Leap year or not (Lab Program)
n
else
print “ given year is not a leap year”
End of the algorithm
tio
(((year%4==0) &&(year%100 != 0)) || year%400 == 0)
• #include<stdio.h>
int main()
{
int year;
printf(“enter the year”);
scanf(“%d”,&year);
lu
if(((year%4==0) &&(year%100 != 0)) || year%400 == 0)
printf(“given year %d is leap year”,year);
So
else printf (“given year %d is not a leap year”,year);
return 0;
}
U
VT
Arithmetic Operators:
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
» int a=5;
» b=a++; //value of b=5; a=6;
• Modulus (remainder): %
– example:
» 12%5 = 2;
» Assignment by addition: +=
– example:
» int a=4;
n
» a+=1; //(means a=a+1) value of a becomes 5
We Can use -, /, *, % also
• Comparison Operators: <, > , <=, >= , !=, ==, !,
tio
&&, || .
– example:
» int a=4, b=5;
» a<b returns a true(non zero number) value.
» Bitwise Operators: <<, >>, ~, &, | ,^ .
•
– example
Meaning of a + b * c ?
» int a=8; lu
» a= a>>1; // value of a becomes 4
So
is it a+(b*c) or (a+b)*c ?
• All operators have precedence over each other
• *, / have more precedence over +, - .
– If both *, / are used, associativity comes into picture. (more on
this later)
– example :
» 5+4*3 = 5+12= 17.
U
++ -- (Postfix)
++ -- (Prefix)
* / %
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
+ -
<< >>
< >
&
n
&&
tio
||
Switch Statement:
lu
Switch
statement begins with switch keyword. It is the
combination of multiple cases separated by break statement. Only one case will
So
be executed at any time and break statement takes the control outside the switch
statement. If there is no match for the case statement default statement will be
executed.
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
#include<stdio.h>
int main()
{
float a,b,c;
n
char op;
printf(“Enter the expression in the form of a op b: “);
Scanf(“%f %c %f”,&a,op,&b);
tio
switch(op)
{
case ‘+’ : c=a+b;
break;
case ‘-’ : c=a-b;
case ‘*’ :
case ‘x’ :
break;
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
#include<stdio.h>
int main()
{
float a,b,area;
n
int choice;
printf(“Enter the choice(1:square,2:rectangle:3:circle “));
scanf(“%d”,&choice);
tio
switch(choice)
{
case 1 : printf(“enter side length”);
scanf(“%f”,&a);
area=a*a;
break;
breadth”);
scanf(“%f%f”,&a,&b);
area=a*b;
lu
case 2 : printf(“enter length and
So
case 3 : printf(“enter the radius”)
scanf(“%f”,&a)
area=3.14*a*a;
break;
default: printf(ïn valid choice”);
break;
}
printf(“ area=%f\n”,area);
U
return 0;
}
While LOOP : It executes the statement with in the loop until the
VT
condition is satisfied.
while (condition)
statement(s);
next_statement;
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
tio
lu
So
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
// increment by 1, repeats
n++;
}
// a newline
printf("\n");
return 0;
}
Output:
n
tio
// simple while loop example
#include <stdio.h>
int main(void)
{
int n = 1,sum=0;
// set the while condition
while(n <= 50)
lu
So
{
sum=sum+n;
// increment n by 1, repeats
n++;
}
// a newline
printf(“sum upto 1 to 50 is =%d“,sum);
return 0;
}
U
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
• Let m and n represent two numbers and variable r represent remainder of the division
r=m%n
Algoritm GCD(m,n)
n
read (m,n)
while(n>o)
{ r= m % n;
tio
m = n;
n= r;
}
print(“gcd of m and n is”, m)
#include<stdio.h>
int main()
{
int m,n,r;
lu
printf(“enter two integer number”);
scanf(“%d%d”,&m,&n);
while(n > 0)
So
{ r=m%n;
m=n;
n=r;
}
printf(“GCD of m and n is :%d”, m);
return 0;
}
U
step m n m%n
1 50 35 15
VT
2 35 15 5
3 15 5 0
4 5 0(s)
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
Do-While Loop: This statement is used when we want to execute
the body of the loop at least once.
tio
do
statement(s);
while (condition)
next_statement;
lu
Executes a block of statements as long as a specified condition is true at least once.
So
Test the condition at the end of the loop rather than at the beginning, as
demonstrated by the for and while loops.
(condition) can be any valid C expression.
When the program encounter the do-while loop, the following events occur:
The statement(s) are executed.
The (condition) is evaluated. If it is TRUE, execution returns to step number
1. If it is FALSE, the loop terminates and the next_statement is executed.
U
This means the statement(s) in the do-while will be executed at least once.
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
tio
#include <stdio.h>
main()
{
int i = 10;
do{
}
printf("Hello %d\n", i );
i = i -1;
}while ( i > 0 );
lu
So
Output:
Hello 10
Hello 9
Hello 8
Hello 7
Hello 6
Hello 5
Hello 4
U
Hello 3
Hello 2
Hello 1
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
#include<stdio.h>
int main()
{
int num,rev=0,temp;
printf("Enter a number: ");
scanf("%d",&num);
temp=num;
while(num!=0){
digit=num%10;
n
num=num/10;
rev=rev*10+digit;
}
if(rev==temp)
tio
printf("%d is palindrome",temp);
else
printf("%d is not a palindrome",temp);
return 0;
num digit
lu rev
So
3467 0
3467 7 7
346 6 76
34 4 764
U
3 3 7643
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
tio
#include<stdio.h>
int main()
{
int num,r,sum=0,temp;
printf("Enter a number: ");
scanf("%d",&num);
temp=num;
lu
So
while(num!=0){
r=num%10;
num=num/10;
sum=sum+(r*r*r);
}
if(sum==temp)
printf("%d is an Armstrong number",temp);
else
U
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
For statement:
• for loop is used for repetitive execution of a statement or group of statements.
for(initial_expr; final_expr; update_expr)
{
statements;
}
example:
for(i=1; i<=10; i++)
n
{
sum= sum+i;
}
tio
lu
So
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
0.1 0.01
0.3 0.09
0.5 0.25
0.7 0.49
0.9 0.81
Algorithm fact
n
read n
fact=1
for i=n down to 2
tio
fact= fact*I
print (fact)
end
lu
So
U
The for statement(s) can be followed by a null (empty) statement, so that task is done in the
for loop itself.
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
nsum = 0;
tio
nsum = nsum + irow;
The above program segment will compute and display the sum of the first 20 natural numbers
•
Example:
for(i=1;i<=2,i++)
lu
So
• { for(j=1; j<=3;j++)
• c=i*j;
• }
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
tio
• Write a program to print the below structure using “*”
*
* *
* * *
* * * *
lu
So
#include <stdio.h>
#include <conio.h>
void main()
{
int I,j;
for( i=1; i<=4;i++)
{ for (j=1; j<=i; j++)
U
{
printf(“*\t”);
}
VT
printf(“\n”);
}
getch();
}
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
void main()
{
int I,j;
tio
for( i=4; i>=1;--i)
{ for (j=1; j<=i; ++j)
{
printf(“*\t”);
}
}
printf(“\n”);
lu
So
getch();
}
Continue statement:
continue keyword forces the next iteration to take place immediately,
skipping any instructions that may follow it.
U
The continue statement can only be used inside a loop (for, do-while
and while) and not inside a switch-case selection.
When executed, it transfers control to the condition (the expression
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
{
int inum;
for(inum = 1; inum <= 10; inum++)
{
// skip remaining code in loop only if iNum == 5
if(inum == 5)
continue;
n
printf("%d ", iNum);
}
printf("\nUsed continue to skip printing the value 5\n");
tio
return 0;
lu
So
Goto Statement:
when a goto statement is came across, the branching does not depend
on any condition.
A goto statement and its target label must be located in the same
function, although they can be in different blocks.
Use goto to transfer execution both into and out of loop.
However, using goto statement strongly not recommended.
Always use other C branching statements.
When program execution branches with a goto statement, no record is
kept of where the execution is coming from.
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example:
#include <stdio.h>
int main () {
/* local variable definition */
n
int a = 10;
/* do loop execution */
LOOP:do {
tio
if( a == 15) {
/* skip the iteration */
a = a + 1;
}
goto LOOP;
lu
So
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
U
Output:
VT
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
value of a: 19
#include<stdio.h>
#include<conio.h>
void main()
n
{ int n,I,r;
scanf(“%d”,&n)
for (i=2; i<=n/2;i++)
tio
{ r= n % i ;
if ( r== 0) {
printf (“given number is not prime”);
getch();
exit(0);
}
}
lu
printf(“ given number is prime”);
getch();
return 0;
So
Remarks: if we check the number up to half of the given number whether it is divisible or
not is enough.
if (a>b)
x=a;
else
x=b;
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
• The ? : operator is just like an if ... else statement except that because it is an operator you
can use it within expressions.
• ? : is a ternary operator in that it takes three values, this is the only ternary operator C has.
• ? : takes the following form:
if condition is true ? then X return value : otherwise Y value;
#include <stdio.h>
main()
n
{
int a , b;
a = 10;
tio
printf( "Value of b is %d\n", (a == 1) ? 20: 30 );
printf( "Value of b is %d\n", (a == 10) ? 20: 30 );
}
Output:
Value of b is 30
Value of b is 20
lu
So
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
tio
Break statement:
•
lu
The break statement in C programming has the following two usages −
When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement.
So
If you are using nested loops, the break statement will stop the execution of the innermost
loop and start executing the next line of code after the block.
#include <stdio.h>
int main () {
int a = 10;
U
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
VT
value of a: 10
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
2. Bitwise operator
n
• It takes the operand as string of bits
• Bit operations are carried out on the data
tio
& bitwise AND operator
| bitwise OR operator
~ NOT operator
<< left shift operator
>> right shift operator
• X=4
x= x<<3
64
lu
32 16 8 4 2 1
So
0 0 0 0 1 0 0
First 0 0 0 1 0 0 0
shift
Second 0 0 1 0 0 0 0
U
shift
Third 0 1 0 0 0 0 0
shift
VT
Answer x= 32
• X=96
x= x>>3
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
64 32 16 8 4 2
98 1 1 0 0 0 0
First 0 1 1 0 0 0
n
shift(48)
Second 0 0 1 1 0 0
shift(24)
tio
Third 0 0 0 1 1 0
shift
(12)
Answer x= 12 lu
So
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Type Casting:
n
tio
lu
So
U
VT
3. Special operator
Comma operator: combines multiple expressions into single expression. The value of
right most expression is assigned to left expression
x=(a=4,b=5,c=2,c+a*b);
x=22
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
float r= 12.45;
int y;
n
y=sizeof(r);
tio
Formatted output statement:
a= 14
printf(“%d”, a) → 14
printf(“%4d”,a) → bb14
printf(“%4.3d”,a) → b014
printf(“%-4d”,a) → 14bb
printf(“%-4.3d”,a) → 014b
lu
So
Note:
b -> stands for blank
float a= 10.437
printf(“%f”,a) → 10.437000( it provides 6 digit
after decimal point)
printf(“%w.df”,a)
w-> number of columns for integer part
U
• getchar() -> used to read single character at run time. Given value is displayed on the screen
and the compiler wait for another character to be typed.
• getche()-> it is used to get a character from console and echoes to the screen. The given
value is displayed on the screen and the compiler does not wait for another character to be
typed
• getch() -> is used to get a character from console but does not echo to the screen.
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Exercises:
• What is a variable and constant? List the rules to be followed while declaring a variable.
• What are data types? List the data types available in C programming language
• List and explain with appropriate example the various operators used in c language.
• Compare while loop with do-while loop of C programming language.
• Write a program to exchange (swap) two numbers.
• Write a program to check the given number is prime or not
n
• Write a program to generate fabinocci series
1 1 2 3 5 8 13 ……..
tio
lu
So
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
MODULE III
ARRAYS, STRINGS AND FUNCTIONS
ARRAYS AND STRINGS: Using an array, Using arrays with Functions, Multi-Dimensional
arrays. String: Declaring, Initializing, Printing and reading strings, strings manipulation functions,
n
strings input and output functions, arrays of strings, programming examples and Exercises.
Text 1: 5.7 Text 2: 7.3, 7.4 Chapter 9
tio
FUNCTIONS: Functions in C, Argument Passing – call by value, Functions and program structure,
location of functions, void and parameter less Functions, Recursion, programming examples and
exercises. Text 1: 1.7, 1.8, Chapter 4 Text 2: 5.1 to 5.4 10 Hours
TEXT BOOK:
1. Brain W. Kernighan, Dennis M. Richie: The C programming Language, 2nd Edition, PHI, 2012.
lu
2. Jacqueline Jones & Keith Harrow: Problem Solving with C, 1st Edition, Pearson 2011.
So
Notes Prepared By:
Manjunatha P C
Sr.Asst.Professor
Dept.Of CSE
REVA ITM
Bengaluru - 64
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
#include <stdio.h>
int main ()
n
{
float temp1,temp2,temp3,temp4,temp5,temp6,temp7;
float avg;
tio
printf("Enter Day-1 Temperature: "); scanf(“%f”,&temp1);
printf("Enter Day-2 Temperature: "); scanf(“%f”,&temp2);
printf("Enter Day-3 Temperature: "); scanf(“%f”,&temp3);
printf("Enter Day-4 Temperature: "); scanf(“%f”,&temp4);
printf("Enter Day-5 Temperature: "); scanf(“%f”,&temp5);
printf("Enter Day-6 Temperature: "); scanf(“%f”,&temp6);
printf("Enter Day-7 Temperature: "); scanf(“%f”,&temp7);
} lu
avg = (temp1 + temp2 + temp3 + temp4 + temp5 + temp6 + temp7) / 7;
printf(“Average Temperature of a Week = %f ", avg);
return 0;
So
It was simple, because we had to store just 7 floating point numbers. Now let's assume we have to
compute average temperature of an year , so what is next? Are we going to use 365 variables?
Thus we can conclude here that:
To handle such situation, C language provides a concept called the arrays. These are the situations,
U
where we need to have logical collection of values of same type in Programming. Few more
examples are:
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
ARRAY
n
2) Multi dimensional array
tio
A single dimensional array is a linear list consisting of related elements of same type. In
memory, all the elements are stored in continuous memory-location one after the other.
data_type array_name[array_size];
where
lu
data_type can be int, float, char or any valid built-in or user defined data type
array_name is any valid identifier i.e name of the array
array_size indicates number of elements in the array, it can be any valid integer expression.
So
For example:
int marks[100];
float temperature[365];
char name[60]
Here:
marks is an array of 100 integer elements stored in a contiguous memory location.
temperature is an array of 365 floating point elements stored in a contiguous memory area.
name is an array of 60 character elements stored in a contiguous memory location.
U
Note that, the first element is indexed at position 0, second element at position 1 and so on
upto n-1 where n is size of an array. And the size of array is 5 times the size of int because there are
5 integer elements.
Storing Values in Arrays
The values can be stored in an array using following three methods:
1) Initialization
2) Assigning values
3) Input values from keyboard
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
a[0] a[1] a[2] a[3] a[4]
21 45 34 56 67
Note: Here even the declaration int a[ ] = { 21, 45, 34, 56, 67 }; is correct because based on
tio
number of elements specified the size will be computed automatically.
Example: The following program illustrate the initialization of one-dimensional array.
#include<stdio.h>
void main()
{ int age[5] = {21, 45, 34, 37, 94};
printf("Value in array age[0] : %d \n", age[0]);
} lu
printf("Value in array age[1] : %d \n", age[1]);
printf("Value in array age[2] : %d \n", age[2]);
printf("Value in array age[3] : %d \n", age[3]);
printf("Value in array age[4] : %d ",age[4]);
So
Output: Value in array age[0] :21
Value in array age[1] :45
Value in array age[2] :34
Value in array age[3] :37
Value in array age[4] :94
2. Assigning values to One-Dimensional Array
Example: int age[5];
age[0] = 22; //value 2 stored in array „age? at position 0
U
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
scanf("%d", &age[1]); //read data from keyboard into array age at position 1.
scanf("%d", &age[2]); //read data from keyboard into array age at position 2.
scanf("%d", &age[3]); //read data from keyboard into array age at position 3.
tio
scanf("%d", &age[4]); //read data from keyboard into array age at position 4.
In general, to read 5 values, we can write as:
for(i = 0; i < 5; i++)
{
scanf("%d", &age[i]);
}
printf("%d", age[i]);
So
}
Example: Program to illustrate reading/writing to one-dimensional array.
#include<stdio.h>
void main()
{
int age[5], i;
printf("enter 5 numbers:\n”);
for(i=0;i<5;i++)
{
U
scanf("%d", &age[i]);
}
for(i=0;i<5;i++)
{
printf("Value in array age[%d] : %d \n ", i, age[i]);
VT
}
}
Output: enter 5 numbers: 2 4 34 3 4
Value in array age[0] :2
Value in array age[1] :4
Value in array age[2] :34
Value in array age[3] :3
Value in array age[4] :4
Thus Array constructs can be used in a simple and easier way using looping constructs.
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
NOTE: While Using Arrays, we must keep in mind the following points:
Array index starts at 0 NOT 1
Array SIZE cannot be ZERO
C does NOT check array bounds whether index points to an element within the array OR
outside the array boundary. So we must never access array elements outside the boundary
and the result of accessing an array outside its boundary may result :
Corrupting of data
n
Segmentation fault
Exposing system to a security hole!
Example: Program to find maximum element in an array of n integer elements
tio
#include<stdio.h>
int main ()
{
int a[50],n,max, i;
printf(“\n\tEnter the number of elements: “);
scanf(“%d”,&n);
printf(“\n\tEnter %d Elements of array: “, n);
for ( i = 0; i < n; i++ )
scanf(“%d”,&a[i]);
max = a[0];
for (i = 1; i < n; i++ )
{ if(a[i] > max) lu
So
max = a[i];
}
printf(“ Maximum Element of an array =%d ", max );
return 0;
}
Example: Program to find minimum element in an array of n integer elements
#include<stdio.h>
int main ()
U
scanf(“%d”, &a[i]);
min = a[0];
for (i = 1; i < n; i++ )
{ if(a[i] < min)
min = a[i];
}
printf(“ Minimum Element of an array = %d ", min);
return 0;
}
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example: Program to find minimum and maximum element in an array of n integer elements
#include<stdio.h>
int main ()
{ int a[50], n, min, max, i;
printf(“\n\tEnter the number of elements: “);
scanf(“%d”, &n); /* 0 ≤ n ≤ 49 */
printf(“\n\tEnter %d Elements of array: “, n);
for ( i = 0; i < n; i++ )
n
scanf(“%d”, &a[i]);
min = max = a[0];
for (i = 1; i < n; i++ )
tio
{ if(a[i] < min)
min = a[i];
if(a[i] > max)
max = a[i];
}
printf(“ Min Element = %d And Max Element = %d” , min, max);
return 0;
}
Searching Problem
lu
This is the problem of finding the given key element in a list of elements. When the key
element is found in the list we call Search as Successful Search otherwise Unsuccessful Search.
So
Two simple Searching Methods which are commonly used are:
• Linear / Sequential Search
• Binary Search
Linear / Sequential Search
It compares each elements of the array with key element Sequentially / Linearly(one element
at a time) and it STOPS when Key is Found and declare Successful Search, It also STOPS when
Array exhaust and declare Unsuccessful Search. The algorithm of Linear/Sequential Search is:
Algorithm : Linear_Search( )
Begin
U
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example: Program to find given key element in an array of n integer elements using Linear
Search
int main ()
{ int a[50], n, min, i, flag = 0;
printf(“\n\tEnter the number of elements: “);
scanf(“%d”, &n); /* 1 ≤ n ≤ 50 */
printf(“\n\tEnter %d Elements of array: “, n);
for ( i = 0; i < n; i++ )
n
scanf(“%d”, &a[i]);
printf(“\n\tEnter the Key element to be Searched: “);
scanf(“%d”, &key);
tio
for (i = 0; i < n; i++ )
{ if(a[i] == key)
{
flag = 1; break;
}
}
if( flag == 1)
}
else
return 0;
lu
printf(“Successful Search - Key found ”);
If we look at the questions viz. How do we search for a person’s telephone number? If we
know only the person’s name. and How difficult is this? Similarly How do we search for a person’s
name? If we know only the person’s telephone number. and Why is this more difficult? similarly
How do we search for a student blue book, when blue books are unsorted? AND when blue books
are sorted?
Here what we can notice is Searching will be easier if the list is sorted. The technique what
U
we use in searching of key element in sorted list is Binary Search. It works only on Sorted Elements.
It finds the middle element in the complete list of sorted elements then Compares the key
element with middle element and STOPS if middle element is KEY and declare Successful Search.
If KEY is less than middle element then it search in the lower half of the sorted list in the same way
and If KEY is greater than middle element it search in the higher half of the sorted list in the same
way and finally If Array exhaust it STOPS and declare Unsuccessful search.
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
do
mid = (low + high) / 2
if a[mid] == key then
flag = TRUE break
tio
else if a[mid] > key then
low = mid + 1
else
high = mid – 1
end if
until low <= high
if flag == TRUE then
else
end if
print “Successful Search”
scanf(“%d”, &a[i]);
printf(“\n\tEnter the Key element to be Searched: “);
scanf(“%d”, &key);
low = 0; high = n – 1;
while(low <= high)
VT
{
mid = (low + high) / 2;
if(key == a[mid]) flag = 1;
else if(key > a[mid]) low = mid + 1;
else high = mid – 1;
}
if( flag == 1) printf(“Successful Search - Key found ”);
else printf(“Unsuccessful Search - Key NOT found”);
return 0;
}
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Arrays with two or more subscipts(dimensions/indices) are called multi dimensional arrays.
It is widely used in matrix operations. Its syntax is:
Data_Type Array_Name[Row_Size][Col_Size];
Here we can note that Two Dimensional Arrays are "an array of One-Dimensional arrays of
n
elements of same type". These are also called "Double Subscripted". Here a[ i ][ j ] refers to i-th
Row and j-th Column element of 2D Array
tio
Example:
int a[3][4];
Here a is an array of 3 arrays of 4 integer elements. The above code can be pictorially represented as
shown below:
a[0][0]
a[1][0]
a[2][0]
lu a[0][1]
a[1][1]
a[2][1]
a[0][2]
a[1][2]
a[2][2]
a[0][3]
a[1][3]
a[2][3]
So
A two dimensional array is used when elements are arranged in a tabular fashion. Here, to
identify a particular element, we have to specify 2 indices:
Example-1:
int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
10
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example-3:
int a[2][3] = { { 1, 2}, { 4 } };
Here we can note that example 2 and 3 are partially initialized, so the uninitialized elements
get ZERO by default.
n
Example-4:
int a[ ][2] = { 11, 2, 3, 4, 5 }; /*Row size = 3 */
tio
int a[ ][4] = { 11, 2, 3, 4, 5 }; /*Row size = 2 */
int a[ ][5] = { 11, 2, 3, 4, 5 }; /*Row size = 1 */
int a[ ][8] = { 11, 2, 3, 4, 5 }; /*Row size = 1 */
In 2D’ Arrays Row size is optional but COLUMN size Compulsory during initializing 2D’ Arrays at
the time of their declaration
This way of reading / printing a 2D’ array is not easy and not recommended
{
for(j=0;j<3;j++) /* specify j-th Column */
{
scanf("%d", &matrix[i][j]);
VT
}
}
Similarly to display 6 elements stored in the matrix, we can write:
for(i=0;i<2;i++) /* specify i-th Row */
{
for(j=0;j<3;j++) /* specify j-th Column */
{
printf("%d ", matrix[i][j]);
}
}
11
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
for(j=0;j<3;j++)
{
scanf("%d", &matrix[i][j]);
tio
}
}
printf("elements of the matrix are: \n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
}
}
}
printf(“\n”);
lu
printf("%d \t", matrix[i][j]);
So
Output:
enter elements of 2*3 matrix:
1 23 11
44 5 6
elements of the matrix are:
1 23 11
44 5 6
Example: Program to read and print mXn Matrix
#include<stdio.h>
U
void main ()
{
int a[10][10], i, j, m, n;
printf(“\n\tEnter the Order of Matrix : “);
VT
12
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Output:
Enter the Order of Matrix : 2 3
Enter 6 Elements of Matrix: 22 7 4 84 5 13
The 6 Elements of Matrix are: 22 7 4 84 5 13
We must display the matrices as matrices only. The following code display matrix in the matrix form
i.e row wise one after the other.
n
Example: Program to read and print mXn Matrix
#include<stdio.h>
void main ()
tio
{
int a[10][10], i, j, m, n;
printf(“\n\tEnter the Order of Matrix : “);
scanf(“%d %d”,&m,&n); /* m is ROW & n is COLUMN */
printf(“\n\tEnter %d Elements of Matrix : “, m * n);
for(i = 0; i < m; i++) /* specify i-th Row */
for(j = 0; j < n; j++) /* specify j-th Column */
lu
scanf(“%d”,&a[ i ][ j ]);
printf(“\n\tThe %d Elements of Matrix are: “, m * n );
for(i = 0; i < m; i++) /* specify i-th Row */
{
printf("\n\t");
So
for(j = 0; j < n; j++) /* specify j-th Column */
printf(“%d”,a[ i ][ j ]);
}
} /* closing of main */
U
VT
13
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
STRINGS
String is an Array of Characters terminated by a NULL character '/0'.
Example:
char a[10] = “Hello”;
The above string can be pictorially represented as shown below:
n
a[0] a[1] a[2] a[3] a[4] a[5] ….. a[9]
H e l l o ‘\0’ 0 0
tio
STRING VARIABLE
There is no separate data type for handling strings in C. They are treated as just an arrays of
characters. So, a variable which is used to store an array of characters is called a string variable.
Declaration of String
Example:
lu
Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char type.
char s[5]; //string s can hold maximum of 5 characters including NULL character
So
The above code can be pictorially represented as shown below:
a[0] a[1] a[2] a[3] a[4]
Initialization of String
Example:
char s[4]={'V', 'T', 'U' };
U
14
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
}
Output:
Value in array s[0] : V
tio
Value in array s[1] : T
Value in array s[2] : U
Reading & Printing Strings
The strings can be read from the keyboard and can be displayed onto the monitor using
following formatted functions:
Formatted input function: scanf()
#include <stdio.h>
int main()
{ lu
Formatted output function: printf()
Example: Program to illustrate the use of scanf() and printf().
So
char str[50];
int i, n; clrscr();
printf(“\n\tEnter a string(gets):“);
gets(str);
printf(“\n\t String Entered is(gets) : %s“, str);
printf(“\n\tEnter number of character in the string:“);
scanf(“%d”, &n);
printf(“\n\tEnter %d characters of string one by one :”);
for( i = 0; i < n ; i++ )
U
scanf(“%c”, &str[ i ] );
str[ i ] = ‘\0’ ;
printf(“\n\t String Entered is: %s“, str);
printf(“\n\tEnter a string(scanf): “); scanf(“%s”, str);
VT
15
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
void main()
{
char name[10];
tio
printf(“enter your name: \n”);
gets(name); //same as scanf(“%s”, name);
printf(“welcome: ”);
puts(name); //same as printf(“%s”, name);
}
Output: enter your name:
rama
welcome: rama
#include <stdio.h>
int main()
{ lu
Example: Program to count the number of characters in a string. – String Lenth
So
char str[100]; int i, length;
printf(“\n\tEnter a String to Compute its Length: ");
scanf(“%s", str);
for(i = 0; str[ i ] != ‘\0’; i++)
; /* NULL Statement * /
length = i;
printf(“\n\n\t The Length of String: %s is %d”, str, length);
return 0;
}
U
16
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
In order to Compare Two Strings, we have to compare each character of String one by one
and needs to return
n
#include <stdio.h>
int main()
{
tio
char str1[100], str2[100]; int i, flag;
printf(“\n\tEnter a String-1: ");
scanf(“%s", str1);
printf(“\n\tEnter a String-2: ");
scanf(“%s", str2); i=0;
while ( (str1 [ i ] == str2 [ i ]) && (str1 [ i ] != ‘\0’) )
i++;
flag = str1 [ i ] - str2 [ i ] ;
if(flag == 0)
lu
printf(“\n\n\t The Strings are equal” );
else if (flag > 0)
So
printf(“\n\n\t The String1 is higher than String2” );
else
printf(“\n\n\t The String1 is lower than String2” );
return 0;
}
Character handling Functions Includes functions to perform useful tests and manipulations
U
on character data. Each function receives a character (an int) or EOF as an argument. These library
functions exists in the header <ctype.h>. Commonly used Character handling functions are:
17
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example: Program to Convert lower case character to upper case and vice versa.
#include<ctype.h>
#include<stdio.h>
int main()
{
char ch; clrscr();
printf("Enter a Character : "); scanf("%c", &ch);
if(islower(ch))
n
ch = toupper(ch);
else
ch = tolower(ch);
tio
printf("\n\tCharacter After Reversing case is : %c", ch);
getch(); return 0;
}
18
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
To hold the list of names we can use Two dimensional array of characters. Consider the
below example.
char s[3][50] = { “EDUSAT”, “PROGRAM”, “BANGALORE” };
char *ptr; ptr = s;
The above declaration can be pictorially viewed as shown below:
n
Content 1 2 3
tio
Here
s[0] = Address of the 0th String
s[1] = Address of the 1st String
s[2] = Address of the 2nd String
lu
int i , n; char names[10][50]; clrscr();
printf("\n\tEnter the Number of Names: "); scanf("%d", &n);
So
printf("\n\tEnter %d Names", n);
for(i = 0; i < n; i++)
{
printf("\n\tEnter Name-%d: ", i+1);
scanf("%s", names[i]);
}
printf("\n\tThe %d Names are: ", n);
for(i = 0; i < n; i++) printf("\n\t\t\t%s",names[i]);
getch();
U
return 0;
}
VT
19
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example: Program to Read a sentence and print frequency of vowels and count of consonants.
#include <stdio.h>
#include<ctype.h>
#include<conio.h>
int main()
{
char str[100]; clrscr();
int i, na, ne, ni, no, nu, nvowel, ncons, x;
n
printf(“\n\tEnter a Sentence : ");
gets(str); /* scanf(“%s", str); */
na = ne = ni = no = nu = nvowel = ncons = x = 0;
tio
for (i = 0 ; str [ i ] != ‘\0’; i++)
{ if(!isalpha(str[ i ])) { x++; continue; }
switch(str [ i ])
{ case ‘A’ :
case ‘a’ : na++; break;
case ‘E’ :
case ‘e’ : ne++; break;
case ‘I’
case ‘i’
case ‘O’
case ‘o’
case ‘U’
:
:
lu
: ni++; break;
: no++; break;
:
So
case ‘u’ : nu++; break;
}
}
nvowel = na + ne + ni + no + nu ;
ncons = i – nvowel - x;
printf(“\n\tNumber of a’s in the String is : %d “, na);
printf(“\n\tNumber of e’s in the String is : %d “, ne);
printf(“\n\tNumber of i’s in the String is : %d “, ni);
printf(“\n\tNumber of o’s in the String is : %d “, no);
U
}
Output: Enter a Sentence : Hai Students
Number of a’s in the String is : 1
Number of e’s in the String is : 1
Number of i’s in the String is : 1
Number of o’s in the String is : 0
Number of u’s in the String is : 1
Number of Vowels in the String is : 4
Number of Consonants in the String is : 7
20
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
unsigned int strlen(const char *s);
char * strcpy(char *dest, const char *src);
char * strcat(char *dest, const char *src);
tio
char * strcmp(const char *dest, const char *src);
char * strchr(const char *s, int c);
char * strstr(const char *m_str, const char *s_str);
char * strrev(char *str);
strlen()
This function calculates the length of string. It takes only one argument, i.e., string-name.
The syntax is :
lu
temp_variable = strlen(string_name);
Example: Program to illustrate the use of strlen().
#include<string.h>
#include<stdio.h>
void main()
So
{
char c[20]; int len;
printf("Enter string whose length is to be found:");
gets(c);
len=strlen(c);
printf("\n Length of the string %s is %d ",c, len);
}
Output: Enter string whose length is to be found: program
Length of the string program is 7
U
strcpy()
This function copies the content of one string to the content of another string. It takes 2
arguments. The syntax is : strcpy(destination,source);
where source and destination are both the name of the string.
VT
21
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
char *blank = " "; int len;
strcpy(dest, str1);
strcat(dest, blank);
tio
strcat(dest, str2);
len = strlen(dest);
printf("\n\n\tThe Length of String\"%s\" is %d\n", dest, len);
return 0;
}
Output: The Length of String "EDUSAT Program" is 14
strcmp()
lu
This function compares 2 string and returns value 0, if the 2 strings are equal. It takes 2
arguments, i.e., name of two string to compare. The syntax is shown below:
So
temp_varaible=strcmp(string1,string2);
gets(str1);
printf("Enter second string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Both strings are equal");
VT
else
printf("Strings are unequal");
}
Output:
Enter first string: rama
Enter second string: rama
Both strings are equal
22
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example: Develop, implement and execute a C Program to search a Name in a list of names
using Binary searching Technique.
#include<stdio.h>
#include<c onio.h>
#include<string.h>
int main()
{
int i, n, low, high, mid;
n
char names[10][50];
char str[50];
clrscr();
tio
printf("\n\tEnter the Number of Names: ");
scanf("%d",&n);
printf("\n\tEnter %d Names", n);
for(i = 0; i < n; i++)
{
printf("\n\tEnter Name-%d: ", i +1 );
fflush(stdin);
}
gets(names[ i ]);
lu
printf("\n\n\tEnter the Name to be Searched: ");
fflush(stdin);
gets(str);
So
low = 0; high = n-1;
while(low <= high)
{
mid = (low + high) / 2;
if(strcmp(str,names[mid]) == 0)
{
printf("\n\tName Found at Position: %d", mid+1);
getch(); exit(0);
}
U
}
Output: Enter the Number of Names: 4
Enter 4 Names
Enter Name-1: Arun Kumar
Enter Name-2: Bhaskar Reddy
Enter Name-3: Chandrashekhar
Enter Name-4: Lahari
Enter the Name to be Searched: Bhaskar Reddy Name Found at Position: 2
23
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
printf("Enter string whose length is to be found:");
gets(str1);
while(str1[len]!='\0')
tio
len++; //here the length of string is calculated.
printf("Length of the string is %d", len);
}
Output:
Enter string whose length is to be found: vtunotesbysri
Length of the string is 13
void main()
{
char str1[25],str2[25]; lu
Example: Program to concatenate two strings without using strcat().
#include<stdio.h>
So
int i=0,j=0;
printf(" Enter First String:");
gets(str1);
printf("\n Enter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
U
str1[i]=str2[j];
j++;
i++;
}
VT
str1[i]='\0';
printf("\n Concatenated String is ");
puts(str1);
}
Output:
Enter First String: rama
Enter Second String: krishna
Concatenated String is ramakrishna
24
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example: Program to copy one string into other without using strcpy().
#include<stdio.h>
void main()
{
char src[100], dest[100]; int i;
printf("Enter string:");
gets(src);
i = 0;
n
while (src[i] != '\0')
{
dest[i] = src[i];
tio
i++;
}
dest[i] = '\0';
printf("Copied String ; %s ", dest);
}
Output:
Enter string : vtunotes
Copied String : vtunotes
#include<stdio.h>
void main()
{ lu
Example: Program to compare 2 strings without using strcmp().
So
char str1[100],str2[100]; int i=0, flag=0;
printf("Enter first string: "); scanf("%s",str1);
printf("Enter second string: "); scanf("%s",str2);
while(str1[i]!='\0' && str2[i]!='\0')
{
if(str1[i]!=str2[i])
{
flag=1;
break;
U
}
i++;
}
if (flag==0 && str1[i]=='\0' && str2[i]=='\0')
VT
25
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
FUNCTION IN C
n
program.
Advantages of Functions
tio
The following are the advantages of using user defined functions:
• Functions separate the concept (what is done?) from the implementation (how it is done?).
• Functions make programs easier to understand thus improves the readability of program.
• Functions can be called several times in the same program, allowing the code to be reused.
Functions in C
lu
There are 2 types of functions in C programming:
• Library function
So
• User defined function
C allows the use of both User-Defined Functions and Library Functions. Library Functions
(e.g printf(), scanf(), getchar(), putchar(), abs(), ceil(), rand(), sqrt(), etc.) are usually grouped
into specialized libraries.(e.g. <stdio.h>, <math.h> <string.h> and so on). Every Function takes
some input(optional) and perform operations and give some output. This can be pictrically
viewed as:
U
VT
26
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
function_name(); // function call
...........
...........
tio
}
void function_name() //function definition
{
................
................
}
lu
As mentioned earlier, every C program begins from main() and program starts executing the
codes inside main() function. When the control of program reaches to function_name() inside main()
function, the control of program jumps to void function_name() and executes the codes inside it.
When all the codes inside that user-defined function are executed, control of the program jumps to
the statement just after function_name() from where it is called.
So
Function Declaration / Prototype
Every function in C program should be declared before they are used. Function declaration
gives compiler information about function name, type of arguments to be passed and return type.
The syntax is shown below:
Data type needed for each argument, If no arguments, use void or leave blank
Example:
void Display(void);
int print_data();
xyz(); // default return type is int
double abc(int, int, char, float*);
int absolute(int);
void print_array(float*, int, int);
27
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Function Call
Control of the program cannot be transferred to user-defined function unless it is called
invoked. The syntax is shown below:
function_name(argument(1),....argument(n));
Function Definition
n
The syntax is shown below:
tio
{
//body of function
}
}
display(); //function call
lu
So
void display() //function definition
{
printf("C Programming");
return;
}
Output:
C Programming
U
VT
Argument (or parameter) refers to data that is passed to function (function definition) while
calling function. Arguments listed in function calling statements are referred to as actual arguments.
These actual values are passed to a function to compute a value or to perform a task. The arguments
used in the function declaration are referred as formal arguments. They are simply formal variables
that accept or receive the values supplied by the calling function. The number of actual and formal
arguments and their data types should be same.
28
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example: Program to add two integers. Make a function add integers and display sum in
main() function.
#include <stdio.h>
int add(int a, int b);
int main()
{
int a,b,sum;
printf("Enters two number to add \n");
n
scanf("%d %d", &a,&b); //actual arguments
sum=add(a,b);
printf("\n sum=%d", sum);
tio
return 0;
}
}
Output:
return sum;
actual arguments because formal arguments are photocopy of actual arguments. Changes made in the
formal arguments are local to the block of called-function. Once control returns back to the calling-
function the changes made vanish.
Example: Program to send values using call-by-value method.
VT
#include <stdio.h>
void main()
{
int x,y,
printf(“enter values of x & y : “);
scanf(“%d %d “, &x, &y);
printf(“\n old values x=%d y =%d”, x, y);
change(x,y) ;
printf(“\n new values x=%d y =%d”, x, y);
}
29
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
Example: Program to SWAP contents of two variables
#include<stdio.h>
#include<conio.h>
tio
void swap(int , int );
int main()
{
int a, b; clrscr();
printf(“\n\tEnter Values of a and b: “); scanf(“%d%d”,&a,&b);
printf(“\n\t Before SWAP a = %d and b = %d”, a, b);
}
swap(a, b);
getch(); return 0;
#include<conio.h>
void swap(int *, int *);
int main()
{ int a, b; clrscr();
printf(“\n\tEnter Values of a and b: “); scanf(“%d%d”,&a,&b);
printf(“\n\t Before SWAP a = %d b = %d”, a, b);
swap(&a, &b);
printf(“\n\t After SWAP a = %d b = %d”, a, b);
getch(); return 0;
}
30
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
Before SWAP a = 15 and b = 27
After SWAP a = 27 and b = 15
Example: Program to check Even or Odd number using Functions.
tio
#include<stdio.h>
void CheckEvenOdd(int); // prototype for absolute()
int main()
{ int num;
printf(“\n\tEnter an integer: “); scanf(“%d”, &num);
CheckEvenOdd(num); // function call
return 0;
}
if ( x % 2 == 0)
else lu
void CheckEvenOdd(int x) // function definition
{
printf(“\n\tThe Number %d is EVEN”, x);
printf(“\n\tThe Number %d is ODD”, x );
So
}
CLASSIFICATION OF USER-DEFINED FUNCTIONS
Based on the parameter and return type of a function we can categorize functions as :
1. Function with no arguments and no return value
2. Function with no arguments and return value
3. Function with arguments but no return value
4. Function with arguments and return value
Example: Program to illustrate function with no arguments and no return value.
U
#include <stdio.h>
void add();
void main()
{
VT
add();
}
void add()
{
int a, b, sum;
printf("Enters two number to add : ");
scanf("%d %d", &a, &b);
sum=a+b;
printf("\n sum=%d", sum);
return 0;
}
31
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Output:
Enters two number to add : 2 3
sum=5
Example: Program to illustrate function with no arguments and return value.
#include <stdio.h>
int add();
void main()
{
n
int sum;
sum=add();
printf("\n sum=%d", sum);
tio
}
int add()
{
int a, b, sum;
printf("Enters two number to add \n");
scanf("%d %d", &a, &b);
}
Output:
sum=a+b;
return sum;
sum= a+ b;
printf("\n sum=%d", sum);
return;
}
Output:
Enters two number to add
23
sum=5
32
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
sum=add(a,b);
printf("\n sum=%d", sum);
return 0;
tio
}
int add(int a, int b)
{
int sum;
sum=a+b;
return sum; //return statement of function
}
Output:
Enters two number to add
23
sum=5
lu
So
Example: Design and develop a C function RightShift(x ,n) that takes two integers x and n as
input and returns value of the integer x rotated to the right by n positions. Assume the integers
are unsigned. Write a C program that invokes this function with different values for x and n
and tabulate the results with suitable headings.
#include<stdio.h>
#include<conio.h>
unsigned RightShift(unsigned x, unsigned n);
int main()
{ unsigned int x, n, res; clrscr();
U
getch(); return 0;
}
unsigned RightShift(unsigned x, unsigned n)
{ unsigned int i;
for(i = 1; i <= n; i++)
{ if( x % 2 == 0) x = x >> 1;
else { x = x >> 1; x = x + ( 1 << ( sizeof(int) * 8 - 1 ) ); }
}
return x;
}
33
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
After Rotating 7 by 3 times we get: 49153
Example: Design and develop a C function isprime(num) that accepts an integer argument and
returns 1 if the argument is prime, a 0 otherwise. Write a C program that invokes this function
tio
to generate prime numbers between the given range.
#include<stdio.h>
#include<conio.h>
int isPrime(unsigned n);
int main()
{ unsigned int m, n, res, i; clrscr();
lu
printf("\n\tEnter a Range of Unsigned Number: ");
scanf("%u%u",&m,&n);
printf("\n\t PRIME Numbers between %u to %u are: ", m, n);
for(i = m; i <= n ; i++)
{ res = isPrime(i);
So
if(res == 1) printf(" %u ", i);
}
getch(); return 0;
}
int isPrime(unsigned n)
{
unsigned int i;
if(n==1) return 0;
U
}
return 1; // Number is PRIME
}
Output:
Enter a Range of Unsigned Number: 1 15
PRIME Numbers between 1 to 15 are: 2 3 5 7 11 13
Enter a Range of Unsigned Number: 20 65
PRIME Numbers between 20 to 65 are: 23 29 31 37 41 43 47 53 59 61
34
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
STORAGE CLASS
Every variable in C program has two properties: type and storage class. Type refers to the
data type of variable And storage class determines how long it stays in existence i.e Storage
duration – how long an object (a program element) can exists in memory And the Scope –
where object (a program element) can be referenced in program. C Support Four types of Storage
classes:
Automatic OR Local
n
Register
Static
Extern OR Global
tio
AUTOMATIC VARIABLE
The keyword auto is used to declare or define an automatic variables Ex: auto double x, y;
The default scope of variables declared or defined within a block is Local / Automatic.
These program elements are created and destroyed within its block.
NO Default value exist for a Local variable i.e it possess a JUNK value when uninitialized.
int main()
{ int x = 9, y = 8, z = 5, t; lu
Example: Program to illustrate Automatic Variables.
#include<stdio.h>
So
printf(“\nX=%d Y=%d Z=%d T=%d”, x, y, z, t);
if(x == 9)
{
int z = 25, a= 55;
printf(“\nX=%d Y=%d Z=%d a = %d”, x, y, z, a);
}
printf(“\nX=%d Y=%d Z=%d”, x, y, z);
getch(); return 0;
}
U
Output:
X=9 Y=8 Z=5 T=-9785
X=25 Y=8 Z=25 a=55
X=9 Y=8 Z=5
VT
REGISTER VARIABLES
• Using keyword register we can declare a register variable. Ex: register int flag = 1;
• Register variables are stored in high-speed registers.
• Register variables Can only be used as automatic variables.
• Register variables are not stored in memory so they do not have address. NO POINTER can
hold an address of register variable
• NO Default value exist for a Register variable i.e it possess a JUNK value when uninitialized.
35
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
z=a+b;
printf("\n sum=%d", z);
}
tio
Output:
Enters two number to add
23
sum=5
EXTERNAL VARIABLES
• Specifies actual storage and initial value of a variable or Function body is defined elsewhere.
• The keyword extern is used to declare/define an Extern / Global variables Ex: extern int x, y;
•
•
•
• lu
The default scope of variables or function declared/defined outside of all functions is Global.
Global variables exist for entire program execution and can be accessed by Every function.
By Default global variable hold ZERO value.
In case of large program, containing more than one file, if the global variable is declared in file 1
So
and that variable is used in file 2 then, compiler will show error. To solve this problem, keyword
extern is used in file 2 to indicate that, the variable specified is global variable and declared in
another file.
Example: Program to demonstrate working local and global variables.
#include <stdio.h>
int z; // z is a global variable
void display()
{
printf("\n sum=%d", z);
U
}
void main()
{ // a and b are local variables
auto int a, b; //or int a, b;
printf("Enters two number to add: ");
VT
36
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
STATIC VARIABLE
• Using keyword static we can declare a static variable. Ex: static int flag = 1;
• Static Variable are similar to local variables except that these can hold(persist) their values(data).
• static variables are initialized only once.
• static variables exist for entire program execution.
• By Default static variable hold ZERO value.
Example: Program to demonstrate working of static variable.
n
#include <stdio.h>
void Check()
{
tio
static int c=0;
printf("%d \t",c);
c=c+5;
}
int main(){ Check(); Check(); Check(); }
Output:
0 5 10
lu
Example: Write and execute a C program that implements string copy operation
STRCOPY(str1,str2) that copies a string str1 to another string str2 without using library function.
#include<stdio.h>
#include<conio.h>
So
char * STRCOPY(char * d, const char * s);
int main()
{ char *str1, *str2; int i; clrscr();
printf("\n\tEnter a String-1: "); scanf("%s", str1);
STRCOPY(str2,str1); //strcpy(str2,str1);
printf("\n\n\tString-1: %s", str1);
printf("\n\n\tString-2: %s", str2);
getch(); return 0;
}
U
str2[i] = str1[i];
i++;
}
str2[ i ] = '\0';
return str2;
}
Output:
Enter a String-1: VTU
String-1: VTU
String-2: VTU
37
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Recommendations in Programming
• Use as much as possible less declarations of variables
• Avoid using Global variables unless it is inevitable.
• Use register variable if local variable is accessed very frequently for many time. (i.e Loop
iterators)
Example: Program to Read two 2’D Arrays and multiply if compatible using Functions
#include<stdio.h>
n
#include<conio.h>
#include<stdlib.h>
MatrixMultiply(int (*)[10], int (*)[10], int [ ][10], int, int, int);
void ReadMatrix(int [ ][10], int, int);
tio
void PrintMatrix(int p[ ][10], int m, int n);
void ReadMatrix(int p[ ][10], int m, int n);
}
printf("\n\t");
for(j = 0; j < n; j++)
lu
printf(" %d ",p[i][j]);
So
}
void ReadMatrix(int p[ ][10], int m, int n)
{
int i, j;
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
scanf("%d", &p[i][j]);
}
int main()
U
getch(); exit(0);
}
printf("\n\tEnter %d Elements of Matrix-A: ", m * n); ReadMatrix(a, m, n);
printf("\n\tEnter %d Elements of Matrix-B: ", p * q); ReadMatrix(b, p, q);
MatrixMultiply(a, b, c, m, n, q);
printf("\n\tMatrix-A is:"); PrintMatrix(a, m, n);
printf("\n\tMatrix-B is:"); PrintMatrix(b, p, q);
printf("\n\tProduct Matrix-C is:"); PrintMatrix(c, m, q);
getch(); return 0;
}
38
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
c[i][j] = c[i][j] + a[i][k]*b[k][j];
}
}
tio
return 0;
}
Output:
Enter Order of Matrix-A : 3 2
Enter Order of Matrix-B : 2 3
Enter 6 Elements of Matrix-A : 1 2 3 4 5 6
Enter 6 Elements of Matrix-B : 1 2 3 4 5 6
Matrix – A is:
1 2 3
4 5 6
Matrix – B is:
1 4 lu
So
2 5
3 6
Product Matrix C is:
14 32
32 77
RECURSION
A recurrence relation is a relation which is defined in terms of smaller instances of itself until
certain condition is met (trivial cases are seen). Consider an example of finding Factorial of a
Number, Here we define the formula as:
U
VT
here when n = 0 the computation stops and return 1. Now we need to write a program to compute
factorial of a number but How to Program it? here we can use Fact(n) instead of n!
Here we can note that function Fact(n) calls itself until n=0. This technique is called RECURSION.
i.e Recursion is a technique in Programming where a Function calls itself until certain
condition is satisfied(trivial case).
39
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Recursive Method
int Fact(int n)
{
if(n == 0) return 1;
else return n * Fact(n – 1) ;
}
n
Another way of finding factorial of a number without recursion could be as shown below, this
is an Iterative method /non-recursive method
tio
int Fact(int n)
{ if(n == 0) return 1;
else
{ int i, prod = 1;
for(i = 2; i <= n; i++)
prod = prod * i;
return prod
}
}
lu
Example: Program to find sum of first n natural numbers using recursion.
#include <stdio.h>
So
int add(int n)
{
if(n==0) return n;
else return n+add(n-1); /*self call to function add() */
}
void main()
{
int num, sum;
printf("Enter a positive integer: ");
U
scanf("%d",&num);
sum=add(num);
printf("sum=%d", sum);
}
VT
Output:
Enter a positive integer: 5
15
Explanation: Here, add() function is invoked from the same function. If n is not equal to 0 then, the
function calls itself passing argument 1 less than the previous argument it was called with. Suppose,
n is 5 initially. Then, during next function calls, 4 is passed to function and the value of argument
decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is returned which is
the sum numbers from 5 to 1.
40
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
=5+4+3+2+1
=5+4+3+3
=5+4+6
tio
=5+10
=15
Every recursive function must be provided with a way to end the recursion. In this example
when, n is equal to 0, there is no recursive call and recursion ends.
Explanation: During first function call, it will display 0. Then, during second function call, variable
c will not be initialized to 0 again, as it is static variable. So, 5 is displayed in second function call
and 10 in third call.
Fibonacci Series
lu
The series 0, 1, 1, 2, 3, 5, 8, 13, ....... is clled Fibonacci series. here we compute the nth
fibonacci number as sum of (n-1)th and (n-2)th fibonacci numbers except 0th and 1st fibonacci
So
number. The Recurrence relation to compute nth fibonacci number can be given by:
if(n == 0 || n == 1) return n;
else return Fib(n – 1) + Fib(n – 2) ;
}
The following is the non-recursive function to compute nth fibonacci number:
VT
int FibI(int n)
{ int fib[50], i;
if(n == 0 || n == 1) return n;
else
{ fib[0] = 0; fib[1] = 1;
for(i=2; i <=n; i++)
fib[i] = fib[i-1] + fib[i-2];
return fib[n];
}
}
41
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example: Write a recursive C function to find the factorial of a number, n!, defined by fact(n)=1,
if n=0. Otherwise fact(n)=n*fact(n-1). Using this function, write a C program to compute the
n
binomial coefficient nCr. Tabulate the results for different values of n and r with suitable
messages.
#include<stdio.h>
tio
#include<conio.h>
int Fact(int n)
{
if(n == 0) return 1;
else return n * Fact(n -1);
}
int FindnCr(int n, int r)
{
}
lu
return Fact(n) / ( Fact(r) * Fact(n - r) );
Output:
Enter Value of n: 5
Enter Value of r: 3
nCr(0,0)=1
nCr(1,0)=1 nCr(1,1)=1
nCr(2,0)=1 nCr(2,1)=2 nCr(2,2)=1
nCr(3,0)=1 nCr(3,1)=3 nCr(3,2)=3 nCr(3,3)=1
nCr(4,0)=1 nCr(4,1)=4 nCr(4,2)=6 nCr(4,3)=4
nCr(5,0)=1 nCr(5,1)=5 nCr(5,2)=10 nCr(5,3)=10
42
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
All array-elements can be passed as individual elements to a function like any other variable.
The array-element is passed as a value parameter i.e. any change in the formal-parameter will not
affect the actual-parameter i.e. array-element. Here we use call by value method.
tio
2) Passing the Whole Array
Here, the address of the array is passed as parameter. Thus here we use call by address value
method. Here the formal parameters indirectly through addresses access the values of actual
parameters. So, any changes in formal parameter imply there is a change in actual parameter.
Global Declarations.
#include<stdio.h>
#include<conio.h>
lu
Example: Program to Read and Print One dimensional arrays using User Defined Functions &
So
void ReadArray( );
void PrintArray( );
int x[50], n;
int main()
{ clrscr();
printf("\n\tEnter number of elements of an array: ");
scanf("%d", &n);
ReadArray( );
PrintArray( );
getch(); return 0;
U
}
void ReadArray( )
{ int i;
printf("\n\tEnter %d Elements of an Array: ", n);
VT
43
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
In the above program we neither used passing an array element by element nor passing
whole array as parameter because here elements are declared globally so no need of passing
any parameter
n
printf("%d", a);
}
void main()
tio
{
int c[3]={2,3,4};
display(c[2]); //Passing array-element c[2] only.
}
Output:
[
4
Example: Program to Read and Print One dimensional arrays using User Defined Functions
By Passing Array: element by element
#include<stdio.h>
#include<conio.h>
lu
void PrintArray( int n) { printf(“ %d “, n); }
int main()
So
{ int x[50], n, i; clrscr();
printf("\n\tEnter number of elements : "); scanf("%d", &n);
printf("\n\tEnter %d Elements of an Array: ", n);
for(i = 0; i < n; i++) scanf("%d", &x[i]);
printf("\n\tThe %d Elements of an Array are: ", n);
for(i = 0; i < n; i++)
PrintArray(x[ i ]);
getch(); return 0;
}
U
Example: Program to Read and Print One dimensional arrays using User Defined Functions
By Passing: the whole Arrays
#include<stdio.h>
#include<conio.h>
VT
44
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
printf("\n\tThe %d Elements of an Array are: ", n);
for(i = 0; i < n; i++)
printf(" %d ", a[ i ]);
tio
}
}
for(i=0;i<6;i++)
sum= sum+ m[i];
avg =(sum/6);
printf("aggregate marks= %d ", avg);
lu
So
void main()
{
int m[6]={60, 50, 70, 80, 40, 80, 70};
average(m); // Only name of array is passed as argument
}
Example: Program to implement Linear Search using User Defined Functions.
#include<stdio.h>
#include<conio.h>
void ReadArray(int *a, int n)
U
{
int i;
printf("\n\tEnter %d Elements of an Array: ", n);
for(i = 0; i < n; i++)
VT
45
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
int main()
{
int x[50], n, key, flag; clrscr();
printf("\n\tEnter number of elements of an array: ");
scanf("%d",&n);
ReadArray(x, n);
printf("\n\tEnter key element to be searched: ");
scanf("%d",&key);
n
flag = LinearSearch(x, n, key);
if(flag == 1) printf("\n\tSuccessful Search");
else printf("\n\tUnSuccessful Search");
tio
getch(); return 0;
}
WORKED EXAMPLES
int
int
array[MAXSIZE];
lu
i, num, negative_sum = 0, positive_sum = 0;
So
float total = 0.0, average;
printf ("Enter the value of N \n");
scanf("%d", &num);
printf("Enter %d numbers (-ve, +ve and zero) \n", num);
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
// Summation starts
for (i = 0; i < num; i++)
U
{
if (array[i] < 0)
negative_sum = negative_sum + array[i];
else if (array[i] > 0)
VT
46
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Output:
Enter the value of N
10
Enter 10 numbers (-ve, +ve and zero)
-8 9 -100 -80 90 45 -23 -1 0 16
Sum of all negative numbers = -212
Sum of all positive numbers = 160
Average of all input numbers = -5.20
n
Example: Program to generate fibonacci series.
#include <stdio.h>
tio
main()
{
int fib[100], i, n;
fib[0] = 0; fib[1] = 1;
printf("enter n value: “); scanf(“%d”. &n);
for(i = 2; i < n; i++)
fib[i] = fib[i-1] + fib[i-2];
}
Output:
printf("fibo series is: ”);
for(i = 0; i < n; i++)
printf(“ %d ", fib[i]);
lu
So
enter n value:7
fibo series is : 0 1 1 2 3 5 8
Example: Program to find the value of the polynomial f(x)=a4x4+a3x3+a2x2+a1x+a0 using
horner’s method.
#include <stdio.h>
void main()
{
float a[100],sum=0,x; int n,i;
U
scanf("%f",&x);
for(i=n;i>0;i--)
sum=(sum+a[i])*x;
sum=sum+a[0];
printf(" Value of the polynomial is =%f",sum);
}
Output: Enter the degree of the polynomial: 4
Enter the coefficients into the array: 3 2 1 1 2
Enter the value of x: 2
Value of the polynomial is: 72.000000
47
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
printf("Enter the elements one by one: \n");
for (i = 0; i < num; i++)
{
tio
scanf("%d", &array[i]);
}
printf("Input array is: \n");
for (i = 0; i < num; i++)
printf("%d ", array[i]);
// Bubble sorting begins
for (i = 0; i < num; i++)
{
{
lu
for (j = 0; j < (num - i - 1); j++)
}
Output:
Enter the value of num: 6
Enter the elements one by one: 23 45 67 89 12 34
VT
48
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
printf("Enter the elements of matrix array1 \n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
tio
scanf("%d", &array1[i][j]);
printf("Enter the elements of matrix array2 \n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &array2[i][j]);
printf("Enter your option: 1 for Addition and 2 for Subtraction \n");
scanf("%d", &option);
switch (option)
{
case 1:
lu
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
So
arraysum[i][j] = array1[i][j] + array2[i][j];
printf("Sum matrix is \n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
printf("%d\t", arraysum[i][j]) ;
printf("\n");
}
break;
U
case 2:
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
arraydiff[i][j] = array1[i][j] - array2[i][j];
VT
49
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Output:
Enter the order of the matrix array1 and array2
33
Enter the elements of matrix array1
234
789
568
Enter the elements of matrix array2
n
333
346
847
tio
Enter your option: 1 for Addition and 2 for Subtraction
1
Sum matrix is
5 6 7
10 12 15
13 10 15
Example: Program to compute the product of two matrices.
#include<stdio.h>
void
{
main()
int
lu
array1[10][10], array2[10][10], array3[10][10], m, n, i, j ,k;
printf("Enter the value of m and n \n"); scanf("%d %d", &m, &n);
So
printf("Enter Matrix array1 \n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &arr[i][j]);
printf("Enter Matrix array2 \n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &arr[i][j]);
for (i = 0; i < m; i++)
U
50
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Output:
Enter the value of m and n
33
Enter matrix array1
4 5 6
1 2 3
3 7 8
Enter matrix array2
n
5 6 9
8 5 3
2 9 1
tio
The product matrix is
72 103 57
27 43 18
87 125 56
Example: Program to find the transpose of a given matrix.
#include <stdio.h>
void main()
{
int array[10][10], i, j, m, n;
lu
printf("Enter the order of the matrix \n"); scanf("%d %d", &m, &n);
printf("Enter the coefiicients of the matrix\n");
for (i = 0; i < m; ++i)
So
for (j = 0; j < n; ++j)
scanf("%d", &array[i][j]);
printf("Transpose of matrix is \n");
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
printf(" %d", array[i][j]);
}
U
printf("\n");
}
}
Output:
VT
51
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
void main()
{
int n, p;
tio
printf(“enter a number”);
scanf(“%d”,&n);
p= square(n);
printf(“The square of the number is %d”,p);
}
Output:
enter a number
4
lu
The square of the number is 16
p=cube(n);
printf(“The cube of the number is %d”,p);
}
Output:
VT
enter a number
4
The cube of the number is 64
Example: Program to calculate the power of a number using recursion.
#include <stdio.h>
int power(int base, int exp)
{
if ( exp!=1 )
return (base*power(base,exp-1));
}
52
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
void main()
{
int base, exp;
printf("Enter base number: ");
scanf("%d", &base);
printf("Enter power number(positive integer): ");
scanf("%d", &exp);
printf("%d^%d = %d", base, exp, power(base, exp));
n
return;
}
Output:
tio
Enter base number: 3
Enter power number(positive integer): 3
3^3 = 27
Example: Program to print fibonacci series using recursion.
#include<stdio.h>
int Fib(int n)
{
}
void
if ( n == 0 )
else if ( n == 1 )
else
main()
return 0;
return 1;
lu
return Fib(n-1)+Fib(n-2);
So
{
int n, i = 0, c;
printf("enter n value: ");
scanf("%d",&n);
printf("Fibonacci series: ");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d \t", Fib(i));
i++;
U
}
}
Output:
enter n value: 7
VT
Fibonacci series : 0 1 1 2 3 5 8
53
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
int n;
printf("Enter an positive integer: "); scanf("%d", &n);
printf("Factorial of %d = %ld", n, fact(n));
tio
return;
}
Output:
Enter an positive integer: 6
Factorial of 6 = 720
Example: Program to solve tower-of-hanoi problem using recursion
#include <stdio.h>
{
if (num == 1)
{ lu
void towers(int num, char frompeg, char topeg, char auxpeg)
So
printf("\n Move disk 1 from peg %c to peg %c", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("\n Move disk %d from peg %c to peg %c", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}
void main()
{
U
int num;
printf("Enter the number of disks : "); scanf("%d", &num);
printf("The sequence of moves involved in the Tower of Hanoi are :\n");
towers(num, 'A', 'C', 'B');
VT
}
Output: Enter the number of disks : 3
The sequence of moves involved in the Tower of Hanoi are :
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C
54
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
temp = list[i];
list[i] = list[j];
list[j] = temp;
tio
}
}
}
printf("Key not found\n");
void main()
{
U
55
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
Ex: The structure definition to hold the student information such as name,
roll_number and average_marks can be written as shown below:
tio
struct student Size of each member in bytes
{
char name[10]; 10
int roll_number; 4
float average_marks; 8
};
Structure declaration lu
members of structure Total size = 22
So
“How to declare a structure?” As variables are declared before they are used
in the function, the structures are also should be declared before they are
used. A structure can be declared using three different ways as shown below:
Tagged structures
Structure variables
Type defined structures
U
Definition: The structure definition with tag name is called tagged structure.
The tag name is the name of the structure. The syntax of tagged structure is
shown below:
VT
struct tag_name
{
type1 member1;
type2 member2;
curly braces …… ……
…… ……
}; Note: semicolon is must at the end
For example, consider the following structure definition:
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
struct student
{
char name[10]; 10 bytes
int roll_number; 4 bytes
float average_marks; 8 bytes
}; Total: 22 bytes
n
Structure variables
The syntax of structure definition and declaration using structure variables is
shown below:
tio
struct
{
type1 member1;
type2 member2;
curly braces …… ……
…… ……
lu
} v1, v2,…..vn ; Note: semicolon is must at the end of variables
structure variables
So
For example, consider the following declaration:
struct
{
char name[10]; 10 bytes
int roll_number; 4 bytes
float average_marks; 8 bytes
} cse, ise; Total: 22 bytes
U
where
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
syntax shown) which in turn ends with semicolon. Note that TYPE_ID is
not a variable, instead it is a user-defined data type.
tio
typedef struct
{
char name[10];
int roll_number;
float average_marks;
} STUDENT;
lu
Since STUDENT is the type created by the user, it can be called as user-
defined data type. From this point onwards we can use STUDENT as data
type and declare the variables. For example, consider the following
So
declaration:
This statement declares that the variables cse and ise are variables of type
STUDENT.
U
Method 2: Here, we use the tag for the structure and then we obtain the user-
defined data type using the keyword typdef. For example, consider the
structure definition:
VT
/* Structure definition */
struct student Note: student is the tag name
{
char name[10];
int roll_number;
float average_marks;
}; /* No memory is allocated for structure
*/
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
The user-defined data type can be obtained using the keyword typdef as
shown below:
n
shown below:
/* Structure declaration */
STUDENT cse, ise; /* Memory is allocated for the
tio
variables */
Structure initialization
struct employee
{
char name[20]; lu
when the variables are declared as shown below:
Memory representation
name M O N A L I K A \0
So
int salary; salary 10950
int id;
id 2001
} a = {"MONALIKA", 10950, 2001};
a
initializers
Method 2: Specify the initializers within the braces and separated by commas
when the variables are declared as shown below:
/* structure definition */
struct employee
U
};
/* structure declaration and initialization */
struct employee a = {"MONALIKA", 10950, 2001};
Accessing structures
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
int salary 10950
int id;
id 2001
} a = {"MITHIL", 10950, 2001};
a
tio
The various members can be accessed using the variable a as shown below:
By specifying a.name we can access the name "MITHIL".
By specifying a.salary we can access the value 10950
By specifying a.id we can access the value of 2001
Programming statements
printf(“%s\n”, a.name);
lu
Now, the question is “How to display the various members of a structure?”
The various values can be accessed and printed as shown below:
MITHIL
Output
So
printf(“%d\n”, a.salary); 10950
printf(“%d\n”, a.id); 2001
Once we know how to display the members of a structure, let us see “How to
read the values for various members of a structure?” We know that format
specifications such as %s %d %d are used to read a string, an integer and a
float. The same format specifications can be used to read the members of a
structure. For example, we can read the name of an employee, the salary and
id as shown below:
U
gets(a.name);
scanf(“%d”, &a.salary);
scanf(“%d”, &a.id);
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
Total : 21
Observe that total size of the structure = 21 bytes. If 2000 is the starting address of
tio
the first member, then the starting address of each member depends on size of
previous member. The complete memory map along with addresses is shown below:
lu
200
200
200
200
200
200
200
200
200
200
201
201
201
201
201
201
201
201
0
6
8 4 8
bytes bytes 1 bytes
byte
21 bytes
So
Observe that the values of the members are stored in increasing address locations in
the order specified in the structure definition.
That is, address of name < address of id < address of salary and the address of
So, address of member id = starting address of member name + size of member name
= 2000 + 8
= 2008
VT
Address of member salary = starting address of member sex + size of member sex
= 2012 + 1
= 2013
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Note: Observe that some members have odd addresses and some members have
even addresses. For example, members such as name, id and sex have even
addresses whereas the member salary has odd address. In such situation,
microprocessor accesses the data stored in even addresses faster than the data stored
in odd addresses. So, it is the responsibility of the compiler to allocate the memory
for members such that they have even addresses so that the data can be accessed
very fast. This leads to slack bytes.
n
Structure operations
tio
Copying of structure variables: Copying from one structure variable to other structure
variable is achieved using assignment operator provided both structures are of the same type.
For example, consider the structure definition and declaration statements shown below:
struct struct
{
} a, b;
int salary;
int id;
lu
char name[10];
{
} c, d;
char name[10];
int salary;
int id;
So
Note: Observe that even though the members of both structures are same in number
and type, both are considered to be of different structures. Hence,
d = c; d = b;
In the previous section, we have seen that copying of two structure variables of same
type is allowed. But, we should remember that comparing of two structure variables
of same type or dissimilar type is not allowed. For example, the following operations
are invalid, even though a and b are of the same type.
However, the members of two structure variables of same type can be compared using
relational operators. For example,
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Note: The arithmetic, relational, logical and other various operations can be
performed on individual members of structures but not on structure variables. But, if
we want to compare we can do so by comparing the individual members of a
n
structure.
Uses of structures
tio
Now, let us see “What is the use of structures?”
arguments.
lu
Can be used to pass arguments so as to minimize the number of function
When more than one data has to be returned from the function, then
structures can be used.
So
Extensively used in applications involving database management
To make the program more readable.
have the same addresses. At any given point during execution, only one
member is active.
Now, let us see “How union is declared and used in C?" The general
VT
union tag_name
{
type1 member1;
type2 member2;
curly braces …… ……
…… ……
}; Note: semicolon is must
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Ex: The union definition to hold the various informations such as integer, char
and double values can be written as shown below:
// union definition
typedef union members of union Here, i, d and c are the fields
{ of the union. They are also
int i; called members of the union.
double d;
n
No space is reserved for the
char c; above union.
} item;
tio
Now, consider the following declaration along with memory representation:
x
c
1 byte
item x;
lu i
4 bytes
d
So
8 bytes
By looking at the above declaration, the compiler will reserve the memory
whose size is that of the largest member . Since double is the largest data
type of the member of the union, sizeof(double) = 8 bytes of memory is
reserved for the variable x.
Observe that all the members have the same starting address and hence
they share the same allocated space
Now, let us consider two programs to show that union and structures behave
U
differently.
#include <stdio.h>
void main()
{
typedef union
{
int marks;
char grade;
float percentage;
} STUDENT;
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
STUDENT x;
Output
x.marks = 100;
printf("Marks : %d\n",x.marks);
Marks: 100
x.grade = 'A';
Grade: A
printf("Grade : %c\n",x.grade);
n
Percentage:
99.5
x.percentage = 99.5;
printf("Percentage: %f\n", x.percentage);
tio
}
Note: It is observed from the above output that only one member of union can
hold a value at a time. It is not possible to access all the members
simultaneously. So, the variable of type STUDENT can be treated as integer
variable or char variable or float variable. Now, consider the same program
with structure.
#include <stdio.h>
void main()
VT
{
typedef struct
{
int marks;
char grade;
float percentage;
} STUDENT;
STUDENT x;
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
x.marks = 100;
x.grade = 'A';
x.percentage = 99.5; Output
n
}
Note: It is observed from the above output that the all the members of a
structure can hold individual values at a time. It is possible to access all the
tio
members of a structure simultaneously. Now to answer the question “What is
the difference between a structure and union?”
Structure Union
1. The keyword struct is used to define a 1. The keyword union is used to
structure define a union.
indicates that memory for each that every member begins at offset
member will start at different offset zero.
values
5. Individual members can be 5. Only one member can be accessed at
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
File Handling
What are we studying in this chapter?
Defining a file
Opening and closing of files
Input and output operations
n
Programming examples
14.1 Introduction
tio
We know that the functions scanf(), gets(), getchar() are used to enter the data from
the keyboard and printf(), puts() and putchar() are used to display the result on the
video display unit. This works fine when the input data is very small. But, as the
volume of input data increases, in most of the applications, we find it necessary to
store the data permanently on the disk and read from it. This can be done using files.
Now, let us see “What is a file?”
lu
Definition: A file is defined as a collection of data stored on the secondary device
such as hard disk. An input file contains the same items we might have typed in from
the keyboard. An output file contains the same information that might have been sent
to the screen as the output from our program.
So
Now, let us see “What are the advantages of creating and using an input file (also
called data file)?” It is very convenient to read input from a data file than to enter
data interactively using the keyboard. The files are used for the following reasons:
It is very difficult to input large volume of data through terminals
It is time consuming to enter large volume of data using keyboard.
When we are entering the data through the keyboard, if the program is terminated
for any of the reason or computer is turned off, the entire input data is lost.
U
To overcome all these problems, the concept of storing the data in disks was
introduced. Here, the data can be stored on the disks; the data can be accessed as and
when required and any number of times without destroying the data. The data is
stored on the disk in the form of a file.
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
When we type the text, we may enter any sequence of characters such as letters,
digits, symbols such as ; : ? # $ and so on and insert tab characters, spaces and
newline characters. All these symbols we store in a text file.
Definition: A file that contains sequence of printable characters such as letters, digits,
n
symbols such as ; : ? # $ and so on including white space characters such as spaces,
tabs and newline characters is called a text file. All the symbols that we type are
stored as a stream of characters and can be processed sequentially.
The text files are in human readable form
tio
They can be created and read using any text editor.
We can read or write one character at a time.
We can read or write one line at a time.
Now, let us see “What are the various steps to be performed when we do file
manipulations?” The various steps to be performed when we do file manipulations
are shown below:
Steps in using lu
Declare a file pointer variable
Open a file
So
the files Read the data from the file or write the data into file
Close the file
U
VT
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Definition: FILE is type defined structure and it is defined in a header file “stdio.h”.
So, FILE can be used as a data type.
It is derived using basic data types such as short, char etc., with the help of the
n
keyword struct.
FILE is a derived data type.
FILE is not a basic data type in C language.
tio
Now, let us see, “How to declare a file pointer variable?” A file pointer variable can
be declared using the derived data type FILE as shown below:
FILE *fp;
where
lu
FILE is the derived data type defined in the header file “stdio.h”. Since, FILE
is defined in “stdio.h”, we have to include the file “stdio.h” in the beginning of
the program.
Since fp is a pointer variable, it is the responsibility of the programmer to point
So
fp to the opened file.
The program segment that shows the declaration of a file pointer is shown below:
#include <stdio.h>
void main()
{
FILE *fp; /* Here, fp is a pointer to a structure FILE */
U
Analogy: The information of all the students in a college is maintained by the college
office. The information of a particular student such as name, address, branch and
semester details along with CET ranking, percentage of marks in PUC etc. is stored in
a file. If we want to read, write or update the student details we have to open a file,
update a file and finally close it. The same sequence of operations can be carried out
with respect to files in C also. Here too, before updating a file, it has to be opened and
after updating the file, it has to be closed.
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Now, let us see “What are the various modes in which a file can be opened/created
successfully?” The various modes in which a file can be opened successfully along
with meanings are shown below:
Mode Meaning
n
“r” opens a file for reading. The file must exist.
“w” creates an empty file for writing. If file does not exist, a new file is
created. If a file already exists with the same name, the contents of the file
tio
are erased and the file is considered as a new empty file.
“a” Append to a file. The data is written at the end of the existing file. If a file
does not exist, a new file is created and we can start writing into the file
from the beginning.
“r+” Opens a file for both reading and writing. The file must exist.
"w+"
"a+"
lu
Creates an empty file for both reading and writing.
Opens a file for reading and appending.
So
14.2 Opening and closing the files
Once we know various modes in which a file can be opened, let us see how to open a
file using fopen(). Now, let us see “What is fopen()? What is its syntax?
a new file can be created to write information into the file. This can be done by
opening the file in write mode using “w”.
an existing/non-existing file can be opened so that new data can be written at the
end of the file. This is called appending. This can be done by opening the file in
VT
#include <stdio.h>
FILE *fp;
……..
……..
fp = fopen(char *filename, char *mode)
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
where
fp is a file pointer of type FILE
filename holds the name of the file to be opened.
mode can be “r” or “w” or “a”
Return values The function may return the following:
A file pointer to the beginning of the opened file, if the file is opened
successfully.
n
NULL otherwise.
If the file pointer fp is not NULL, the necessary data can be accessed from the
tio
specified file. If a file cannot be opened successfully for some reason, the function
returns NULL. We can use this NULL character to test whether a file has been
successfully opened or not using the statement:
if (fp == NULL)
{
}
exit(0);
lu
printf(“Error in opening the file\n”);
Now, let us see “What is flose()? Why it is used” flose() is a function using which
An existing file can be closed. When we no longer need a file, we should close the
file.
This is the last operation to be performed on a file.
This ensures that all buffers are flushed
U
fclose(fp);
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
The following set of instructions are used to open the file “input.txt”
#include <stdio.h>
n
FILE *fp;
tio
Now, let us see “What will happen if the non-existing file is opened in read mode?
When the function fopen() is executed and if the file does not exist, the function
fopen() returns NULL. In this situation, we display the message “Error in opening the
file” as shown below:
if (fp == NULL)
{
lu
printf(“Error in opening the file”);
exit(0);
// If the file does not exist
So
}
“What will happen if the existing file is opened in read mode? If the file is existing,
the function fopen() returns a pointer to the file which points to the beginning of the
file and it is copied into file pointer variable fp as shown in figure below:
input.txt
Sai Vidya Institute of Technology∆
U
fp EOF
The final program segment to open an existing/non-existing file can be written as
shown below:
VT
#include <stdio.h>
FILE *fp;
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
exit(0); // terminate
}
n
14.2.2 Open the file for writing
To open a file for writing, we use the same procedure as given in previous section.
tio
But, the file mode has to be changed from “r” to “w”. Suppose, the file “input.txt” has
to be opened for writing. We can use the following instructions.
#include <stdio.h>
FILE *fp;
fp = fopen(“input.txt”, “w”);
When fopen() is executed in write mode “w”, three situations may arise.
1) Read only file exists.
2) Normal file exists.
So
3) File does not exist.
Case 1: Read only file exists: Now, let us see “What will happen if a read only file is
opened in write mode? Suppose, the read only file “input.txt” is opened for writing.
Since the file is read only, it should not be modified. So, the function fopen() returns
NULL. It indicates that it is an error and the file should not be opened. The code for
this can be written as shown below:
if (fp == NULL)
U
{
printf(“Error in opening the file”);
exit(0);
}
VT
Case 2: Normal file exists: Now, let us see “What will happen if a normal text file
which is already existing is opened in write mode? Suppose, the file “input.txt” exists
as shown below:
input.txt
Sai Vidya Institute of Technology∆
EOF
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Now, once fopen() is executed, the contents of the file are erased and file pointer
points to the beginning of the file as shown below:
input.txt
fp
n
Now, we can start writing into the file from fp onwards as if it is a new file. Suppose,
a string “Subject videos :www.saividya.ac.in” is written into the file. The contents of
the file are shown below:
tio
input.txt
Subject videos :www.saividya.ac.in∆
EOF
lu
So, when a normal file is opened in write mode, the contents of the given file are
deleted. The file pointer points to the beginning of the file and we can start writing the
characters into the file. Now, the file pointer will always points to the end of the file.
Case 3: File does not exist: Now, let us see “What will happen if non-existing file is
So
opened in write mode? Suppose, the file “input.txt” is opened for writing and the file
does not exist. Now, a new file “input.txt” is created and the function fopen() returns
a pointer to the beginning of the file and it is stored in the variable fp as shown below:
input.txt
U
fp
Now, we can start writing into the file from fp onwards. Suppose we write the string
“Sai Vidya Institute of Technology”, then the contents of the file is shown below:
VT
fp
EOF
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
So, when a non-existing file is opened in write mode, a new file is created and we can
write into the file. Now, the file pointer will always points to the end of the file. The
final program segment can be written as shown below:
#include <stdio.h>
FILE *fp;
n
fp = fopen(“input.txt”, “w”); // Create the file
tio
{
printf(“Error in opening the file”); // display error message
exit(0); // terminate
}
fclose(fp);
lu
// close the file
#include <stdio.h>
FILE *fp;
fp = fopen(“input.txt”, “a”); // Open the file in append mode
U
When fopen() is executed in append mode “a”, three situations may arise.
1) Read only file exists.
2) Normal file exists.
3) File does not exist.
VT
Case 1: Read only file exists: Now, let us see “What will happen if a read only file is
opened in append mode? Since the file is read only, it should not be modified. So, the
function fopen() returns NULL. It indicates that it is an error and the file should not
be opened. The code for this can be written as shown below:
if (fp == NULL)
{
printf(“Error in opening the file”);
exit(0);
}
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
So, when a read only file is oopened in append mode, we cannot perform any
operations on the file and hence after displaying the message “Error in opening the
file” the program is terminated.
Case 2: Normal file exists: Now, let us see “What will happen if a normal text file
which is already existing is opened in append mode? Suppose, the file “input.txt”
n
exists as shown below:
input.txt
Sai Vidya Institute ∆
tio
EOF
Now, once fopen() is executed, the file pointer points to the end of the file as shown
below:
input.txt
Sai Vidya Institute ∆
fp lu
So
Now, we can start appending into the file from fp onwards as if it is a new file. The
file after appending a sequence of characters “if Technology” is shown below:
fp
EOF
So, when a normal file is opened in append mode, we can insert the characters at the
end of the file. Now, the file pointer will always points to the end of the file.
VT
Case 3: File does not exist: Now, let us see “What will happen if non-existing file is
opened in append mode? Suppose, the file “input.txt” has to be opened for appending
and the file does not exist. Now, a new file “input.txt” is created and the function
fopen() returns a pointer to the beginning of the file and it is stored in the variable fp
as shown below:
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
input.txt
fp
Now, we can start appending into the file from fp onwards. When the string “Sai
Vidya Institute of Technology” is written into the file, the contents of the file are
n
shown below:
tio
fp
EOF
So, when a non-existing file is opened in append mode, a new file is created and we
lu
can write into the file. Now, the file pointer will always points to the end of the file as
shown in above figure. The final program segment can be written as shown below:
#include <stdio.h>
So
FILE *fp;
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Now, let us see “What is the use of fscanf() function? Explain with syntax”
fscanf: The function of fscanf and scanf are exactly same. Only change is that scanf
is used to get data input from keyboard, whereas fscanf is used to get data from the
file pointed to by fp. Because input is read from the file, extra parameter file pointer
n
fp has to be passed as the parameter. Rest of the functionality of fscanf remains same
as scanf. The syntax of fscanf() is shown below:
fscanf(fp, “format string”, list);
tio
where
fp is a file pointer. It can point to a source file or standard input stdin. If fp is
pointing to stdin, data is read from the keyword. If fp points to source file, the
data is read from the specified source file.
format string and list have the same meaning as in scanf() i.e., the variables
lu
specified in the list will take the values from the file specified by fp using the
specifications provided in format string.
The function returns EOF when it attempts to read at the end of the file;
Otherwise, it returns the number of items read in and successfully converted.
So
Example 14.1: Consider the following statement:
Suppose, fp points to the source file. After executing above statement, the values for
the variables id, name and avg_marks are obtained from the file associated with file
pointer fp. This function returns the number of items that are successfully read from
the file.
U
Now, let us see “What is the use of fprintf() function? Explain with syntax”
fprintf: The function of fprintf and printf are exactly same. Only change is that
printf is used to display the data onto the video display unit, whereas fprintf is used
to send the data to the output file pointed to by fp. Since file is used, extra parameter
file pointer fp has to be passed as parameter. Rest of the functionality of fprintf
remains same as printf. The syntax of fprintf() is shown below:
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
Example 14.3: Consider the following statement:
tio
After executing fprintf, the values of the variables id, name and avg_marks are
written into the file associated with file pointer fp. This function returns the number
of items that are successfully written into the file.
lu
fprintf(stdout, “%d %s %f”, id, name, avg_marks);
Example 14.5: C program to read n numbers from keyboard and write into a file
U
#include <stdio.h>
void main()
{
FILE *fp;
VT
int num;
if (fp == NULL)
{
printf(“Error in opening the file\n”);
exit(0);
}
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
14.3.2 Read from file and display on the screen
Now, let us write a program to read n numbers from the input file “input.dat” and
display on the screen.
tio
Example 14.6: C program to read n numbers from input file and display on the screen
#include <stdio.h>
void main()
{
FILE *fp;
int num;
fp = fopen(“input.dat”, “r”);
if (fp == NULL)
{ lu // input.dat : 10 20 30 40 50
So
printf(“Error in opening the file\n”);
exit(0);
}
while (fscanf(fp, “%d”, &num) > 0)
{ // Output
printf(“%d\n”, num); // 10 20 30 40 50
}
U
fclose(fp);
}
14.3.3 Read from two files and write into third file
VT
In this section, let us write the program for the following instance of the problem.
Given two university information files “studentname.txt” and “usn.txt” that contains
students Name and USN respectively. Write a C program to create a new file called
“output.txt” and copy the content of files “studentname.txt” and “usn.txt” into
output file in the sequence shown below. Display the contents of output file
“output.txt” on to the screen.
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Example 14.7: C program to read student name and usn from two different files and
n
write into a different file in the sequence
#include <stdio.h>
tio
void main()
{
FILE *fp1, *fp2, *fp3;
char name[20];
int usn;
fp1 = fopen(“studentname.txt”, “r”);
fp2 = fopen(“usn.txt”, “r”);
fp3 = fopen(“output.txt”, “w”);
lu // Open the name file in read mode
// Open the usn file in read mode
// Open the file in write mode
So
for(;;)
{
if ( fscanf(fp1, “%s”, name) > 0) // read name from 1st file
{
if (fscanf(fp2, “%d”, &usn) > 0) // read name from 2nd file
{
fprintf(fp3,”%s %d\n”, name, usn); // write to 3rd file
}
else break;
U
}
else break;
}
fclose(fp1); /* close all the files */
VT
fclose(fp2);
fclose(fp3);
}
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Pointers in C
Pointers like all other variables in C must be declared as such prior to use.
n
which indicates that ptr is a pointer to a variable of type type. For example
int *ptr ;
tio
declares a pointer ptr to variables of type int.
NB : The type of the pointer variable ptr is int *. The declaration of a pointer variable
normally sets aside just two or four bytes of storage for the pointer whatever it is defined
to point to.
lu
In 16-bit systems two byte pointers are termed near pointers and are used in small
memory model programs where all addresses are just segment offset addresses and 16
bits in length. In larger memory model programs addresses include segment and offset
addresses and are 32 bits long and thus pointers are 4 bytes in size and are termed far
pointers.
So
In 32-bit systems we have a flat address system where every part of memory is
accessible using 32-bit pointers.
For Example :-
U
int *m ;
int count=125, i ;/* m is a pointer to int, count, i are
integers */
m = &count ;
VT
The * operator is the complement of the address operator & and is normally termed the
indirection operator. Like the & operator it is a unary operator and it returns the value of
the variable located at the address its operand stores.
For Example :-
i = *m ;
1
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
assigns the value which is located at the memory location whose address is stored in m,
to the integer i. So essentially in this case we have assigned the value of the variable
count to the variable i. The final situation is illustrated below.
indirection
count i m
125 125 1000
n
1000 1724 1824
tio
One of the most frequent causes of error when dealing with pointers is using an
uninitialised pointer. Pointers should be initialised when they are declared or in an
assignment statement. Like any variable if you do not specifically assign a value to a
pointer variable it may contain any value. This is extremely dangerous when dealing with
pointers because the pointer may point to any arbitrary location in memory, possibly to
an unused location but also possibly to a memory location that is used by the operating
system. If your program tries to change the value at this address it may cause the whole
lu
system to crash. Therefore it is important to initialise all pointers before use either
explicitly in your program or when defining the pointer.
For Example :-
int var1, var2 ;
int *ptr1, *ptr2 = &var2 ;
int *ptr3 = NULL ;
U
...
ptr1 = &var1 ;
ptr1 and ptr2 are now pointing to data locations within the program so we are free to
VT
manipulate them at will i.e. we are free to manipulate the piece of memory they point to.
Call by Reference
Recall when we wanted to swap two values using a function we were unable to actually
swap the calling parameters as the call by value standard was employed. The solution to
the problem is to use call by reference which is implemented in C by using pointers as is
illustrated in the following example.
2
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
#include <stdio.h>
void main( )
{
int a, b ;
n
printf( "Enter two numbers" ) ;
scanf( " %d %d ", &a, &b ) ;
tio
printf( "a = %d ; b = %d \n", a, b ) ;
temp = *ptr2 ;
*ptr2 = *ptr1 ; lu
So
*ptr1 = temp ;
}
The swap() function is now written to take integer pointers as parameters and so is
called in main() as
swap( &a, &b ) ;
where the addresses of the variables are passed and copied into the pointer variables in
the parameter list of swap(). These pointers must be de-referenced to manipulate the
U
values, and it is values in the the same memory locations as in main() we are swapping
unlike the previous version of swap where we were only swapping local data values.
In our earlier call-by-value version of the program we called the function from main() as
VT
swap(a,b); and the values of these two calling arguments were copied into the formal
arguments of function swap.
In our call-by-reference version above our formal arguments are pointers to int
and it is the addresses contained in these pointers, (i.e. the pointer values), that are copied
here into the formal arguments of the function. However when we de-reference these
pointers we are accessing the values in the main() function as their addresses do not
change.
3
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
For Example :-
char str[80], *ptr ;
tio
ptr = str ;/* causes ptr to point to start of string str
*/
ptr = &str[0] ; /* this performs the same as above */
lu
as str is a constant pointer and so its value i.e. the address it holds cannot be changed.
Instead of using the normal method of accessing array elements using an index we can
use pointers in much the same way to access them as follows.
So
char str[80], *ptr , ch;
Note that the parentheses are necessary above as the precedence of * is higher than that of
+. The expression
VT
ch = *ptr + 1 ;
for example says to access the character pointed to by ptr ( str[0] in above example with
value ‘a’) and to add the value 1 to it. This causes the ASCII value of ‘a’ to be
incremented by 1 so that the value assigned to the variable ch is ‘b’.
In fact so close is the relationship between the two forms that we can do the following
ptr = x ;
4
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Pointer Arithmetic
n
Pointer variables can be manipulated in certain limited ways. Many of the manipulations
tio
are most useful when dealing with arrays which are stored in contiguous memory
locations. Knowing the layout of memory enables us to traverse it using a pointer and not
get completely lost.
Assignment
int count, *p1, *p2 ;
p1 = &count ;
directly
p2 = p1 ;
lu
// assign the address of a variable
The value a pointer holds is just the address of a variable in memory, which is normally a
four byte entity. It is possible to modify this address by integer addition and subtraction if
necessary. Consider the following we assume a 32-bit system and hence 32-bit integers.
ptr = array ;
array[0] 2008 100
array[1] 2012 101
array[2] 2016 102
VT
We now have the pointer variable ptr pointing at the start of array which is stored at
memory location 2008 in our illustration. Since we know that element array[1] is stored
at address 2012 directly after element array[0] we could perform the following to access
its value using the pointer.
ptr += 1 ;
This surprisingly will cause ptr to hold the value 1012 which is the address of array[1], so
we can access the value of element array[1]. The reason for this is that ptr is defined to be
5
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
a pointer to type int, which are four bytes in size on a 32-bit system. When we add 1 to
ptr what we want to happen is to point to the next integer in memory. Since an integer
requires four bytes of storage the compiler increments ptr by 4. Likewise a pointer to type
char would be incremented by 1, a pointer to float by 4, etc.
Similarly we can carry out integer subtraction to move the pointer backwards in memory.
ptr = ptr - 1 ;
n
ptr -= 10 ;
The shorthand operators ++ and -- can also be used with pointers. In our continuing
tio
example with integers the statement ptr++ ; will cause the address in ptr to be
incremented by 4 and so point to the next integer in memory and similarly ptr-- ; will
cause the address in ptr to be decremented by 4 and point to the previous integer in
memory.
NB : Two pointer variables may not be added together ( it does not make any logical
sense ).
lu
p1 = p1 + p2 ; /* illegal operation */
count = p2 - p1 ; /* legal */
The result of such an operation is not however a pointer, it is the number of elements of
the base type of the pointer that lie between the two pointers in memory.
U
Comparisons
We can compare pointers using the relational operators ==, <, and > to establish
whether two pointers point to the same location, to a lower location in memory, or to a
VT
higher location in memory. These operations are again used in conjunction with arrays
when dealing with sorting algorithms etc.
For Example :- Writing our own version of the puts() standard library function.
int i ;
n
void puts( const char *s ) // char *const s would make
pointer unalterable
tio
{
while ( *s )
putchar( *s++ ) ;
putchar( '\n' ) ;
}
As you can see by comparing the two versions above the second version using pointers is
lu
a much simpler version of the function. No extra variables are required and it is more
efficient as we will see because of its use of pointer indirection.
if ( palin( str ) )
printf( "%s is a palindrome\n", str ) ;
else
printf( "%s is not a palindrome\n") ;
VT
ptr = str ;
while ( *ptr )
ptr++ ; /* get length of string i.e. increment ptr while *ptr != '\0' */
ptr-- ; /* move back one from '\0' */
7
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
Strings and pointers
tio
C's standard library string handling functions use pointers to manipulate the strings. For
example the prototype for the strcmp() function found in <string.h> is
where const is a C keyword which locks the variable it is associated with and prevents
lu
any inadvertent changes to it within the function.
in both cases the compiler allocates just sufficient storage for both strings.
Arrays of Pointers
U
It is possible to declare arrays of pointers in C the same as any other 'type'. For example
int *x[10] ;
VT
To make one of the pointers point to a variable one might do the following.
x[ 2 ] = &var ;
*x[ 2 ]
8
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Passing this array to a function can be done by treating it the same as a normal array
which happens to be an array of elements of type int *.
For Example : -
void display( int *q[ ], int size )
{
n
int t ;
for ( t=0; t < size; t++ )
printf( "%d ", *q[t] ) ;
tio
}
Note that q is actually a pointer to an array of pointers as we will see later on with
multiple indirection.
puts( err[num] );
}
Note that using an array of pointers to char initialised as above conserves space as no
blank filling characters are required as would be if we used
U
char err[3][30] = {
... } ;
VT
c:>type text.dat
9
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
where the name of the file to be printed is taken into the type program and the contents of
the file then printed out.
In C there are two in-built arguments to the main() function commonly called argc and
argv which are used to process command line arguments.
n
...
}
tio
argc is used to hold the total number of arguments used on the command line which is
always at least one because the program name is considered the first command line
argument.
argv is a pointer to an array of pointers to strings where each element in argv points to a
command line argument. For example argv[0] points to the first string, the program
name.
arguments.
#include <stdio.h>
lu
For Example :- Program to print a name ( saved in name.c ) using command line
c:\>name tom
VT
For Example :- Program to count down from a given value, the countdown being
displayed if the argument "display" is given.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
10
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
{
int disp, count ;
if ( argc < 2 )
{
puts("Missing Arguments Usage : progname count [display]" );
exit(1) ;
}
n
if ( argc > 2 && !strcmp( argv[2], "display" ) )
disp = 1 ;
tio
else
disp = 0 ;
lu
NB : C has a broad range of functions to convert strings into the standard data types and
vice versa. For example atoi() converts a string to an integer above - remember all
command line arguments are just character strings.
So
Dynamic Memory Allocation
This is the means by which a program can obtain and release memory at run-time. This is
very important in the case of programs which use large data items e.g. databases which
may need to allocate variable amounts of memory or which might have finished with a
U
particular data block and want to release the memory used to store it for other uses.
The functions malloc() and free() form the core of C's dynamic memory allocation and
are prototyped in <malloc.h>. malloc() allocates memory from the heap i.e. unused
VT
memory while available and free() releases memory back to the heap.
malloc() allocates num_bytes bytes of storage and returns a pointer to type void to the
block of memory if successful, which can be cast to whatever type is required. If malloc()
is unable to allocate the requested amount of memory it returns a NULL pointer.
11
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
For example to allocate memory for 100 characters we might do the following
#include <malloc.h>
void main()
{
char *p ;
n
if ( !( p = malloc( sizeof( char ) * 100 ) )
{
puts( "Out of memory" ) ;
tio
exit(1) ;
}
}
The return type void * is automatically cast to the type of the lvalue type but to make it
more explicit we would do the following
lu
if ( !( (char * )p = malloc( sizeof( char ) * 100 ) )
{
puts( "Out of memory" ) ;
exit(1) ;
}
So
To free the block of memory allocated we do the following
free ( p ) ;
Note :- There are a number of memory allocation functions included in the standard
library including calloc( ), _fmalloc( ) etc. Care must be taken to ensure that memory
allocated with a particular allocation function is released with its appropriate deallocation
function, e.g. memory allocated with malloc() is freed only with free() .
U
VT
In the normal situation, single indirection, a pointer variable would hold the address in
memory of an appropriate variable, which could then be accessed indirectly by de-
referencing the pointer using the * operator.
12
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
In the case of double indirection, we have the situation where a variable may be pointed
to by a pointer as with single indirection, but that this pointer may also be pointed to by
another pointer. So we have the situation where we must de-reference this latter
pointer twice to actually access the variable we are interested in. De-referencing the
pointer to a pointer once gives us a normal singly indirected pointer, de-referencing the
pointer to a pointer secondly allows us to access the actual data variable. The situation is
depicted in the diagram below.
n
single indirection single indirection
tio
double_ptr single_ptr variable
address 2 address 3 value
double indirection
lu
To declare a pointer to a pointer we include another indirection operator
float * * ptr ;
So
which in this case defines a pointer to a pointer to type float.
p = &x ;
q = &p ;
U
13
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
arrays of n doubles,
the rows
pointerto
array of m
tio
pointer to
double pointers to rows
ptr_rows
lu
So
#include <stdio.h>
#include <malloc.h>
_flushall() ;
user_ptr = ptr_rows ;
for ( i = 0; i < m ; i++ ) // and then
row elements
{
*user_ptr = (double *) malloc( n * sizeof( double ) ) ;
elem_ptr = *user_ptr ;
for ( j = 0; j < n ; j++ )
*elem_ptr++ = 1.0 ;
14
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
for ( i = 0; i < n; i++ )
free( *user_ptr ++ ) ; // free a row and move onto next
tio
free( ptr_rows ) ; // free pointers to rows
Pointers to Functions
lu
A function even though not a variable still has a physical address in memory and this
address may be assigned to a pointer. When a function is called it essentially causes an
execution jump in the program to the location in memory where the instructions
So
contained in the function are stored so it is possible to call a function using a pointer to a
function.
The address of a function is obtained by just using the function name without any
parentheses, parameters or return type in much the same way as the name of an array is
the address of the array.
where fptr is declared to be a pointer to a function which takes parameters of the form
indicated in the parameter list and returns a value of type ret_type.
VT
The parentheses around * fptr are required because without them the declaration
int (*fptr)( ) ;
15
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
ch = (*fptr)( ) ;
ch = fptr( ) ;
n
Example :- Program to compare two strings using a comparison function passed as a
parameter.
tio
#include <stdio.h>
#include <string.h>
void check( char *a, char *b, int ( * cmp ) ( ) );
void main( )
{
char s1[80], s2[80] ;
int (*p)( ) ;
p = strcmp ;
gets(s1) ; lu
So
gets( s2 );
Note that even though we do not specify parameters to the function pointer in the
VT
prototype or declarator of the function we must specify them when actually calling the
function.
Note also that instead of using an explicitly declared pointer variable to call the required
function in main() we could make the call as follows
16
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
For Example : Program that may check for either numeric or alphabetic equality.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
n
int numcmp( char *, char * ) ;
void main( )
tio
{
char s1[80], s2[80] ;
gets(s1) ;
gets( s2 );
else
}
lu
check( s1, s2, strcmp ) ;
if ( atoi( a ) == atoi( b ) )
return 0 ;
else
return 1 ;
VT
Efficiency Considerations
When used correctly pointers can lead to more efficient code in situations where
sequential operations on contiguous blocks of memory are required.
For example when accessing each element of an array sequentially. The inefficient way
to do this is
17
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
When done this way the compiler has to index into the array for each iteration of the
loop. This involves reading the current value of the index, k, multiplying this by the
sizeof( double ) and using this value as an offset from the start of the array.
n
ptr = array ;
for ( k = 0; k < 100; k++ )
tio
*( ptr + k ) = 0.0 ;
whereas the most efficient solution is of course to do the following where the pointer
itself is moved by the appropriate amount.
ptr = array ;
for ( k = 0; k < 100; k++ )
*ptr++ = 0.0 ;
lu
In this case we just incur the addition of sizeof( double ) onto the address contained in the
pointer variable for each iteration.
So
Pre-Processor Directives
We know that compiler accepts the program written in high level language and converts
it into machine language. The C compiler is used to convert all C programs into machine
language. The C compiler is made up of two separate programs: the preprocessor and
the translator. In this section, we shall concentrate on the first program called
U
preprocessor.
18
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
part of instruction
The various activities performed by the preprocessor are shown below:
tio
C Language – The Preprocessor
The Preprocessor, Preprocessor directives, Macros, #define identifier string, Simple macro
substitution, Macros as arguments, Nesting of macros, Undefining a macro and File inclusion.
The Preprocessor
lu
A unique feature of c language is the preprocessor. A program can use the tools provided by
preprocessor to make his program easy to read, modify, portable and more efficient.
Preprocessor is a program that processes the code before it passes through the compiler. It operates
So
under the control of preprocessor command lines and directives. Preprocessor directives are placed in
the source program before the main line before the source code passes through the compiler it is
examined by the preprocessor for any preprocessor directives. If there is any appropriate actions are
taken then the source program is handed over to the compiler.
Preprocessor directives follow the special syntax rules and begin with the symbol #bin column1 and
do not require any semicolon at the end. A set of commonly used preprocessor directives
U
VT
Preprocessor directives:
Directive Function
#define Defines a macro substitution
#undef Undefines a macro
#include Specifies a file to be included
#ifdef Tests for macro definition
#endif Specifies the end of #if
#ifndef Tests whether the macro is not def
#if Tests a compile time condition
19
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Macros:
n
Macro substitution is a process where an identifier in a program is replaced by a pre defined string
composed of one or more tokens we can use the #define statement for the task.
tio
It has the following form
The preprocessor replaces every occurrence of the identifier int the source code by a string. The
lu
definition should start with the keyword #define and should follow on identifier and a string with at
least one blank space between them. The string may be any text and identifier must be a valid c name.
There are different forms of macro substitution. The most common form is
So
1. Simple macro substitution
2. Argument macro substitution
3. Nested macro substitution
#define pi 3.1415926
Writing macro definition in capitals is a convention not a rule a macro definition can include more
than a simple constant value it can include expressions as well. Following are valid examples:
VT
Macros as arguments:
The preprocessor permits us to define more complex and more useful form of replacements it takes
the following form.
20
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Notice that there is no space between identifier and left parentheses and the identifier f1,f2,f3 …. Fn is
analogous to formal arguments in a function definition.
There is a basic difference between simple replacement discussed above and replacement of macro
arguments is known as a macro call
n
# define CUBE (x) (x*x*x)
tio
If the following statements appears later in the program,
volume=CUBE(side);
volume =(side*side*side)
Nesting of macros:
lu
We can also use one macro in the definition of another macro. That is macro definitions may be
So
nested. Consider the following macro definitions
# define SQUARE(x)((x)*(x))
Undefining a macro:
# undef identifier.
This is useful when we want to restrict the definition only to a particular part of the program.
VT
File inclusion:
The preprocessor directive " #include file name” can be used to include any file in to your
program if the function s or macro definitions are present in an external file they can be included in
your file
In the directive the filename is the name of the file containing the required definitions or functions
alternatively the this directive can take the form
21
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Without double quotation marks. In this format the file will be searched in only standard directories.
The c preprocessor also supports a more general form of test condition #if directive. This takes the
following form
n
{
statement-1;
tio
statemet2’
….
….
}
#endif
lu
the constant expression can be a logical expression such as test < = 3 etc
So
If the result of the constant expression is true then all the statements between the #if and #endif are
included for processing otherwise they are skipped. The names TEST LEVEL etc., may be defined as
macros.
U
VT
22
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Data Structures
At the heart of virtually every computer program are its algorithms and its data structures.
It is hard to separate these two items, for data structures are meaningless without
algorithms to create and manipulate them, and algorithms are usually trivial unless there
n
are data structures on which to operate.
Data type specifies the type of data stored in a variable. The data type can be classified
tio
into two types Primitive data type and Non-Primitive data type
PRIMITIVE DATATYPE
The primitive data types are the basic data types that are available in most of the
programming languages. The primitive data types are used to represent single values.
Eg: 12, 90
lu
Integer: This is used to represent a number without decimal point.
Float and Double: This is used to represent a number with decimal point.
So
Eg: 45.1, 67.3
NON-PRIMITIVE DATATYPES
The data types that are derived from primary data types are known as non-Primitive
data types. These datatypes are used to store group of values.
Arrays
Structure
Union
23
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
linked list
Stacks
Queue etc
Data Structures:
A data structure is an arrangement of data in a computer's memory or even disk storage.
Data structures can be classified into two types
n
Linear Data Structures
tio
Non Linear Data Structures
In programming each program is breakdown into modules, so that no routine should ever
U
exceed a page. Each module is a logical unit and does a specific job modules which in
turn will call another module.
24
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
The basic idea of implementing ADT is that the operations are written once in program
and can be called by any part of the program.
n
A1, A2, A3, ..... ,AN
tio
A1 - First element of the list
If the element at position i is Ai then its successor is Ai+1 and its predecessor is Ai-1.
lu
1. Insert (X, 5) - Insert the element X after the position 5.
So
2. Delete (X) - The element X is deleted
1. Array Implementation
3. Cursor Implementation.
25
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
* Insertion and Deletion operation are expensive as it requires more data movement
* Even if the array is dynamically allocated, an estimate of the maximum size of the
n
Linked List Implementation
Linked list consists of series of nodes. Each node contains the element and a pointer to its
tio
successor node. The pointer of the last node points to NULL.
Insertion and deletion operations are easily performed using linked list.
A singly linked list is a linked list in which each node contains only one link field
pointing to the next node in the list.
•Linked list
–An ordered sequence of nodes with links
U
sat
bat
•
•
•Linked list may be represented in mmemory: Data[ ], Link[ ]
0
vat
n
1
4
2 cat
tio
3
4 sat 1
6
lu bat 2
So
Singly Linked Lists(Cont.)
•Insertion
27
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
first
n
tio
Delete mat from list
Stack :
lu
Stack is a Linear Data Structure which follows Last in First Out mechanism.
It means: the first element inserted is the last one to be removed
So
Stack uses a variable called top which points topmost element in the stack. top is
incremented while pushing (inserting) an element in to the stack and decremented while
poping (deleting) an element from the stack
top
D
U
top
C top C C
B top B B B
A top A A A A
VT
28
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
n
Applications of Stack:
tio
Stacks are used in recursion programs
Stacks are used in function calls
Stacks are used in interrupt implementation
Queue Model lu
So
A Queue is a linear data structure which follows First In First Out (FIFO) principle, in
which insertion is performed at rear end and deletion is performed at front end.
Operations on Queue
1. Enqueue
2. Dequeue
VT
Enqueue :
Dequeue :
Exception Conditions
29
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
Overflow : Attempt to insert an element, when the queue is full is said to be overflow
condition.
Underflow : Attempt to delete an element from the queue, when the queue is empty is
said to be underflow
Applications of Queue
n
* Batch processing in an operating system
tio
* Priority Queues can be used to sort the elements using Heap Sort.
* Simulation.
lu
* Computer networks where the server takes the jobs of the client as per the queue
strategy.
So
U
VT
30
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
TREES
3.1 PRELIMINARIES :
TREE : A tree is a finite set of one or more nodes such that there is a specially
designated
n
node called the Root, and zero or more non empty sub trees T1, T2....Tk, each of
tio
whose roots are connected by a directed edge from Root R.
lu
grouped into subsets, each of which is itself a tree. This hierarchical relationship is
described by referring to each such subtree as a child of the root, while the root is referred
to as the parent of each subtree. If a tree consists of a single node, that node is called a
leaf node.
So
Figure 3.4: A simple tree.
U
Fig. 3.4 is different from the one in which nodes E and F are interchanged. Thus it makes
sense to say that the first subtree at A has 4 leaf nodes.
Example 3.4 Show how to implement the Abstract Data Type tree using lists.
Solution We write [A B C] for the list containing three elements, and distinguish A from
[A]. We can represent a tree as a list consisting of the root and a list of the subtrees in
order. Thus the list-based representation of the tree in Fig 3.4 is
31
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
LEAF : A node which doesn't have children is called leaf or Terminal node.
n
SIBLINGS : Children of the same parents are said to be siblings,. F, G are siblings.
PATH : A path from node n, to nk is defined as a sequence of nodes n1, n2,n3....nk such
that ni is the parent of ni+1. for . There is exactly only one path from each node to
tio
root.
Definition :-
lu
Binary Tree is a tree in which no node can have more than two children.
So
Maximum number of nodes at level i of a binary tree is 2i-1.
A binary tree is a tree which is either empty, or one in which every node:
has no children; or
has just a left child; or
has just a right child; or
has both a left and a right child.
U
A complete binary tree is a special case of a binary tree, in which all the levels, except
perhaps the last, are full; while on the last level, any missing nodes are to the right of all
the nodes that are present. An example is shown in Fig. 3.5.
VT
32
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website
Downloaded from VTUSOLUTION.IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates
A complete binary tree: the only ``missing'' entries can be on the last row.
Example Give a space - efficient implementation of a complete binary tree in terms of an
array A. Describe how to pass from a parent to its two children, and vice-versa
Solution An obvious one, in which no space is wasted, stores the root of the tree in A[1];
the two children in A[2] and A[3], the next generation at A[4] up to A[7] and so on. An
element A[k] has children at A[2k] and A[2k+1], providing they both exists, while the
parent of node A[k] is at A[k div 2]. Thus traversing the tree can be done very
n
efficiently.
tio
GENERAL TREE & BINARY TREE
lu
number of children. more than two children.
= 15 nodes.
A complete binary tree of height h has between 2h and 2h+1 - 1 nodes. In the bottom level
the elements should be filled from left to right.
There are two ways for representing binary tree, they are
* Linear Representation
* Linked Representation
33
Online Chat Support Projects | Technical Seminar Guidance & Support Download our app or visit website