Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C Programming PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 171

Downloaded from VTUSOLUTION.

IN NOTES | INTERNSHIP | VIDEO LECTURE Like us on FB for regular updates

Subject: Computer Programming in C and data Structures

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

Working principle of a computer involves following steps

Instruction phase
VT

– Step 1: Fetch instruction from the memory


– Step 2: Decode instruction
Execution phase
– Step 3: Execute the instruction
– Step 4: Store the results

Now the question is how to write such Instructions?

Hence we require a programming language to communicate with machine by writing


instructions. Instruction can be written in Machine language or assembly language or High level
language.

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

3. High level languages


 The set of commands available in high level language is very simple and
U

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 ?

 A programming is a tool for developing executable models for a class of problem


domains.

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 programming language is a notational system for describing computation in a


machine-readable and human-readable form.
 A vocabulary and set of grammatical rules for instructing a computer to perform
specific tasks. It usually refers to high-level languages, such as BASIC, C, C++, etc…

• 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

underlying technology considerations. It summarizes a program’s steps (or flow) but


excludes underlying details. Hence, By describing a program in pseudocode, programmers
of all types of languages can understand the function of a program.
VT

Example

If student's marks is greater than or equal to 35


Print "pass"
else
Print "fail “

• 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

Example to demonstrate some of the flowcharts are

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

Psedocode to calculate class average grade

: Determine the average grade of a class


Initialize Counter and Sum to 0

Do While there are more data

n
Get the next Grade

Add the Grade to the Sum

tio
Increment the Counter

Loop

Compute Average = Sum / Counter

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

History of C Programming Language


 The C programming language was designed by

Dennis Ritchie at Bell Laboratories in the early 1970s

n
tio

 Influenced by following previous High level languages


ALGOL 60 (1960

CPL (Cambridge, 1963),


lu ),
So
• BCPL (Martin Richard, 1967), (Basic Combined Programming Language)

• B (Ken Thompson, 1970)

B language is modified by Ritchie and new Language is named as C

 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

 Standardized in 1989 by ANSI (American National Standards Institute)


known as ANSI C
VT

 International standard (ISO) in 1990 which was adopted by ANSI and is


known as C89

 As part of the normal evolution process the standard was updated in


1995 (C95) and 1999 (C99)

Characteristics of C Programming languages:

 Direct access to memory layout through pointer manipulation

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

 Concise syntax, small set of keywords


 Block structured language
 Some encapsulation of code, via functions
 Type checking (pretty weak)
 C is portable(program written for one computer can be run on
another computer with little modification)
 C has an ability to extend itself.

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

Compilation process in UNIX/LINUX environment:


 To compile and link a C program that is contained entirely in one source file:

cc program.c

 The executable program is called a.out by default.

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

Type the program in the editor


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

Run the Program by pressing (Ctrl+F9)

n
tio
lu
Output of the program will be displayed as shown below:
So
U

General structure of C program


VT

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>

// program prints hello C world

Int main() {

n
printf ("Hello C world!");

tio
return 0;

Output: Hello C world!

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

• We can call those functions in our program by supplying parameters

• Header file is given an extension .h

• C Source file is given an extension .c


U

Example : # include <stdio.h>


VT

main ()
• This is the entry point of a program

• When a file is executed, the start point is the main function

• From main function the flow goes as per the programmers instructions.

• There may or may not be other functions written by user in a program

• Main function is compulsory for any c program

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

Comment lines in C Program:


• Single line comment (line starts with two slashes //)

– // (double slash)

– Termination of comment is by pressing enter key

• Multi line comment (starts with / * and end with */)

n
/*….

tio
…….*/

This can span over to multiple lines

Output Statement printf()

printf() statement is used to output the expression values and messages on


lu
to the output screen. General structure of printf() is

printf(“ message placeholder”, variables);


So
printf(“ value of c = %d”,c);
• printf() is a library function declared in <stdio.h>
• Syntax: printf( FormatString, Expr, Expr...)
– FormatString: String of text to print
– Exprs: Values to print
– FormatString has placeholders to show where to put the values (note: #placeholders
should match #Exprs)
– Placeholders: %s (print as string), %c (print as char),
U

%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;
}

Output: The Number is 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

Input statement scanf()


scanf (); //used to take input from console(user).

 scanf(“%d”, &a);

 Remember to use & symbol along with integer/floating variable.


Does not use at the time of reading character/string type data.

n
Some of the format specifier

%c for The character.

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

<<Data type>> <<variable name>>;

int a;

Initialization

n
<<varname>>=<<value>>;

a=10;

tio
Usage (updation)

<<varname>>

a=a+1; //increments the value of a by 1

Rules to declare a variable:



lu
Should not be a reserved words like int, float, sin etc..

Should start with a letter or an underscore(_)


So
• Can contain letters, numbers or underscore.

– Choose a name that reflects the role of the variable in a program, e.g.

• Good: customer_name, ss_number;

• Bad : cn, ss;

• No other special characters are allowed including space


U

• Variable names are case sensitive

– say variable A (Big letter) and a (small letter) are different

Some properties of a variable:


VT

• Represent storage units in a program

• Used to store/retrieve data over life of program

• Type of variable determines what can be placed in the storage unit

• Assignment – process of placing a particular value in a variable

• Variables must be declared before they are assigned

• 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

• Six types of tokens are: keywords, identifiers(variables),constants, string literals,


operators and other separators

keywords- reserved words for example sqrt,pow,sin,int

identifiers- names given to variables example: a,sum

n
Constants: integer, floating and character example: 10,10.0

tio
Operators: arithmetic, relational, logical example: < ,==, !=,&&,||

Separators: white spaces, comments 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

TYPE OF DATA TYPE SIZE (IN BYTES) RANGE


DATA
16 BIT COMPUTER
U

Character char 1 Signed -128 to 127

Unsigned: 0 to 255
VT

integer int 2 Signed: -32768 to 32767

Unsigned: 0 to 65535

Real number float 4

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.

• C supports four type of constants

integer, floating, character and enumeration constants

Integer Constant

n
• Represents a signed integer of typically 2 or 4 or 8 bytes (16 or 32 or 64 bits)

• Precise size is machine-dependent

tio
• It is a number that has an integer value.

• It can be specified in decimal, octal or hexadecimal form

example: 5, 125,


Floating Constant
lu
Floating constant have matissa and exponent part(optional includes the letter e or E)
So
ddd.dddE(+/-)dd

• Mantissa(significant part) contains digit followed by decimal point(.)and then digit

453.678

Character Constant
• It is grouped into two categories: integer character, wide character
U

integer character is a sequence of one or more character enclosed in single quotes


‘ a’
VT

• The character within the single quote may be any character (except backslash or
newline or single quote)

example : ‘d’ ‘f’

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

Some points to be remembered about C Programs are

• all statements end with a semicolon!

• Commas separate multiple declarations

• Blank lines have no effect

• Extra spaces between tokens has no effect.

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

Operators in C Programming languages


Some of the operators used in c language are
 Arithmetic operators

 Conditional operators

 Bitwise operators

n
 Relational operators

tio
 Logical operators

 Assignment operators

 Increment and decrement 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

E.g. If a =10 and b=4


a-b=6
a+b=14
a/b=2
VT

a%b=2

Real Arithmetic :

Real operator is known as real arithmetic.


Decimal and exponential notation
If x,y are floats

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

Mixed –mode Arithmetic

 One of the operands is real and the other is integer

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;

printf(“ enter length and breadth of triangle”);

scanf(“%d%d”,&len,&bre);

area=0.5*len*bre;

printf(“\narea of triangle=%d”,area);
U

return 0;

}
VT

OUT PUT

enter length and breadth of triangle

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

2. Write a program to calculate area of circle


#include<stdio.h>

#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;

printf(“\narea of circle = %f”, area);

}
return 0;
lu
So

3. Write a program to calculate area and perimeter of a circle


U

#include<stdio.h>

#define pi 3.14
VT

int main()

int r;

float area,peri;

printf(“ enter radius of the circle);

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;

printf(“ area of circle = %f\n”, area);

printf(“ perimeter of a circle=%f”,peri);

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);

printf(“ enter rate of interest and time period”);

scanf(“%f%f”,&r,&t);

interest=(p*r*t)/100.0;
U

total=p+interest;

printf(“interest amount=%f\n total amount=%f”,interest,total);


VT

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

Mathematical Library functions:

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.

• Some of the library header files available in C are

n
input/output facility <stdio.h> (scanf,printf,gets,puts….)

mathematical operations <math.h>(sqrt,sin,cos,log,pow…)

tio
string manipulation oper <string.h>(strcpy,strcat,strlen..)

console input/output <conio.h> (getch,…)

• These header should be included in the program using

#include preprocessor directive statement

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

sqrt sqrt(x) Square root of x

power pow(x,y) X rise to Y


U

exponential exp(x)

log10 log10(x)
VT

log log(x) Natural logarithm of x

sin sin(x) Sine of (x)

cos cos(x) Cosine of (x)

tan tan(x) Tangent of (x)

absolute abs() |a|

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

printf(“ area of triangle=%f”,area);


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

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

C Language supports following control statements


So
U
VT

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

Program to find biggest among two numbers using (if-else)

#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

Input OUT PUT


co-ordinates

25,78 the co-ordinate lies on 1st quadrant


VT

-105,40 the co-ordinate lies on 2nd quadrant

-105,-150 the co-ordinate lies on 3rd quadrant

85,-125 the co-ordinate lies on 4th quadrant

0,0 the co-ordinate lies in origin

0,25 the co-ordinate lies in y-axis

30,0 the co-ordinate lies in x-axis

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 declare student result

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

1. Program to calculate Roots of Quadratic equation (Lab program)


U

• 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)

A year is leap if it is divisible by 4 but not by 100 or is divisible by 400


ex: 1996,2000,2004 -- leap year
1900,2002,2100 -- not a leap year
Algorithm leap(year)
read(year)
if(year is divisible by 4 and year is not divisible by 100) or is divisible by 400
print “ given year is leap year”

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:

• Prefix Increment : ++a


– example:
» int a=5;
» b=++a; // value of b=6; a=6;
» Postfix Increment: a++
– 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

» 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

• Precedence rules decides the order in which different operator are


applied.

• Associativity rule decides the order in which multiple occurrences of


VT

the same level operator are applied



Precedence Table:
Highest on top

++ -- (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

1. Program to Simulate simple calculator

#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;

case ‘X’ : c=a*b;


lu
So
break;
case ‘/’ : c=a/b;
break;
}
printf(“c=%f\n”,c);
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 calculate area of geometric objects as per user request

#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.

 Executes a block of statements as long as a specified condition is TRUE.


 The general while loop construct,

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

 The (condition) may be any valid C expression.


 The statement(s) may be either a single or a compound (a block of code) C statement.
 When while statement encountered, the following events occur:
1. The (condition) is evaluated.
2. If (condition) evaluates to FALSE (zero), the while loop terminates and execution passes to the next_statement.
3. If (condition) evaluates as TRUE (non zero), the C statement(s) is executed.
4. Then, the execution returns to step number 1 until condition becomes FALSE.

n
tio
lu
So
U
VT

simple while loop example


#include <stdio.h>
int main(void)
{
int n = 1;
// set the while condition
while(n <= 12)
{
// print
printf("%d ", n);

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

while – loop example


To sum= 2^2+4^2+….. +50^2
VT

simple while loop example


#include <stdio.h>
int main(void)
{
int n = 2;
float sum=0.0;
// set the while condition
while(n <= 50)
{
sum=sum+pow(n,2);
// increment n by 1, repeats
n=n+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

printf(“sum upto 2^2 to 50^2 is =%d“,sum);


return 0;

3. GCD using Euclidian’s algorithm

• 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

1. Program to check the given number is palindrome or not

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

1. Check the given number is Armstrong number or not using C


program

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

printf("%d is not an Armstrong number",temp);


return 0;
}
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

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

• Initial_expr is usually an assignment expression.


• Update_expr is an increment/decrement expression
• Final_expr is the relational expression results in T or F
Print the numbers in the given range say m to n
scanf(“%d%d”,&m,&n);
for (i=m;i<=n;i++)
printf(“%d \t”,i);
• for( x=0.1;x<=1.0;x+=0.2)
printf(“%f\t %f\n”,x,x*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

0.1 0.01
0.3 0.09
0.5 0.25
0.7 0.49
0.9 0.81

1. Program to find factorial of a given number

Algorithm fact

n
read n
fact=1
for i=n down to 2

tio
fact= fact*I
print (fact)
end

lu
So
U

 for loop is a very flexible construct.


 Can use the decrementing counter instead of incrementing. For example,
for (nCount = 100; nCount > 0; nCount--)
 Can use counter other than 1, for example 3,
VT

for(nCount = 0; nCount < 1000; nCount += 3)


 initial_value can be omitted if the test variable has been initialized beforehand.
 However the semicolon must still be there. For example,
nCount=1;
for( ; nCount < 1000; nCount ++)

 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

Null statement consists of a semicolon alone on a line. For example


for(count = 0; count < 20000; count++)
;
 This statement provides a pause (delay) of 20,000 milliseconds.

for loop – Example


sum=0+1+2+……….+20

n
nsum = 0;

for(irow = 1; irow <=20; irow++)

tio
nsum = nsum + irow;

printf("\n Sum of the first 20 natural numbers = %d“,nsum);

The above program segment will compute and display the sum of the first 20 natural numbers

Nested for loop



Example:

for(i=1;i<=2,i++)
lu
So
• { for(j=1; j<=3;j++)

• c=i*j;

• }

for i=1 j varies from 1 to 3

for i=2 j varies from 1 to 3


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
• 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

• Write a program to print the below structure using “*”


* * * *
* * *
* *
*
#include <stdio.h>
#include <conio.h>

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

part) in a while or do-while loop, and to the increment expression in a


for loop.
Unlike the break statement, continue does not force the termination of
a loop, it merely transfers control to the next iteration.

// using the continue in for structure


#include <stdio.h>
int main(void)

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:

 The goto statement is one of C unconditional jump or branching.


 When program execution encounters a goto statement, execution
U

immediately jumps, or branches, to the location specified by the goto


statement.
 The statement is unconditional because execution always branches
VT

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

1. Program to check the given number is prime or Not

#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.

• Conditional operator: (? : Operator)


The conditional operator consists of 2 symbols the question
U

mark (?) and the colon (:)


Syntax:
VT

exp1 ? exp2: exp3


example:
a=16
b=25;
x=(a>b) ? a : b;
working of above expression can be analyzed as follows:

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

if( a > 15) {


/* terminate the loop using break statement */
break;
}
}
return 0;
}
Output:

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:

• Process of converting an expression of a given type to another type


example: int to float
float to int
• When two operands in an expression are different, user explicitly changes the data type, this
is known type conversion

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

4. Size of operator : sizeof()


used to determine size of the operand based on its data type

float r= 12.45;

int y;

n
y=sizeof(r);

value of y is 4 because size of float is 4 bytes.

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

d-> number of digits to be limited after


the decimal point
Printf(“%4.2f”,a) -> 10.44
VT

Comparison of getchar(),getche(),getch() functions

• 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

PROGRAMMING IN C AND DATA STRUCTURES (14PCD13/23)

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

ARRAYS & STRINGS

BASIC CONCEPT OF ARRAYS: Consider a program to find average temperature in a week.


Here we need to store 7 floating point numbers. If we use simple variable and data type concepts,
then we need 7 variables of float data type and program will be something as follows:

#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:

 It's difficult to program with too many declarations.


 It's not recommended way of programming.
 It's not the right way of programming.

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:

 List of Marks of a Student


VT

 List of Employees of an Organization


 List of Daily Temperature in an year
 List of temperatures recorded every hour in a day, or a month, or a year
 List of products and their cost sold by a store
 Matrices and so on…
Having these collections of data we need to perform various operations on these values such as:
 Searching for a particular element.
 Ordering of the elements
 Finding Maximum, Minimum, Average, Mean and so on…
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

ARRAY

Array is a collection of homogeneous elements (elements of same data type), stored


sequentially one after the other in memory. An element of an array can be accessed by using: name
of the array and position of element in the array.
Arrays are of 2 types:
1) Single dimensional array

n
2) Multi dimensional array

SINGLE 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.

The Syntax of declaration of Single Dimensional Arrays is as shown below:

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

The declaration int a[5]; can be pictorially represented as shown below:


a[0] a[1] a[2] a[3] a[4]
VT

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

1. Initialization of One-Dimensional Array


The syntax is as shown below:
data_type array_name[array_size] = {v1, v2, v3,..., vN};
where v1, v2, v3, ..., vN are values
Ex: int a[5] = { 21, 45, 34, 56, 67 };
The above code can be pictorially represented as shown below:

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

age[1] = 44; //value 4 stored in array „age? at position 1


age[2] = 34; //value 34 stored in array „age? at position 2
age[3] = 35; //value 3 stored in array „age? at position 3
age[4] = 47; //value 4 stored in array „age? at position 4
VT

Example: Program to illustrate assigning values to one-dimensional array.


#include<stdio.h>
void main()
{ int age[5];
age[0] = 22; age[1] = 44; age[2] = 34; age[3] = 35; age[4] = 47;
printf("Value in array age[0] : %d \n", age[0]);
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]);
}
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

Output: Value in array age[0] :22


Value in array age[1] :44
Value in array age[2] :34
Value in array age[3] :35
Value in array age[4] :47
3. Reading/Writing to One-Dimensional Array
Example: int age[5]
scanf("%d", &age[0]); //read data from keyboard into array age at position 0.

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]);
}

for(i = 0; i < 5; i++)


{
lu
Similarly, to display 5 elements stored in the array, we can write:

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

{ int a[50], n, min, 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++ )
VT

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

read the number of elements n


read n elements of an array a
read the key element to be searched
flag = FALSE // Assume key is not found
for i = 0 to n-1 do //compare key with all the elements
VT

if a[i] == key then


flag = TRUE break
end if
end for
if flag == TRUE then
print “Successful Search”
else
print “UnSuccessful Search”
end if
End

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 ”);

printf(“Unsuccessful Search - Key NOT found”);


So
Binary Search

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.

How does it work?


VT

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

The algorithm of Binary Search can be given as:


Algorithm : Binary_Search( )
Begin
read the number of elements n
read n elements of an array a
read the key element to be searched
low = 0 high = n-1 flag = FALSE

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”

print “UnSuccessful Search”


lu
So
End
Example: Program to find given key element in an array of n integer elements using Binary
Search
int main ()
{ int a[50], n, key, low, high, mid, i, flag = 0;
printf(“\n\tEnter the number of elements: “);
scanf(“%d”, &n); /* 1 ≤ n ≤ 50*/
printf(“\n\tEnter %d Elements of an array in Sorted Order: “, n);
for ( i = 0; i < n; i++ )
U

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

MULTI DIMENSIONAL ARRAYS

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:

 First index identifies the row number of the element and


 Second index identifies the column number of the element

Thus 2D Arrays Simulate Matrices of Order mXn

Initialization of Two Dimensional Arrays


U

Example-1:
int a[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };

The above code can be pictorially represented as shown below


VT

a[0][0] = 1 a[0][1] = 2 a[0][2] = 3


a[1][0] = 4 a[1][1] = 5 a[1][2] = 6
Example-2:
int a[2][3] = { 1, 2, 3, 4, 5 };

a[0][0] = 1 a[0][1] = 2 a[0][2] = 3


a[1][0] = 4 a[1][1] = 5 a[1][2] = 0

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 } };

a[0][0] = 1 a[0][1] = 2 a[0][2] = 0


a[1][0] = 4 a[1][1] = 0 a[1][2] = 0

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

Reading and Writing Two Dimensional Arrays


Example:
int matrix[2][3];
lu
scanf("%d", &matrix[0][0]); //read data from keyboard into matrix at row=0 col=0.
So
scanf("%d", &matrix[0][1]); //read data from keyboard into matrix at row=0 col=1.
scanf("%d", &matrix[0][2]); //read data from keyboard into matrix at row=0 col=2.
scanf("%d", &matrix[1][0]); //read data from keyboard into matrix at row=1 col=0.
scanf("%d", &matrix[1][1]); //read data from keyboard into matrix at row=1 col=1.
scanf("%d", &matrix[1][2]); //read data from keyboard into matrix at row=1 col=2.

This way of reading / printing a 2D’ array is not easy and not recommended

In general, to read 6 values, we can write:


for(i=0;i<2;i++) /* specify i-th Row */
U

{
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

Example: Program to illustrate reading/writing to two-dimensional array.


#include<stdio.h>
void main()
{
int matrix[2][3], i, j;
printf("enter elements of 2*3 matrix: \n”);
for(i=0;i<2;i++)
{

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

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 */
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 */
for(j = 0; j < n; j++) /* specify j-th Column */
printf(“%d”,a[ i ][ j ]);
} /* closing of main */

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

The above code can be pictorially represented as shown below:


a[0] a[1] a[2] a[3]
V T U \0
VT

we can also use


char s[10]="VTU";
Here 10 bytes of memory is allocated and only three characters are stored and remaining will be
initialized to zero.
a[0] a[1] a[2] a[3] a[4] a[5] ….. a[9]
V T U \0 0 0 0 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

Example: Program to illustrate the initialization of string.


#include<stdio.h>
void main()
{
char s[4]={'V','T','U'}; //or char s[4]="VTU";
printf("Value in array s[0] : %c \n", s[0]);
printf("Value in array s[1] : %c \n", s[1]);
printf("Value in array s[2] : %c \n", s[2]);

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

printf(“\n\t String Entered is(scanf) : %s“, str);


getchar(); return 0;
}
Example: Program to illustrate the use of scanf() and printf().
#include<stdio.h>
void main()
{ char name[10];
printf(“enter your name: \n”); scanf(“%s”, name);
printf(“welcome: ”); printf(“%s”, name);
}

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

STRING INPUT/OUTPUT FUNCTIONS: gets, puts


The strings can be read from the keyboard and can be displayed onto the monitor using
following unformatted functions:
 Unformatted input function: gets()
 Unformatted output function: puts()
Example: Program to illustrate the use of gets() and puts().
#include<stdio.h>

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

Example: Program to Print String in Reverse


#include <stdio.h>
int main()
{
VT

char str[100]; int i, length;


printf(“\n\tEnter a String a Reverse: ");
scanf(“%s", str);
for(i = 0; str[ i ] != ‘\0’; i++) ; /* NULL Statement * /
length = i;
printf(“\n\n\t The Reverse of a String - %s - is : ” , str);
for( i = length – 1; i >= 0; i--)
printf(“%c”, str[ i ]);
return 0;
}

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

 a negetive value if S1 < S2,


 if S1 == S2
 a posetive value if S1 > S2

Example: Program to Compare Two String

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 LIBRARY FUNCTIONS

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:

 int isdigit( int )


VT

 int isalpha( int )


 int isalnum( int )
 int islower( int )
 int isupper( int )
 int tolower( int )
 int toupper( int )

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;
}

Example: Program to Check whether the character read is digit or an alphabet.


#include<ctype.h>
#include<stdio.h>
int main()
{
char ch; clrscr();
lu
printf("Enter a Character: "); scanf("%c",&ch);
if(isdigit(ch))
So
printf("\n\tCharacter %c is a Digit", ch);
if(isalpha(ch))
printf("\n\tCharacter %c is a Alphabet", ch);
getch(); return 0;
}
Pointers and Strings
The arrays are implicitly treated as pointers. And the strings are array of characters
terminated by NULL character. Hence a pointer to char type can be used to read a string.
U

Example: Program to read a String using Pointer


#include<stdio.h>
#include<conio.h>
int main()
{ int i; char *str1, str2[50], *ptr; clrscr();
VT

printf("\n\tEnter a String-1: ");


scanf("%s", str1);
printf("\n\tEnter a String-2: ");
scanf("%s", &str2);
ptr = str1;
printf("\n\tThe String is : %s",ptr);
ptr = str2;
printf("\n\tThe String is : %s",ptr);
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:

Location Name s[0] s[1] s[2]

n
Content 1 2 3

Address 1400 1450 1500

tio
Here
s[0] = Address of the 0th String
s[1] = Address of the 1st String
s[2] = Address of the 2nd String

Example: Program to Read a List of Names


#include<stdio.h>
int main()
{

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

printf(“\n\tNumber of u’s in the String is : %d “, nu);


printf(“\n\tNumber of Vowels in the String is : %d “, nvowel);
printf(“\n\tNumber of Consonants in the String is : %d “, ncons);
getch(); return 0;
VT

}
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

STRING MANIPULATION FUNCTIONS FROM THE STANDARD LIBRARY


Strings are often needed to be manipulated by programmer according to the need of a
problem. All string manipulation can be done manually by the programmer but, this makes
programming complex and large. To solve this, the C supports a large number of string handling
functions. There are numerous functions available in <string.h> header file. It includes functions to
perform useful tests and manipulations on Strings. Each of these functions receives a pointer to
character as an argument. Commonly used String handling functions are:

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

Example: Program to illustrate the use of strcpy().


#include<string.h>
#include<stdio.h>
void main()
{ char src[20],dest[20];
printf("Enter string: ");
gets(src);
strcpy(dest, src); //Content of string src is copied to string dest
printf("Copied string: "); puts(dest);
}

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

Output: Enter string: vtunotesbysri


Copied string: vtunotesbysri
Example: Program to demonstrate use of strcpy() and strcat() functions.
#include<stdio.h>
#include<string.h>
int main()
{
char dest[25], *str1 = "EDUSAT“, *str2 = "Program";

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);

Example: Program to illustrate the use of strcmp().


#include <string.h>
#include<stdio.h>
void main()
{
char str1[30],str2[30];
printf("Enter first string: ");
U

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

else if(strcmp(str,names[mid]) > 0) low = mid + 1;


else high = mid - 1;
}
printf("\n\n\tName Does not Exist"); getch(); return 0;
VT

}
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

SOME USEFUL STRING FUNCTIONS

Example: Program to find length of a string without using strlen().


#include<stdio.h>
void main(void)
{
char str1[25];
int len=0;

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

printf("Both strings are equal");


else
printf("Both strings are not equal");
}
Output:
Enter first string: rama
Enter second string: rama
Both strings are equal

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

A complex problem is often easier to solve by dividing it into several smaller


parts(pieces), each of which can be solved by itself. Each sub-problem is more manageable than
the original problem. This is called structured programming. These sub-problems which are easy
to manage are made into Functions/Procedures/Modules in C. main() uses functions to solve
the original problem. Thus A function is a block of code to perform a specific task. Every C
program has at least one function main( ). Without main() function, there is technically no 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

FUNCTIONS AND PROGRAM STRUCTURE

C programs usually have the following form:


 include statements
 function prototypes/declarations
 main() function
 function definitions

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

Basic structure of C program with function is shown below:

#include <stdio.h> // include statements


void function_name(); //function declaration
int main()
{
...........
...........

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:

return_type function_name(type(1) argument(1),....,type(n) argument(n));


Here:
U

 Return-Type: Data type of the result returned


 (use void if nothing returned)
 Function-Name: Any valid Identifier
 Parameter list: Comma separated list of arguments
VT

 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

Function definition contains programming codes to perform specific task.

n
The syntax is shown below:

return_type function_name(type(1) argument(1),..,type(n) argument(n))

tio
{
//body of function
}

Example: Program to Print a sentence using function.


#include<stdio.h>
void display(); //function declaration
void main()
{

}
display(); //function call

lu
So
void display() //function definition
{
printf("C Programming");
return;
}

Output:
C Programming
U
VT

ACTUAL AND FORMAL ARGUMENTS

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;
}

int add(int a, int b) //formal arguments


{
int sum;
sum=a+b;

}
Output:
return sum;

Enters two number to add


2 3 lu
So
sum=5
FUNCTION CALL METHODS
C Supports two types of calling a Function :
 Call by Value
 Call by Address
ARGUMENT PASSING – CALL BY VALUE
In this type, value of actual arguments are passed to the formal arguments and the operation
is done on the formal arguments. Any changes made in the formal arguments does not affect the
U

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

void change(int a, int b)


{
k=a; a=b; b=k;
return;
}
Output: enter values of x & y : 2 3
old values x=2 y =3
new values x=2 y =3

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;

void swap(int x, int y) lu


printf(“\n\t After SWAP a = %d and b = %d”, a, b);
So
{
int t;
t = x;
x = y;
y = t;
}
Output: Enter Values of a and b: 15 27
Before SWAP a = 15 and b = 27
After SWAP a = 15 and b = 27
U

ARGUMENT PASSING – CALL BY ADDRESS VALUE


The Address of actual parameters are copied to formal parameters. Here changing the formal
parameters indirectly affects the actual parameters.
#include<stdio.h>
VT

#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

void swap(int *x, int *y)


{
int t;
t = *x;
*x = *y;
*y = t;
}
Output: Enter Values of a and b: 15 27

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;

Enters two number to add lu


So
2 3
sum=5
Example: Program to illustrate function with arguments but no return value
#include <stdio.h>
void add(int a, int b);
void main()
{
int a, b, sum;
printf("Enters two number to add \n");
U

scanf("%d %d", &a, &b);


add(a, b);
}
void add(int a, int b)
{
VT

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

Example: Program to illustrate function with arguments and return value


#include <stdio.h>
int add(int a, int b);
int main()
{
int a, b, sum;
printf("Enters two number to add \n");
scanf("%d %d", &a, &b);

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

printf("\n\tEnter an Unsigned Number: "); scanf("%u",&x);


printf("\n\tEnter the Number of Right Rotations to be done: "); scanf("%u",&n);
res = RightShift(x, n);
printf("\n\tAfter Rotating %u by %u times we get: %u ",x,n,res);
VT

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

Output: Enter an Unsigned Number: 16


Enter the Number of Right Rotations to be done: 2
After Rotating 16 by 2 times we get: 4
Enter an Unsigned Number: 5
Enter the Number of Right Rotations to be done: 1
After Rotating 5 by 2 times we get: 32770
Enter an Unsigned Number: 7
Enter the Number of Right Rotations to be done: 3

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

for(i = 2; i <= n/2; i++)


{
if( n % i == 0) // Number is NOT PRIME
return 0;
VT

}
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

Example: Program to illustrate use of register variable.


#include <stdio.h>
void main()
{
int a, b;
register int z;
printf("Enters two number to add \n");
scanf("%d %d", &a, &b);

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

scanf("%d %d", &a, &b);


z=a+b;
display();
}
Output: Enters two number to add: 2 3
sum=5

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

char * STRCOPY(char str2[ ], const char str1[ ])


{
int i = 0;
while(str1[ i ] != '\0')
{
VT

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);

void PrintMatrix(int p[ ][10], int m, int n)


{ int i, j;
for(i = 0; i < m; i++)
{

}
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

{ int a[10][10], b[10][10], c[10][10], m, n, p, q; clrscr();


printf("\n\tEnter Order of Matrix A:" ); scanf("%d %d",&m,&n);
printf("\n\tEnter Order of Matrix B:" ); scanf("%d %d",&p,&q);
if(n != p)
{ printf("\n Incompatible Order of Matrices to Multiply...");
VT

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

MatrixMultiply(int (*a)[10], int (*b)[10], int c[ ][10], int m, int n, int q)


{
int i, j, k;
for(i = 0; i < m; i++)
{ for(j = 0; j < q; j++)
{
c[i][j] = 0;
for(k = 0; k < n; k++)

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

Observe the following for better visualization of recursion in this example:


add(5)
=5+ add(4)
=5+4+ add(3)
=5+4+3+ add(2)
=5+4+3+2+ add(1)
=5+4+3+2+1+ add(0)
=5+4+3+2+1+0

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:

The following is the recursive function to compute nth fibonacci number:


int Fib(int n)
{
U

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

Recursive and Iterative Methods - Comparison


• Recursive programs seems to be easier BUT it takes more time and space for its execution.
• Iterative method take less time and space for its execution.
• Never Use Recursion In Programming – Its Very Expensive

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) );

int Minimum(int x, int y) { return (x < y)?x:y; }


So
void main()
{ int n, r, i, j; clrscr();
printf("Enter Value of n:" ); scanf("%d",&n);
printf("Enter Value of r:" ); scanf("%d",&r);
for(i = 0; i <= n; i++)
{ printf("\n\t");
for(j = 0; j <= Minimum(i, r); j++)
{ int res;
res = FindnCr(i, j);
U

printf(" nCr(%d, %d) = %d",i, j, res);


}
}
getch();
}
VT

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

ARRAYS AND FUNCTIONS


Arrays are implicitly treated as constant pointers. Array elements can be passed as parameter
to Function in TWO ways: Passing element by element OR Passing the whole array(Here number of
elements also need to be passed)

1) Passing Individual Elements of an Array

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

for(i = 0; i < n; i++)


scanf("%d", &x[i]);
}
void PrintArray( )
{ int i;
printf("\n\tThe %d Elements of an Array are: ", n);
for(i = 0; i < n; i++)
printf(" %d ", x[i]);
}

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

Example: Program to illustrate passing individual elements of an array to a function.


#include<stdio.h>
void display(int a)
{

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

void ReadArray(int *, int );


void PrintArray(int [ ], int );
int main()
{ int x[50], n; clrscr();
printf("\n\tEnter number of elements of an array: ");
scanf("%d", &n);
ReadArray(x, n);
PrintArray(x, n);
getch(); return 0;
}

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

void ReadArray( int *p, int n)


{ int i;
printf("\n\tEnter %d Elements of an Array: ", n);
for(i = 0; i < n; i++)
scanf("%d", &p[ i ]);
}
void PrintArray(int a[ ], int n)
{ int i;

n
printf("\n\tThe %d Elements of an Array are: ", n);
for(i = 0; i < n; i++)
printf(" %d ", a[ i ]);

tio
}

Example: Program to find average of 6 marks using call by address value.


#include <stdio.h>
void average(int m[])
{
int i ,avg, avg, sum=0;

}
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

scanf("%d", &a[ i ]);


}
int LinearSearch(int p[ ], int n, int key)
{
int i;
for(i = 0; i < n; i++)
if(p[ i ] == key)
return 1;
return 0;
}

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

Example: Program to calculate Sum and Average of an array.


#include <stdio.h>
void
{
main()

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

positive_sum = positive_sum + array[i];


else if (array[i] == 0)
;
total = total + array[i] ;
}
average = total / num;
printf("Sum of all negative numbers = %d \n", negative_sum);
printf("Sum of all positive numbers = %d \n", positive_sum);
printf("Average of all input numbers = %.2f", average);
}

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

printf("Enter the degree of the polynomial:"); scanf("%d",&n);


printf("Enter the coefficients into the array:");
for(i=n;i>=0;i--)
scanf("%f",&a[i]);
printf("Enter the value of x:");
VT

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

Example: Program to sort n numbers in ascending order using bubble sort.


#include <stdio.h>
#define MAXSIZE 10
void main()
{
int array[MAXSIZE], i, j, num, temp;
printf("Enter the value of num: \n");
scanf("%d", &num);

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++)

if (array[j] > array[j + 1])


{
So
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is :\n ");
for (i = 0; i < num; i++)
printf("%d ", array[i]);
U

}
Output:
Enter the value of num: 6
Enter the elements one by one: 23 45 67 89 12 34
VT

Input array is: 23 45 67 89 12 34


Sorted array is.: 12 23 34 45 67 89

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

Example: Program to calculate the addition or subtraction of 2 matrices.


#include <stdio.h>
void main()
{
int array1[10][10], array2[10][10], arraysum[10][10], arraydiff[10][10];
int i, j, m, n, option;
printf("Enter the order of the matrix array1 and array2 \n");
scanf("%d %d", &m, &n);

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

printf("Difference matrix is \n");


for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
printf("%d\t", arraydiff[i][j]) ;
printf("\n");
}
break;
}
}

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

for (j = 0; j < n; j++)


{
array3[i][j] = 0;
for (k = 0; k < n; k++)
VT

array3[i][j] = array3[i][j] + array1[i][k] * array2[k][j];


}
printf("The product matrix is \n");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
printf("%3d", arr[i][j]);
printf("\n");
}
}

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

Enter the order of the matrix


33
Enter the coefiicients of the matrix
3 7 9
2 7 5
6 3 4
Transpose of matrix is
3 2 6
7 7 3
9 5 4

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

C PROGRAMS BASED ON FUNCTIONS

Example: Program to find square of a number using function.


#include<stdio.h>
int square()
{
return n*n;
}

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

Example: Program to find cube of a number using function.


#include<stdio.h>
So
int cube()
{
return n*n*n;
}
void main()
{
int n, p;
printf(“enter a number”);
scanf(“%d”,&n);
U

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

Example: Program to calculate factorial of a number using recursion.


#include<stdio.h>
int fact(int n)
{
if(n!=1) return n*fact(n-1);
}
void main()
{

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

Example: Program to perform binary search using recursion


#include <stdio.h>
void bubble_sort(int list[], int size)
{ int temp, i, j;
for (i = 0; i < size; i++)
for (j = i; j < size; j++)
if (list[i] > list[j])
{

n
temp = list[i];
list[i] = list[j];
list[j] = temp;

tio
}
}

void binary_search(int list[], int lo, int hi, int key)


{ int mid;
if (lo > hi)
{

}
printf("Key not found\n");

mid = (lo + hi) / 2; lu return;


So
if (list[mid] == key)
printf("Key found\n");
else if (list[mid] > key)
binary_search(list, lo, mid - 1, key);
else if (list[mid] < key)
binary_search(list, mid + 1, hi, key);
}

void main()
{
U

int key, size, i; int list[25];


printf("Enter size of a list: "); scanf("%d", &size);
printf("Enter %d numbers ",size);
for(i = 0; i < size; i++)
VT

scanf("%d ", &list[i]);


bubble_sort(list, size);
printf("\n\n");
printf("Enter key to search: "); scanf("%d", &key);
binary_search(list, 0, size, key);
}
Output: Enter size of a list: 10
Enter 10 numbers : 83 86 77 15 93 35 86 92 49 21
Enter key to search: 21
Key found

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

Now, we shall see “What is a structure?”

Definition: A structure is defined as a collection of data of same/different data


types. All data items thus grouped are logically related and can be accessed
using variables. Thus, structure can also be defined as a group of variables of
same or different data types. The variables that are used to store the data are
called members of the structure or fields of the structure. In C, the structure is
identified by the keyword struct.

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

Type-Defined Structure: The structure definition associated with keyword


typedef is called type-defined structure. This is the most powerful way of defining the
structure. This can be done using two methods:
VT

Method 1: The syntax of type-defined structure is shown below:


typedef struct
{
type1 member1;
type2 member2;
curly braces …… ……
…… ……
} TYPE_ID; Note: semicolon is must after TYPE_ID

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

 typedef is the keyword added to the beginning of the definition


 struct is the keyword which tells the compiler that a structure is being
defined.
 member1, member2,….. are called members of the structure. They are
also called fields of the structure.
 The members are declared within curly braces.
 The closing brace must end with type definition name (TYPE_ID in the

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.

For example, the type-defined structure definition is shown below:

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:

STUDENT cse, ise ;

user-defined data type Terminated by semicolon


Structure variables

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:

typedef struct student STUDENT; /* STUDENT is user-defined


data type */
Using the user-defined data type STUDENT, we can declare the variables as

n
shown below:
/* Structure declaration */
STUDENT cse, ise; /* Memory is allocated for the

tio
variables */

Structure initialization

The structures can be initialized various ways:


Method 1: Specify the initializers within the braces and separated by commas

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

{ Note: The compiler will not reserve


char name[20]; memory for structure definition
int salary;
int id;
VT

};
/* structure declaration and initialization */
struct employee a = {"MONALIKA", 10950, 2001};
Accessing structures

The members of a structure can be accessed by specifying the variable


followed by dot operator followed by the name of the member. 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

consider the structure definition and initialization along with memory


representation as shown below:

//Structure initialization Memory representation


struct employee
{
char name[20]; name M I T H I L \0
salary;

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

Internal implementation of structures

Now, let us see “What is the size of the structure?”

Definition: The size of a structure is defined as the sum of sizes of individual


member of the structure. For example, the structure declaration along with
sizes of individual data members 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

// Structure definition Pictorial representation Bytes


struct employee
{
char name[8]; name M I T H I L \0 8
int id; id 10950 4
char sex; sex M 1
double salary;
salary 9999.9 8
} a = {“MITHIL”,109,‘M’,9999.9};

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:

name id sex salary


M I T H I L \0 10950 M 9999.99

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

each member is obtained using the following relation:

address of member = starting address of previous member + size of previous member


U

So, address of member id = starting address of member name + size of member name
= 2000 + 8
= 2008
VT

Address of member sex = starting address of member id + size of member id


= 2008 + 4
= 2012

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,

// The following are valid // The following are invalid


a = b; a = c;
b = a; b = d;
c = d; c = a;
U

d = c; d = b;

Comparison of two structure variables or members


VT

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.

a == b; /* Invalid: Comparison is not allowed between structure variables */


a != b; /* Invalid: Comparison is not allowed between structure variables */

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

a.member1 == b.member2 // valid if both members have the same type


a.member1 != b.member2 // valid if both members have the same type

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?”

The structures can be used for the following reasons:


 Structures are used to represent more complex data structures
 Related data items of dissimilar data types can be logically grouped under
a common name and all the items can be accessed using a common
name.

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.

Union and its definition


Definition: A union is similar to a structure which is also collection of data
items of similar or dissimilar data types which are identified by unique names
using identifiers. Each identifier is called a field or a member. All the members
of the union share the same memory space. Thus, all the identifiers of union
U

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

format (syntax) of a union definition is shown below:

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.

Example : Program to show how union behaves


VT

#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
}

Observe the following points during execution of the above program:


 After executing the statement x.marks = 100, the member marks will hold
the value 100 whereas other members should not access the data. If
accessed, it will be treated as garbage value.

it will be treated as garbage value.


lu
 After executing the statement x.grade = ‘A’, the member grade will hold the
value ‘A’ whereas other members should not access the data. If accessed,

 After executing the statement x.percentage = 99.5, the member


percentage will hold the value 99.5 whereas other members should not
So
access the data. If accessed, it will be treated as garbage value.

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.

Example : Program to show how structure behaves


U

#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

printf("Grade : %c\n",x.grade); Marks: 100


printf("Marks : %d\n",x.marks); Grade: A
printf("Percentage: %f\n", x.percentage); Percentage: 99.5

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.

a structure, the compiler allocates


the memory for each member. The
sizeof structure is greater than or
equal to the sum of sizes of its lu
2. When a variable is associated with 2. When a variable is associated with
a union, the compiler allocates the
memory by considering the size of
the largest member. So, size of
union is equal to the size of largest
So
members. The smaller members member
may end with unused slack bytes
(see section 2.4.5)
3. Altering the value of a member will 3. Altering the value of any of the
not affect other members of the member will alter other member
structure values.
4. The address of each member will 4. The address is same for all the
be in ascending order This members of a union. This indicates
U

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

accessed at any time since a time since memory is shared by


separate memory is reserved for each member.
each member

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

14.1.1 Creating a data file


Now, let us see “How to create a data file or a text file?”
A data file also called text file can be created as shown below:
 When we use Linux/Unix operating system, we can invoke “vi” editor
 When we are using Windows operating system, we can invoke notepad or
Microsoft word.
 After invoking the editor, type the data or text and save the data or text into a
file. The file along with data is stored in hard disk permanently till we
physically delete it.

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.

Now, let us see “What is 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

14.1.2 Declare a file pointer variable


A file pointer variable should be declared using FILE. First, let us see “What is a
FILE? Where it is defined?”

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

………. /* File operations */


……….
}
VT

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

14.1.3 Modes of a file

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?

Definition: fopen() is a function using which


 an existing file can be opened only in read mode using mode “r”.
 an existing file can be erased and treat it as a new file. This can be done by
opening the file in write mode using “w”.
U

 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

append mode using “a”.

The syntax is shown below:

#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”);

/* Using fp access file contents */


So
…………..
………….

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

 All the links to the file are broken.


 Once the file is closed, to access the file, it has to be re-opened.
 If a file is closed successfully, 0 is returned otherwise EOF is returned.
VT

The syntax is shown below:

fclose(fp);

14.2.1 Open the file for reading


Now, let us see “How to open a file in read mode?” The steps to open a file in read
mode are shown below:
 Invoke the function fopen() with two arguments
 The first argument is the file name which has to be opened

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

 Second argument is the mode in which the file has to be opened


 The function fopen() returns NULL if file does not exist. Otherwise, it returns
pointer to the opened file.

The following set of instructions are used to open the file “input.txt”

#include <stdio.h>

n
FILE *fp;

fp = fopen(“input.txt”, “r”); // Open the file in read mode

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;

fp = fopen(“input.txt”, “r”); // Open the file

if (fp == NULL) // If file does not exist


{
printf(“Error in opening the file”); // display error message

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
}

/* Read the opened file and perform various operations


………..

fclose(fp); // close the file

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”);

lu // Open the file in write mode

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

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

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

if (fp == NULL) // If file cannot be created

tio
{
printf(“Error in opening the file”); // display error message
exit(0); // terminate
}

// write the data into the file


………..

fclose(fp);

lu
// close the file

14.2.3 Open the file for appending


So
To open a file for writing, we use the same procedure as we use in opening the file in
read mode. But, the file mode has to be changed from “r” to “a”. Suppose, the file
“input.txt” has to be opened for appending. We can use the following instructions.

#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

Sai Vidya Institute of Technology∆


U

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

Sai Vidya Institute of Technology∆

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;

fp = fopen(“input.txt”, “a”); // Open the file

if (fp == NULL) // If file cannot be appended


{
printf(“Error in opening the file”); // display error message
exit(0); // terminate
U

// append the data into the file


………..
VT

fclose(fp); // close the file

14.3 I/O file functions


In this chapter we study three types of I/O functions to read from or write into the file
 File I/O functions for fscanf() and fprintf()
 File I/O functions for strings fgets() and fputs()
 File I/O functions for characters fgetc() and fputc()

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

14.3.1 fscanf(), fprintf()

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:

fscanf(fp, “%d %s %f”, &id, name, &avg_marks);

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

Example 14.2: Consider the following statement:

fscanf(stdin, “%d %s %f”, &id, name, &avg_marks);


VT

The above statement is same as the following scanf function:

scanf( “%d %s %f”, &id, name, &avg_marks);

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

fprintf(fp, “format string”, list);


where
 fp is a file pointer associated with a file that has been opened for writing.
 format string and list have the same meaning as in printf() function i.e., the
values of the variables specified in the list will be written into the file associated
with file pointer fp using the specifications provided in format string.

n
Example 14.3: Consider the following statement:

fprintf(fp, “%d %s %f”, id, name, avg_marks);

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.

Example 14.4: Consider the following statement:

lu
fprintf(stdout, “%d %s %f”, id, name, avg_marks);

The above statement is same as the following printf statement:


So
printf(“%d %s %f”, id, name, avg_marks);

14.2.2 Read from keyboard and write into a file


Now, let us write a program to read n numbers from the keyboard and write into a file
“input.dat”

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;

fp = fopen(“input.dat”, “w”); // Open the file in write mode

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

while (scanf(“%d”, &num) != EOF) // 10 20 30 40 50 Cntl-z (Turbo)


{ // Cntl-d (linux)
fprintf(fp,“%d\n”, num); // The above data is written into
} // file : input.dat
fclose(fp);
}

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

Student Name USN Heading


Name1 USN1
Name2 USN2
….. …..
….. …..

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.

Syntax : type *ptr ;

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.

Pointer Operators * and &


& is a unary operator that returns the address of its operand which must be a variable.

For Example :-
U

int *m ;
int count=125, i ;/* m is a pointer to int, count, i are
integers */
m = &count ;
VT

The address of the variable count is placed in the pointer variable m.

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.

A pointer may also be initialised to 0 ( zero ) or NULL which means it is pointing at


So
nothing. This will cause a run-time error if the pointer is inadvertently used in this state.
It is useful to be able to test if a pointer has a null value or not as a means of determining
if it is pointing at something useful in a program.

NB : NULL is #defined in <stdio.h>.

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 swap( int *, int * ) ;

void main( )
{
int a, b ;

n
printf( "Enter two numbers" ) ;
scanf( " %d %d ", &a, &b ) ;

tio
printf( "a = %d ; b = %d \n", a, b ) ;

swap( &a, &b ) ;

printf( "a = %d ; b = %d \n", a, b ) ;


}
void swap ( int *ptr1, int *ptr2 )
{
int temp ;

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

Pointers and Arrays


There is a very close relationship between pointer and array notation in C. As we have
seen already the name of an array ( or string ) is actually the address in memory of the
array and so it is essentially a constant pointer.

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 */

It is illegal however to do the following

str = ptr ; /* illegal */

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;

ptr = str ; // position the pointer appropriately

*ptr = 'a' ; // access first element i.e. str[0]


ch = *( ptr + 1 ) ; // access second element i.e.
str[1]
U

Thus *( array + index ) is equivalent to array[index].

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

int x[10], *ptr ;

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

ptr[4] = 10 ; /* accesses element 5 of array by indexing a


pointer */

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

// assign the value of another pointer


variable, an address
So
 Addition / Subtraction

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.

int *ptr ; Address Value


int array[3] = { 100, 101, ptr 1000 2008
102 } ;
U

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 ).

char *p1, *p2 ;

lu
p1 = p1 + p2 ; /* illegal operation */

Two pointers may however be subtracted as follows.


So
int *p1, *p2, array[3], count ;
p1 = array ;
p2 = &array[2] ;

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.

1. Using array notation

void puts( const char s[ ] ) /* const keyword makes string


contents read only */
{
6
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 i ;

for ( i = 0; s[i] ; i++ )


putchar( s[i] ) ;
putchar( '\n' ) ;
}

2. Using pointer notation

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.

For Example :- Palindrome program using pointers.


So
#include <stdio.h>
int palin( char * ) ; /* Function to determine if array is a palindrome. returns 1
if it is a palindrome, 0 otherwise */
void main( )
{
char str[30], c ;

puts( "Enter test string" ) ;


gets( str ) ;
U

if ( palin( str ) )
printf( "%s is a palindrome\n", str ) ;
else
printf( "%s is not a palindrome\n") ;
VT

int palin ( char *str )


{
char *ptr ;

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

while ( str < ptr )


if ( *str++ != *ptr-- )
return 0 ; /* return value 0 if not a palindrome
*/

return 1 ; /* otherwise it is a palindrome */


}

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

int strcmp( const char *string1, const char *string2 ) ;

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.

Strings can be initialised using pointer or array notation as follows

char *str = "Hello\n" ;


So
char string[] = "Hello\n" ;

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

declares an array of ten integer pointers.

To make one of the pointers point to a variable one might do the following.

x[ 2 ] = &var ;

To access the value pointed to by x[ 2 ] we would do the following

*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

which simply de-references the pointer x[ 2 ] using the * operator.

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.

A common use of pointer arrays is to hold arrays of strings.

void serror( int num )


{
static char *err[] = { lu
For Example :- A function to print error messages.
So
"Cannot Open File\n",
"Read Error\n",
"Write Error\n" } ;

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

Command Line Arguments


Command line arguments allow us to pass information into the program as it is run. For
example the simple operating system command type uses command line arguments as
follows

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.

void main( int argc, char *argv[ ] )


{

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

void main( int argc, char *argv[ ] )


So
{
if ( argc != 2 )
{
puts( "Missing parameter. Usage : name yourname" ) ;
exit( 1 );
}
printf( "Hello %s", argv[1] ) ;
}
U

To run the program one might type

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>

void main( int argc, char *argv[ ] )

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 ;

for ( count = atoi( argv[1] ) ; count ; count-- )


if ( disp )
printf( "%d\n", count ) ;
printf( “done\n” ) ;
}

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.

The following is the prototype for the malloc() function

void * malloc( size_t num_bytes ) ;

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

Multiple Indirection -- Pointers to Pointers


It is possible in C to have a pointer point to another pointer that points to a target value.
This is termed multiple indirection in this case double indirection. Multiple indirection
can be carried out to whatever extent is desired but can get convoluted if carried to
extremes.

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

address 1 address 2 address 3

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.

The following illustrates some valid operations using double indirection.

int x = 10, *p, **q ;

p = &x ;
q = &p ;
U

**q = 20 ; // de-reference twice to access value


p = *q ; // de-reference q once to get a pointer to int

int array1[] = { 1,2,3,4,5,6 ,7 ,8,9,10} ;
int array2[] = {10,20,30,40,50} ;
VT

int *pointers[2] ; // an array of pointers to type int


int **ptr ; // a doubly indirected pointer

ptr = pointers ; // initialise pointer to array of pointers


*ptr++ = array1 ; // now we simply de-reference the pointer to a
pointer
*ptr = array2 ; // once and move it on like any pointer

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

**ptr = 100 ; // ptr is pointing at pointers[1] which in turn is


pointing
// at array2 so array2[0] is assigned 100
For Example :- Allocation and initialisation of an m x n matrix using double indirection

What we require here is to allocate an n x n matrix as a collection of discrete rows rather


than just as one block of memory. This format has advantages over a single block
allocation in certain situations. The structure we end up with is illustrated below.

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>

void main( void )


{
double **ptr_rows, **user_ptr, *elem_ptr ;
int m, n, i, j ;

printf( “\n\nEnter the number of rows and columns required (m, n) : “ ) ;


scanf( “%d, %d”, &m, &n ) ;
U

_flushall() ;

ptr_rows = ( double **) malloc( m * sizeof ( double * ) ) ; // space for


row pointers
VT

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

user_ptr++ ; // move onto next row pointer


}

// after use we need to clean up in reverse


order
user_ptr = ptr_rows ;

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.

A pointer to a function is declared as follows


U

Syntax : ret_type ( * fptr ) ( parameter list ) ;

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

ret_type * fptr( parameter list ) ;

just declares a function fptr which returns a pointer to type ret_type !

To assign a function to a pointer we might simply do the following

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

fptr = getchar ; /* standard library function */

To call the function using a pointer we can do either of the following

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 );

check( s1, s2, p ) ;


}
void check ( char *a, char *b, int (* cmp)( ) )
{
if ( ! cmp( a, b ) )
puts( "equal" ) ;
else
U

puts( "not equal") ;


}

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

check( s1, s2, strcmp ) ;

where we essentially pass a constant pointer to strcmp( ).

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>

void check( char *a, char *b, int ( * cmp ) ( ) );

n
int numcmp( char *, char * ) ;

void main( )

tio
{
char s1[80], s2[80] ;

gets(s1) ;
gets( s2 );

if ( isalpha( *s1 ) // should have a more rigorous test here

else

}
lu
check( s1, s2, strcmp ) ;

check( s1, s2, numcmp ) ;

void check ( char *a, char *b, int (* cmp)( ) )


So
{
if ( ! cmp( a, b ) )
puts( "equal" ) ;
else
puts( "not equal") ;
}

int numcmp( char *a, char *b )


{
U

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

for ( k = 0; k < 100; k++ )


array[ k ] = 0.0 ;

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.

The exact same thing occurs if we use a pointer incorrectly as follows

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.

Now, let us see “What is preprocessor?”


Definition: The preprocessor is used automatically by the C compiler to transform all our
VT

C programs before compilation. It is a program that accepts a source program with


preprocessing statements as the input and produces another source program which will
not contain any preprocessing statements. The preprocessing statements also called
preprocessor directive starts with symbol ‘#’ in C language.

Now, let us see “What are preprocessor directives?”


Definition: The preprocessor directives are lines included in our programs that start with
character #. These lines are not program statements but they are the instructions (also
called directives) for the preprocessor. The symbol ‘#’ is followed by an identifier that is
a directive name or instruction name. For example,

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

#define MAX_LENGTH 100


#include <stdio.h>
etc. are all preprocessor directives. A preprocessor directive statement should not end
with semicolon and it should not have even comments in that line.
Ex 1: #define MAX_LENGTH 100;
The above statement ends with semicolon and hence it is an error.
Ex 2: #define MAX_LENTH 100 /* It is a symbolic constant */
The above statement is also wrong. Even comments are also not allowed as

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

#else Specifies alternatives when # if test fails


The preprocessor directives can be divided into three categories
1. Macro substitution division
2. File inclusion division
3. Compiler control division

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

#define identifier string

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

Simple macro substitution:

Simple string replacement is commonly used to define constants example:


U

#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

#define AREA 12.36

Macros as arguments:

The preprocessor permits us to define more complex and more useful form of replacements it takes
the following form.

# define identifier(f1,f2,f3…..fn) string.

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

A simple example of a macro with arguments is

n
# define CUBE (x) (x*x*x)

tio
If the following statements appears later in the program,

volume=CUBE(side);

The preprocessor would expand the statement to

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:

A defined macro can be undefined using the statement


U

# 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

#include< filename >

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

#if constant expression

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

 Character : This is used to represent single character

Eg: ‘C’, ‘a’

 String: This is used to represent group of characters.


U

Eg: "M.S.P.V.L Polytechnic College"

 Boolean: This is used represent logical values either true or false.


VT

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.

The non-primitive data types are

 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

Linear Data Structures:


Linear data structures are those data structures in which data elements are accessed (read
and written) in sequential fashion ( one by one)
Eg: Stacks , Queues, Lists, Arrays

Non Linear Data Structures: lu


So
Non Linear Data Structures are those in which data elements are not accessed in
sequential fashion.
Eg: Trees, graphs

ABSTRACT DATA TYPE

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.

Modularity has several advantages


VT

1. Modules can be compiled separately which makes debugging process easier.

2. Several modules can be implemented and executed simultaneously.

3. Modules can be easily enhanced.

Abstract Data type is an extension of modular design.

An abstract data type is a set of operations such as Union, Intersection, Complement,


Find etc.,

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.

THE LIST ADT

List is an ordered set of elements.

The general form of the list is

n
A1, A2, A3, ..... ,AN

tio
A1 - First element of the list

AN - Last element of the list

N - Size of the list

If the element at position i is Ai then its successor is Ai+1 and its predecessor is Ai-1.

Various operations performed on List

lu
1. Insert (X, 5) - Insert the element X after the position 5.
So
2. Delete (X) - The element X is deleted

3. Find (X) - Returns the position of X.

4. Next (i) - Returns the position of its successor element i+1.

5. Previous (i) - Returns the position of its predecessor i-1.

6. Print list - Contents of the list is displayed.


U

7. Makeempty - Makes the list empty.

Implementation of List ADT


VT

1. Array Implementation

2. Linked List Implementation

3. Cursor Implementation.

Array Implementation of List

Array is a collection of specific number of data stored in a consecutive memory locations.

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

* Find and Printlist operations takes constant time.

* Even if the array is dynamically allocated, an estimate of the maximum size of the

list is required which considerably wastes the memory space.

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.

Types of Linked List

1. Singly Linked List

2. Doubly Linked List

3. Circular Linked List.


lu
So
2.1.2 Singly 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

–The nodes do not reside in sequential locations


–The locations of the nodes may change on different runs
VT

sat
bat

cat vat null


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



•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

bat cat sat vat null


bat cat sat vat null
U

first mat Insert mat after cat


VT

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

Singly Linked Lists (Cont.)


•Deletion

first

bat cat mat sat vat null

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

Push(A) Push(B) Push(C) Push(D) Pop()

Valid Operations on Stack:

 Inserting an element in to the stack (Push)

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

 Deleting an element in to the stack (Pop)


 Displaying the elements in the queue (Display)
Note:
While pushing an element into the stack, stack is full condition should be checked
While deleting an element from the stack, stack is empty condition should be checked

n
Applications of Stack:

tio
Stacks are used in recursion programs
 Stacks are used in function calls
 Stacks are used in interrupt implementation

The Queue ADT

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.

Example : Waiting Line in Reservation Counter,

Operations on Queue

The fundamental operations performed on queue are


U

1. Enqueue

2. Dequeue
VT

Enqueue :

The process of inserting an element in the queue.

Dequeue :

The process of deleting an element from the queue.

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

* To implement Priority Queues.

tio
* Priority Queues can be used to sort the elements using Heap Sort.

* Simulation.

* Mathematics user Queueing theory.

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.

The ADT tree


A tree is a finite set of elements or nodes. If the set is non-empty, one of the nodes
is distinguished as the root node, while the remaining (possibly empty) set of nodes are

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

It is a notational convenience to allow an empty tree. It is usual to represent a tree using a


picture such as Fig. 3.4, in which the root node is A, and there are three subtrees rooted at
B, C and D. The root of the subtree D is a leaf node, as are the remaining nodes, E, F, G,
H and I. The node C has a single child I, while each of E, F, G and H have the same
parent B. The subtrees rooted at a given node are taken to be ordered, so the tree in
VT

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

[A [[B [[E] [F] [G] [H]]] [C [I]] [D]]].

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

ROOT : A node which doesn't have a parent. In the above tree.

NODE : Item of Information.

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.

LENGTH : The length is defined as the number of edges on the path.

DEGREE : The number of subtrees of a node is called its degree.

3.2 BINARY TREE

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

General Tree Binary Tree

* General Tree has any * A Binary Tree has not

lu
number of children. more than two children.

FULL BINARY TREE :-


So
A full binary tree of height h has 2h+1 - 1 nodes.

Here height is 3 No. of nodes in full

binary tree is = 23+1 -1

= 15 nodes.

COMPLETE BINARY TREE :


U

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.

3.2.1REPRESENTATION OF A BINARY TREE


VT

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

You might also like