0% found this document useful (0 votes)
71 views793 pages

CP&DS - All 5 Units - Notes

The document covers C programming fundamentals, including data types, variables, expressions, conditional statements, functions, and arrays. It outlines the structure of C language, rules for naming variables, and the use of header files. Additionally, it discusses control structures such as if statements, loops, and function definitions, along with examples and review questions for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views793 pages

CP&DS - All 5 Units - Notes

The document covers C programming fundamentals, including data types, variables, expressions, conditional statements, functions, and arrays. It outlines the structure of C language, rules for naming variables, and the use of header files. Additionally, it discusses control structures such as if statements, loops, and function definitions, along with examples and review questions for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 793

C Programming and Data Structures

Unit I: C Programming FundamentalsUnit I


Chapter - 1
C Programming Fundamentals

Syllabus
Data Types - Variables - Operations - Expressions and Statements - Conditional
Statements - Functions - Recursive Functions - Arrays - Single and Multi-
Dimensional Arrays.

Contents
1.1 Introduction

1.2 Keywords, Variables and Constants

1.3 Header Files

1.4 Data Types May-19, …. Dec.-19, … Marks 6

1.5 Expressions using Operators ….. May-19, Dec.-19, ….. Marks 13

1.6 Input and Output Operations

1.7 Decision Making and Conditional Statements. …… Dec.-19, ……. Marks 13

1.8 Functions ……. Dec.-18, May-19, ……. Marks 13

1.9 Recursive Functions ……. Dec.-18,19, …….. Marks 13

1.10 Arrays ……. May-19, ………. Marks 7

1.11 Simple Programs …….. Dec.-18, ………. Marks 13

1.12 Two Marks Questions with Answers


Introduction
• C is a structured programming language developed by a programmer Dennis
Ritchie.

• It is also called as a high level programming language.

• It has small instruction set using which development of many engineering


applications is possible.

• It is a case sensitive language. That means it differentiates between the two


variables having the same letters but different cases (upper and lower case).

Keywords, Variables and Constants

Keywords:
Keywords are the standard words in C.

• These are basically the reserved words which have special meaning. The
meaning of keywords cannot be changed.

• All keywords are written in lower case.

• Various keywords used in C are listed below -


Identifiers :
• Identifier is a collection of alphanumeric characters in which the first
character must not be numeric.

• Identifiers are the names given to the variables, functions or constants.

• The name of the identifier must not be the keyword

Validity of variable names


Following are the rules which should be followed while deciding the variable
names
1) The first letter of the variable must not be digit or any special character.

2) Special characters (such as $, #, %) are not allowed in the variable


name except underscore.

3) The variable name is case sensitive. A variable name can be in capital letters.

4) The length of the variable name can be any but only first 31 characters are
recognized.

5) The keywords are not valid variable names.

6) Blank spaces or special characters, commas, use of quotes are not allowed in
the variable name.

7) Arithmetic operators should not be used in the variable names.

The variable names should be informative. It should describe the purpose of it by


its name.

The valid variables are

Count,tax_id,INDEX,Xyz,brick01

The invalid variable names are

_file,char,#id, 1A,valid name

Constants
Definition of constant: The specific alphabetical or numerical value that never
gets changed during the processing of the instructions is called as constant.

• The constant can be alphabetical, numeric or special symbol.

• The constants are given some names and are referred by the names.
• Example: The most commonly used constant is PI. Once the value to this
constant is assigned then it does not get changed.ohcorl tugi

• The names to the constant help in accessing them easily.

• Generally all the letters in the name of the constant are capital.

Comparison between Constants and Variables

Header Files
The header files contain standard library functions. For using these library
functions directly in the program, it is necessary to include the header file at the
beginning of the program.

Following are the header files supported by C


Some commonly used header files are

stdio.h: It is standard input output header file. In this file the functions for printf,
scanf, fprintf, fscanf are defined. These functions deal with input and output
functions.

conio.h: It is Console Input Output header file. In this file the typical functions
such as clrscr() is defined. By using clrscr(), the console (output) screen gets
cleared.

math.h In math.h all the functionalities related to mathematical operations are


defined. Such as pow for computing power, sqrt for computing square root and
many more.

alloc.h: This header file is used when a a function for allocating the
memory dynamically, such as malloc() is used in the program.

Key Point: We have to include header files at the beginning of C program.

Data Types
• Data types specify the type of data we enter in our program.
• In C there are some predefined set of data types which are also called
as primitive data types.

• Primitive data types are fundamental data types.

(1) integer type: These data types are used to store whole number. (i.e. the number
without fraction).

Size and range of Integer type on 16-bit machine :


(2) float type : These are the data types used to store the real numbers (i.e. the
numbers with fractional part).

Size and range of Integer type on 16-bit machine

(3) char type: This data type is used to store the character value.

Size and range of Integer type on 16-bit machine

(4) void type : Void data types mean no value. This data type is normally
associated with a function that return no value.

Review Questions

1. Examine the various data types in C with an example. AU: May-19, Marks 6

2. Give the length and range of the primitive data types. AU: Dec.-19, Marks 2

Expressions using Operators


AU: May-19, Dec.-19, Marks 13

For handling the expressions the operators are used. C support following set of
operators -
Conditional operator :

The conditional operator is? The syntax of using conditional operator is

For example A

a > b?true:false
This means if a is greater than b, if yes then the value will be true otherwise it will
be false.

Precedence of Operators

Precedence means the priority of certain operation.

1. In case there is a tie between operations of same priority preference is given to


the operator which occurs first.

2. Within a paranthesis, the same hierarchy is operative. If there are more than one
set of paranthesis inner most parantheses will be performed first, followed by
operations within second.

e.g. a = 3/2*4+3/8+3

Stepwise evaluation to

a = 3/3*4+3/8+3 operation /
= 1*4+3/8+3 operation

= 4+3/8+30 operation

= 4+0+3 operation +

= 4+3 operation +

=7

Ex. 1.5.1 Determine the output of the following "C" statements: Assume a =
13, b = 25 and c = 5.

i) z = a Λ b ii) x = ++ab iii) y = b++ + C

iv) x = c > b ?1 : 0,

Sol. : i) z = 20 as it is logical bit wise EX-OR operation

The truth table for EX-OR operation is as shown below

As ++a is a pre increment operator the value of a is incremented by one before the
expression gets evaluated.

iii) 30 since y = b++c = 25+ 5

As b++ is a post increment operator, after expression gets incremented the value of
b becomes 26.

iv) 0
The meaning of this expression is if c> b is true then print 1 otherwise 0. As value
of c is less than b the output will be 0.

Review Questions

1. List all the operators in C with an example for each. AU: May-19, Marks 7 oals
neo insmeisje

2. Describe the various operators in C with examples and the associativity. AU:
Dec.-19, Marks 13

Input and Output Operations


In C inputting some data is done by scanf and outputting or printing the data on
console (output screen) is done by printf statement. These are standard library
functions. The way to write these statements is,

scanf(format specifier,variables);

Note that the format specifier is %d since the val is an integer variable. Also the
val variable is taken with the & symbol. The & (ampersand) means "address of".
Any variable is referred by its address. It is exactly similar to the way you find
your friend, either by his address or by his phone number. Thus any variable can be
obtained by its address.

printf(format specifier,variables);

For example: printf("%d",val);

Note that here there is no need of & because we are printing the value of val
variable. This value is already stored in some statement.
Even the printf can also be used to simply print the message on the console.

Decision Making and Conditional Statements


AU: Dec.-19, Marks 13

Various control structures are -

1. if statement

2. while statement

3. do-while statement

4. switch case statement

5. for loop

Let us discuss these control structures with the help of simple examples

1. If statement
There are two types of if statements - simple if statement and compound if
statement. The simple if statement is a kind of if statement which is followed by
single statement. The compound if statement is a kind of if statement for which a
group of statements are followed. These group of statements are enclosed within
the curly brackets.

If statement can also be accompanied by the else part.

Following table illustrates various forms of if statement


2. While statement
The while statement is executing repeatedly until the condition is false. The while
statement can be simple while or compound while. Following table illustrates the
forms of while statements –

3. do…while
The do...while statement is used for repeated execution. The difference between
do while and while statement is that, in while statement the condition is checked
before executing any statement whereas in do while statements the statement is
executed first and then the condition is tested. There is at least one execution of
statements in case of do...while. Following table shows the use of do while
statement.
Note that the while condition is terminated by a semicolon.

4. Switch Case statement


From multiple cases if only one case is to be executed at a time then switch case
statement is executed. Following table shows the use of switch case statements
5. for Loop
The for loop is a not statement it is a loop, using which the repeated execution of
statements occurs. Following table illustrates the use of for loop -
Ex. 1.7.1 Write output of the following C code:

i) #include <stdio.h>

main ( )

int x=3;

float y=3.0;

if (x==y)

printf ("\nx and y are equal");

else

printf ("\nx and y are not equal");

ii) #include <stdio.h>

void main( )

int i=0;

for (; i ;)

printf ("\n Here is some mail for you");

iii) #include <stdio.h>

main( )

int x=4;

while (x==1)
{

x = x-1;

printf ("\n%d", x);

- - X;

Sol. :

i) x and y are equal

ii) The printf statement will not be executed. Hence there will not be any message
on the console.

iii) The printf statement will not be executed.As x=4 and the condition in while
loop gets false. The control will not enter in the loop at all. Hence there will not
be any message on the console.

Ex. 1.7.2 Explain use of "break" and "continue" keywords in "C" with suitable
example.

Sol. : The break statement is used to terminate the execution of the loop. It can
be used to break the looping of for, while, do-while and switch.

For example:

while(i<10)

printf("%d", i)

if(i==5) when i reaches to the value 5 the

while loop will be terminated.


break;

i++;

The continue statement is used to continue the execution of the control loop.

For example:

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

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

if(a[i]= =b[j])→ continue statement skips this value

continue;

else

printf("%d %d", a[i],b[j]);

By above code if a[i] = b[j] simply go back and increment j. Hence if a[i] b[j] then
both a[i] and b[j] will be displayed.

Review Questions

1. Explain Control Statement in C

2. Describe the decision making, branching and looping statements in C.

AU: Dec.-19, Marks 13

Functions
AU: Dec.-18, May-19, Marks 13

If certain set of instructions is required frequently then those instructions are


wrapped within a function.

C programmer handles the C function using three methods -

1. Declaration of function

2. Definition of function

3. Call to the function

For example

void main( )

void sum( ); /* declaration of the function*/

sum( ); /*call to the function*/

void sum( ) /*definition of the function*/

int a,b,c;
printf("\n Enter The two numbers");

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

c=a+b;

printf("\n The Additon Of two numbers is %d",c);

The syntax for declaration of the function is

Return_type Function_name(Data_type Parameter);

The syntax for definition of the function is

Return_type Function_name(Data_type Parameter)

eqyt

erli zag oels so W bloy as nonut edt of 191916

//body of function

The syntax for call to the function is

Function_name(Parameters);

1. Parameter Passing Method


Type 1. Passing nothing and returning nothing.

void main( )

{
void sum ( ); /*declaration of the function*/

void sum( ) /*definition of the function*/

int a,b,c;

printf("\n Enter The two numbers");

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

c=a+b;

printf("\n The Additon Of two numbers is %d",c);

In above example no parameter is passed and there is no return value from the
function. Hence the data type of the above function is void. The void data indicates
that the function is returning nothing or returning NULL.

We can also pass the argument as void to the function main. The parameter void to
function main indicates that there are no parameters to the function main. Thus
instead of void main() we can write void main(void)

Ex. 1.8.1 Write use of void data.

Solution :

• The void data type indicates that the function is returning nothing.

• If the function is not returning anything from the function then its data type is
specified as void. We can also pass the argument void to the function to indicate
that there are no parameters to the function.

Type 2. Passing the parameter and returning nothing.


Here we will see a sample C code in which the function is written with some
parameter.

main( )

int a,b;

void sum(int a,int b);/*declaration*/

printf("\n Enter The two numbers");

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

sum(a,b);/*call*/

void sum(int x, int y)/*definition*/

{.

int c;

c=x+y;

printf("\n The Addition is %d",c);

The parameters a and b are passed. In the definition we have interpreted them as x
and y. You can take them as a, b respectively or x, y or any other names of your
own choice. It makes no difference. It takes them as a and b only. There are
actually two methods of parameter passing.

1. Call by Value.

The above example which we have discussed is of parameter passing by call by


value. This is called by value because the values are passed.

2. Call by Reference.
In call by reference the parameters are taken by reference. Pointer variables are
passed as, parameters.

For example

main()

int a,b;

void sum(int *,int *);

printf("\n Enter The Two Numbers");

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

sum(&a,&b);

void sum(int *x,int *y)

int c;

c=*x+*y;

printf("%d",c);

Difference between Call by Value and Call by Reference


Type 3.

Passing the parameters and returning from the function

In this method the parameters are passed to the function. And this function returns
some value. If the function is returning integer value then the data type of that
function is int. Thus depending upon the type of data which is returning from the
function the data type of that function is determined. If nothing is returned form the
function then that function has a void data type.
void main( )

int a,b,c;

int sum(int,int);/* Only mentioning of data type is allowed

for the parameters*/

printf("\n Enter The Two Numbers");

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

c = sum(a,b);

printf("\n The Addition Is =%d",c);

int sum()

c = a+b;

return c; /*returning c which is of int type*/

/*so data type of sum is int*/

Ex. 1.8.2 Write a C program to interchange two variables without using third
variable.

Solution :

/**************************************

Program to interchange two variables without using third variable


***************************************/

#include <stdio.h>

void main( )

int a=11;

int b=20;

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

a = a+b;

b = a-b;

a = a-b;

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

Ex. 1.8.3: Write a C program to get two numbers and exchange these numbers
using pass by value and pass by reference. AU: Dec.-18, Marks 7

Sol.:

#include<stdio.h>

void swap_by_value(int a, int b)

int temp;

temp = a;

a = b;
b = temp;

void swap_by_ref(int *a, int *b)

int temp;

temp = *a

*a = *b;

*b= temp;

int main( )

int x, y;

printf("\nEnter First number: ");

scanf("%d", &x);

printf("\nEnter Second number: ");

scanf("%d", &y);

printf("\nBefore Swaping x = %d and y = %d", x, y);

swap_by_value(x,y); // Function Call - Pass By Value

printf("\nAfter Swaping(By Value) x = %d and

y = %d", x, y);
printf("\nBefore Swaping x = %d and y = %d", x, y);

swap_by_ref(&x,&y); // Function Call - Pass By Reference

printf("\nAfter Swaping (By Reference) x = %d and

y = %d", x, y);

Output

Enter First number: 10

Enter Second number: 20

Before Swaping x = 10 and y = 20

After Swaping (By Value) x = 10 and y = 20

Before Swaping x = 10 and y = 20

After Swaping (By Reference) x = 20 and y = 10

Review Questions

1. Explain with a suitable example, function call by reference and function call by
value.

2. Write suitable 'C' program that creates different results after passing a
parameter by reference and by values.

3. Illustrate pass by value and pass by reference in functions with an example.

AU May-19, Marks 13

Recursive Functions
AU: Dec.-18,19, Marks 13

Definition: Recursion is a programming technique in which the function calls itself


repeatedly for some input.
By recursion the same task can be performed repeatedly.

Properties of Recursion

Following are two fundamental principles of recursion

1. There must be at least one condition in recursive function which do not involve
the call to recursive routine. This condition is called a "way out" of the sequence
of recursive calls. The is called base case property.

2. The invoking of each recursive call must reduce to some manipulation and
must go closer to base case condition.

While computing factorial using recursive method -

if(n= =0)

return 1; //This is a base case

else

return n*fact (n-1);//on each call the computation will go closer to base case

1. Factorial
Algorithm for Factorial Function using Iterative Definition

1. prod = 1;

2. x=n;

3. while(x>0)

4. {

5. prod = prod*x;

6. X - - ;
7. }

8. return(prod);

Algorithm for Factorial Function using Recursive Definition

1. if(n==0)

2. fact =1;

3. else

4. x-n-1;

5. y= value of x!;

6. fact = n* y;

7. } /*else ends here */

This definition is called the recursive definition of the factorial function. This
definition is called recursive because again and again the same procedure of
multiplication is followed but with the different input and result is again
multiplied with the next input. Let us see how the recursive definition of the
factorial function is used to evaluate the 5!

Step 1. 5! = 5* 4!

Step 2. 4! = 4* 3!

Step 3. 3! = 3 * 2!

Step 4. 1! = 1 * 0!

Step 5. 2! = 2 * 1!

Step 6. 0! = 1.
Actually the step 6 is the only step which is giving the direct result.So to solve 5!
we have to backtrack from step 6 to step 1,collecting the result from each step.
Let us see how to do this.

Step 6'. 0! =1

Step 5'. 1!= 1*0! = 1 from step 6'

Step 4'. 2! 2*1! = 2 from step 5'

Step 3'. 3! = 3*2! = 6 from step 4'

Step 2. 4! 4*3! = 24 from step 3'

Step 1'. 5!= 5*4! = 120 from step 2'

Ex. 1.9.1 Write a C program to find factorial of a number. Using recursive


function.

AU: Dec.-18, Marks 6

Solution :

/*****************************

Program for finding out the factorial for any given number.

******************************/

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

void main(void)

int n,f;
int fact(int n);/* declaration*/

clrscr( );

printf("\n\t\t Program For finding the factorial of n");

printf("\n\n Enter the number for finding the factorial: ");

scanf("%d", &n);

f=fact(n);/*call to fucntion*/

printf("\n the factorial of %d is %d",n,f);

getch( );

int fact(int n)

int x,y;

if(n<0)

printf("The negative parameter in the factorial function");

exit(0);

if(n= =0)

return 1;

x = n-1;

y=fact(x); /*recursive call*/

return(n*y);
}

Output

Program For finding the factorial of n

Enter the number for finding the factorial: 5

the factorial of 5 is 120

2. GCD (Greatest Common Divisor)


In this method the GCD is calculated using following function

gcd (a,b)=gcd(b,a mod b) provided a>b

when we get gcd(a,0)

then

GCD = a

Consider there are two numbers 30 and 18 then we can find GCD as follows -

The above table itself illustrates the procedure for finding GCD using Euclid's
algorithm.
The algorithm in simple steps can be given as -

Step 1: Divide a by b and assign the value of remainder to variable c.

Step 2: Then assign the value of b to a and value of c (remainder of a/b) to b.

Step 3: Repeat the steps 1 and 2 until value of b becomes 0.

Step 4: If b=0 then return value of a as the GCD value of a and b.

Step 5: Stop.

C program

/************************************

Program to find out the greatest common divisor of the two integers.

************************************/

#include< stdio.h >

#include< conio.h >

#include< stdlib.h >

void main(void)

int a,b,ans;

int gcd(int a,int b);

clrscr();

printf("\n\t\t GCD Of two integers");

printf("\n\n Enter the two numbers: ");

scanf("%d %d",&a,&b);
ans=gcd(a,b);

printf("\n The gcd of %d and %d is = %d",a,b,ans);

getch( );

int gcd(int a,int b)

int temp,ans;

if( b< = a &&a%b = =0)

return b;

else

if(a<b)

return(gcd(b,a));

/*the divisior should be less than divident*/

else

ans = a%b;

return(gcd(b,ans));

Output

GCD Of two integers

Enter the two numbers: 12 15


The gcd of 12 and 15 is = 3

3. Fibonacci Sequence
The Fibonacci sequence is the sequence of integers

Each number in this sequence is the sum of two preceding elements.

For example the series can be formed in this way

0+1 = 1, ---- 0th element + 1st element

1+1= 2, ---- 1st element + 2nd element

1+2= 3, ---- 2nd element + 3rd element

2+3 = 5, ---- 3rd element + 4th element

3+5 = 8, ---- 4th element + 5th element

Let fib(0) = 0,fib(1) = 1,We can define the recursive definition of Fibonacci
sequence by the recursive definition :

fib(n) = n if n==0 or n==1 … (1)

fib(n) = fib(n-2)+ fib(n-1)if n>=2 …(2)

Let us apply this definition to compute fib(6)

fib(6) = fib(4) +fib(5) using definition (2)

but fib(4) = (fib(2)+fib(3))

fib(6) = (fib(2)+fib(3)) +fib(5)


= (fib(0)+fib(1))+fib(3)+fib(5) ……… where fib(2) is fib(0)+fib(1)

= 0+1+fib(3)+fib(5) ……. fib(0)=0 and fib(1)=1

= 1+fib(1)+fib(2)+fib(5) …….. where fib(3) is fib(1)+fib(2)

= 1+1+fib(2)+fib(5) …….. .fib(1) is 1 and fib(2)

= fib(0)+fib(1)

= 2+fib(0)+fib(1)+fib(5)

= 2+0+1+fib(5)

= 3+fib(5)

= 3+fib(3)+fib(4)

= 3+fib(1)+fib(2)+fib(4)

= 3+1+fib(2)+fib(4)

= 4+fib(0)+fib(1)+fib(4)

= 4+0+1+fib(4)

= 5+fib(4)

= 5+fib(2)+fib(3)

= 5+fib(0)+fib(1)+fib(3)

= 5+0+1+fib(3)

= 6+fib(1)+fib(2)

= 6+1+fib(2)

= 7+fib(0)+fib(1)

= 7+0+1

Hence fib(6) = 8
Here the recursive definition appears twice e.g. fib(6)=fib(4)+fib(5).

Algorithm for Fibonacci series by recursive method :

int fib(int n)

int x,y;

if(n< = 1)

return n;

x = fib(n-1);

y = fib(n-2);

return (x+y);

Algorithm for Fibonacci series by iterative method :

if(n< = 1)

return (n);

a = 0;

b = 1;

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

x=a;

a=b;

b=x+a;

}
return (b);

C Program

/*******************************************************

Program for computing the number in the fibonacci series at certain location.For
e.g.the sixth number in fibonacci series will be 8.The fibonacci series is 1 1 2 3 5 8
13 21 34...

**********************************************************/

/*header files*/

#include<stdio.h>

#include<conio.h>

void main(void)

int n,num;

int fib(int n);

clrscr( );

printf("\n Enter location in fibonacci series: ");

scanf("%d",&n);

num=fib(n);

printf("\n The number at %dth position is %d in fibonacci series",n,num);

getch();

}
int fib(int n)

int x,y;

if(n< = 1)

return n;

x = fib(n-1);

y = fib(n-2);

return (x+y);

/**************** End of Program ****************/

Output

Enter location in fibonacci series: 9

The number at 9th position is 34 in fibonacci series

4. Tower of Hanoi
The problem is the "Towers of Hanoi". The initial setup is as shown in Fig. 1.9.1.
There are three pegs named as A,B and C. The five disks of different diameters are
placed on peg A. The arrangement of the disks is such that every smaller disk is
placed on the larger disk.

The problem of "Towers of Hanoi" states that move the five disks from peg A to
peg C using peg B as a auxillary.

The conditions are :

i) Only the top disk on any peg may be moved to any other peg.

ii) A larger disk should never rest on the smaller one.

The above problem is the classic example of recursion. The solution to this
problem is very simple.

First of all let us number out the disks for our comfort

The solution can be stated as

1. Move top n-1 disks from A to B using C as auxillary.

2. Move the remaining disk from A to C.

3. Move the n-1 disks from B to C using A as auxillary.

We can convert it to

move disk 1 from A to B.

move disk 2 from A to C.

move disk 1 from B to C.


move disk 3 from A to B

move disk 1 from C to A

move disk 2 from C to B

move disk 1 from A to B

move disk 4 from A to C

move disk 1 from B to C

move disk 2 from B to A

move disk 1 from C to A

move disk 3 from B to C

move disk 1 from A to B


move disk 2 from A to C

move disk 1 from B to C

Thus actually we have moved n-1 disks from peg A to C. In the same way we can
move the remaining disk from A to C.

'C' Program

/******************************************************

Program For Towers of Hanoi. The input will be the number of disks for which the
program should operate.

*******************************************************/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

void main(void)

int n;

void towers (int n,char from, char to,char aux); clrscr();

printf("\n\t\t Program For Towers Of Hanoi");

printf("\n\n Enter the total number of disks");

scanf("%d",&n);
towers(n,'A','C', 'B');

getch();

void towers (int n,char from, char to,char aux)

/*if only one disk has to be moved*/

if(n = =1)

printf("\n Move disk 1 from %c peg to %c peg", from,to);

return;

/*move top n-1 disks from A to B using C*/

towers(n-1,from,aux,to);

printf("\n Move disk %d from %c peg to %c peg",n,from,to);

/* move remaining disk from B to C using A*/

towers(n-1,aux,to,from);

Output

Program for Towers of Hanoi

Enter the total number of disks 4

Move disk 1 from A peg to B peg


Move disk 2 from A peg to C peg

Move disk 1 from B peg to C peg

Move disk 3 from A peg to B peg

Move disk 1 from C peg to A peg

Move disk 2 from C peg to B peg

Move disk 1 from A peg to B peg

Move disk 4 from A peg to C peg

Move disk 1 from B peg to C peg

Move disk 2 from B peg to A peg

Move disk 1 from C peg to A

Move disk 3 from B peg to C

Move disk 1 from A peg to B peg

Move disk 2 from A peg to C peg

Move disk 1 from B peg to C peg

5. Ackerman's Recursive Function


The Ackerman's recursive formula is as given below

• A(0, n): n + 1 for n ≥0

• A(m, 0):= A(m - 1, 1) for m > 0

• A(m, n): A(m - 1, A(m, n - 1)) for m, n > 0


Ex. 1.9.2. Solve A (2, 1) using Ackerman's function

Solution :

Here m = 2, n = 1

A (2, 1) = A (m-1, A (m, n − 1))

= A (1, A (2, 0))

= A (1, A (2-1, 1))

= A (1, A (1, 1))

= A (1, [A(1-1, A (1, 0))])

= A (1, A (0, A (1, 0)))

=A (1, A (0, A (0, 1)))

= A (1, A (0, 2))

= A (1, 3) …. (1)

= A (1, 3) = A (1 - 1, A (1, 3 - 1))

= A (0, A (1, 2))

= A (0, A (1-1, A (1, 2 - 1)))

= A (0, A (0, A (1, 1)))

= A (0, A (0, A (1-1, A (1, 1- 1))))

= A (0, A (0, A (0, A (1, 0)))).

= A (0, A (0, A (0, A (0, 1))))

= A (0, A (0, A (0, 2)))

= A (0, A (0, 3))

A (1, 1) = A (0, 4) = 5 … (2)


Putting value of equation (2) in (1)

A (2, 1) = 5

Ex. 1.9.3 Compute A(1,1) using Ackerman's formula.

Solution:

Let us compute A(1,1)

A(1,1) = A(m-1,A(m,n-1)) = A(0,A(1,0))

= A(0,A(m-1,1))

= A(0,A(0,1) …. (1)

A(0,1) = n+1=2

Putting this value in equation (1) we will get

A(1,1) = A(0,2)= n+1 = 3

C Function

int ackerman(int m, int n, int &count)


C Program

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

int ackerman(int m, int n, int &count)

count++;

if (m = = 0)

}
return (n + 1);

if (n = = 0 && m>0)

return ackerman(m - 1, 1, count);

if (m>0 && n>0)

return ackerman(m - 1, ackerman(m, n - 1, count), count);

int main( )

int m, n;

printf("\n Enter value of m: ");

scanf("%d", &m);

printf("\n Enter value of n: ");

scanf("%d", &n);

int count = 0;

printf("%d", ackerman(m, n, count));

Output
Enter value of m: 2

Enter value of n: 1

6. Comparison between Iteration and Recursion

Review Question

1. Explain recursion and write a C program to print the first 'n' numbers in the
Fibonacci series using recursion.

AU: Dec.-19, Marks 13

Arrays
AU May-19, Marks 7
Arrays can be defined as a set of pair-index and the value. Two basic operations
that can be performed on arrays are: Storing of data at desired location or index
and retrieving data from desired location (index).

Advantages of Arrays

1. Elements can be retrieved or stored very efficiently in array with the help of
index or memory location.

2. All the elements are stored at continuous memory locations. Hence searching
of element from sequential organization is easy.

Disadvantages of Arrays

1. Insertion and deletion of elements becomes complicated due to sequential


nature.

2. For storing the data large continuous free block of memory is required.

3. Memory fragmentation occurs if we remove the elements randomly.

Syntax

The syntax of declaring an array is

data_type name_of_array [size];

For example, int a [10]; double b[10] [10];

Here 'a' is the name of the array inside the square bracket size of the array is
given. This array is of integer type i.e. all the elements are of integer type in array
'a'. Similarly arrays may be of user defined type, called as array of structure C
supports both one dimensional and multidimensional arrays.
1. Initialization
• It is possible to initialize an array during declaration only. For example

int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

• The list of values, enclosed in braces {}, separated by commas, provides the
initial values for successive elements of the array.

• If there are fewer initializers than elements in the array, the remaining elements
are automatically initialized to 0. For example,

int a[10] = (0, 1, 2, 3, 4, 5, 6);

would initialize a[7], a[8], and a[9] to 0.

. When an array definition includes an initializer, the array dimension may be


omitted, and the compiler will infer the dimension from the number of initializers.
For example,

int b[ ] = {10, 11, 12, 13, 14};

would declare, define, and initialize an array b of 5 elements. Here only the
dimension is omitted; the brackets [] remain to indicate that b is in fact an array.

2. Single Dimensional Arrays


Array can be one dimensional and two dimensional.

For example

You can visualize one dimensional array as :


Note that the elements in array are always stored in contiguous memory
locations.

Now let us see how to handle this array. We will write a simple C program in
which we are simply going to store the elements and then we will print those
stored elements.

C Program

#include<stdio.h>

#include<conio.h>

main( )

int a[10],index;

clrscr( );

printf("\n Store The Elements In An Array a");

for(index=0;index < = 9;index++)


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

printf("\n You have stored these numbers in the array a");

for(index=0;index < =9;index++)

printf("\n %d", a[index]);

3. Two Dimensional Arrays


The two dimensional array is something which you can compare with the two
storied building! Extra space which is arranged in rows and columns. Let us draw a
figure which will represent the two dimensional array.

The syntax of two dimensional array is :

Data _ type Name_Of_array[row_size][column_size];

For example

int a[10][10];
By this allocation the memory block of 10 x 10 =100 is getting created. The nested
for loops can be effectively used to access all the elements of an two dimensional
array. We will take a sample example to explain this idea. bon atomolo orb

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

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

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

Execution of Nested for Loop

Initially the value of i=0 at that time

j-0 it will store the element in a[0][0]

j-1 it will store the element in a[0][1]

j-2 it will store the element in a[0][2]

Next time i will be incremented by 1 and now i=1

Again

j=0 it will store the element in a[1][0]

j-1 it will store the element in a[1][1]

j-2 it will store the element in a[1][2]

Next time i will be incremented by 1 and now i=2

j=0 it will store the element in a[2][0]

j-1 it will store the element in a[2][1]


j-2 it will store the element in a[2][2]

Since now value of i and j has reached to 2 the scanning procedure will get
terminated as condition is i<=2 and j<=2. Thus all the elements from a[0][0] to
a[2][2] get scanned.

Ex. 1.10.1 How two dimensional arrays are created in C? Write a C program to
generate a population survey having citizen's record stored as a collection of
year-wise population.

Sol. : Two dimensional array - Refer section 1.10.3

#include <stdio.h>

int main( )

int arr[3][3],i,j;

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

printf("\nEnter the population for country#%d", (i+1));

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

{
printf("\n Enter the population for Year#%d", (j+1));

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

printf("\n printing the population ....\n");

printf("\n\t country#1 country#2 country#3\n");

printf("\n-----------------------\n");

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

printf("Year#%d ", (i+1));

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

printf("\t%dL", arr[i][j]);

printf("\n");

return 0;

Simple Programs
• Program 1.11.1: Sorting Program

AU: Dec.-18, Marks 13


AU: Dec.-18, Marks 6

/*****************************

Program for sorting the elements

*****************************/

/* Header Files*/

#include<stdio.h>

#include<conio.h>

#include <process.h>

/*Declaration*/

void sort(int a[20], int n)

int i,j,m,temp;

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

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

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

{ temp=a[j];

a[j]=a[j+1];

alj+1]=temp;

}
}

//Printing the sorted array//

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

printf("\n\t%d",a[i]);

void main( )

int a[20],i,n;

int ch;

clrscr( );

printf("\nEnter the number of elements in the sorting array: ");

scanf("%d", &n);

//Accepting n number of elements in the array

printf("\nEnter the elements for the array\n");

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

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

bubblesort (a,n);

getch( );

/**************** End Of Program Output ************/

Enter the number of elements in the sorting array: 5

Enter the elements for the array


30

20

50

40

10

10

20

30

40

50

• Program 1.11.2 Searching Program AU: Dec.-18, Marks 7

/***********************************************

Program to perform the linear search operation on some number of elements.

************************************************/

#include<stdio.h>

#include<conio.h>

#define MAX 10

int a[MAX],n,i;

/*

The create Function

Input :none

Output:none
Called By: main

Calls:none

*/

void create( )

printf("\n How Many Elements");

scanf("%d",&n);

printf("\n Enter The Elements");

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

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

/*

The display Function

Input:none

Output:none

Called By:main

Calls:none

*/

void display( )

printf("\n The Elements Are");

for(i=0;i<n;i++)
printf("\n%d",a[i]);

/*

The search function

Input:key element- which is to be searched

Output:the status

Called By:main

Calls:none

*/

search(int k)

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

if(a[i]==k)

return 1;

return 0;

void main( )

int status,key;

clrscr( );
create( );

display( );

printf("\n Enter the Element Which You wish to Search ");

scanf("%d", &key);

status=search(key);

if (status = =1)

printf("\n The Element is Present");

else

printf("\n The Element Is Not Found");

getch();

/**************** End Of Program' **************/

Output

How Many Elements 5

Enter The Elements 10

100

1000

10000

The Elements Are

10

1
100

1000

10000

Enter the Element Which You wish to Search 99

The Element Is Not Found

How Many Elements 5

Enter The Elements 10

100

1000

10000

The Elements Are

10

100

1000

10000

Enter the Element Which You wish to Search 100

The Element is Present

➤ Program 1.11.3 Matrix Operations

The matrix can be represented by a two dimensional array in C program.


Following is a C program that performs various matrix operations.
/*****************************************

Program to perform matrix operations

*****************************************/

#include<stdio.h>

#include<conio.h>

#define MAX 5

void main( )

int a[MAX][MAX],b[MAX] [MAX],c[MAX] [MAX];

int m1,n1,m2,n2;

int choice;

int i,j;

char ans='y';

void Print_Matrix(int c[MAX] [MAX],int,int);

void Addition(int a[MAX] [MAX], int m1,int n1,int b[MAX] [MAX], int c[MAX]
[MAX]);

void Subtraction(int a[MAX] [MAX], int m1,int n1,int b[MAX] [MAX], int
c[MAX] [MAX]);

void Transpose(int a[MAX] [MAX], int m1,int n1,int c[MAX][MAX]);

void Multiplication(int a[MAX][MAX],int,int,int b[MAX] [MAX],int,int,int


c[MAX][MAX]);
printf("\n\t Program for performing matrix operations ");

printf("\n Enter data for matrix a \n");

printf("\n Enter the total number of rows ");

scanf("%d",&m1);

printf("\n Enter the total number of columns ");

scanf("%d", &n1);

printf("\n Enter the elements\n");

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

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

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

printf("\n Enter data for matrix b");

printf("\n Enter the total number of rows ");

scanf("%d", &m2);

printf("\n Enter the total number of columns ");

scanf("%d", &n2);

printf("\n Enter the elements\n");

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

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

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

do

{
printf("\n\t Main Menu");

printf("\n 1. Addition 2. Subtraction 3. Multiplication 4. Transpose");

printf("\n Enter your choice");

scanf("%d", &choice);

switch(choice)

case 1:printf("\n The addition of two matrices is \n");

Addition(a,m1,1,b,c);

Print_Matrix(c,m1,n1);

break;

case 2:printf("\n The subtraction of two matrices is \n");

Subtraction(a,m1,n1,b,c);

Print_Matrix(c,m1,n1); -

break;

case 3:printf("\n The multiplication of two matrices is \n");

if(n1= =m2)

Multiplication(a,m1,n1,b,m2,n2,c);

Print_Matrix(c,m1,n2);

}.

else
printf("\n Multiplication is not possible");

break;

case 4:printf("\n The transpose of matrix a is \n");

Transpose(a,m1,n1,c);

Print_Matrix(c,m1,n1);

break;

printf("\n Do you want to continue?");

ans = getch( );

} while(ans= ='y');

getch( );

void Print_Matrix(int c[MAX] [MAX], int m,int n)

int i,j;

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

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

printf("%d",c[i][j]);

printf("\n");
}

void Addition(int a[MAX] [MAX], int m1,int n1,int b[MAX][MAX], int c[MAX]
[MAX])

int i,j;

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

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

c[i][j]=a[i][j]+b[i][j];

void Subtraction(int a[MAX] [MAX], int m1,int n1,int b[MAX] [MAX], int
c[MAX][MAX])

int i,j;

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

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

{
c[i][j]=a[i][j]-b[i][j];

void Multiplication(int a[MAX][MAX], int m1,int n1,int b[MAX][MAX], int


m2,int n2,int c[MAX][MAX])

int i,j,k;

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

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

c[i][j]=0;

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

c[i][j]=c[i][j]+a[i][k]*b[k][j];

void Transpose(int a[MAX] [MAX], int m1,int n1,int c[MAX][MAX])

int i,j;

for(i=0;i<m1;i++)
{

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

c[i][j]=a[j][i];

Output

Program for performing matrix operations

Enter data for matrix a

Enter the total number of rows 3

Enter the total number of columns 3

Enter the elements

123

456

789

Enter data for matrix b

Enter the total number of rows 3


Enter the total number of columns 3

Enter the elements

111

222

333

Main Menu

1. Addition 2. Subtraction 3. Multiplication

4. Transpose

Enter your choice 1

The addition of two matrices is

234

678

10 11 12

Do you want to continue?

Ex. 1.11.1: Write a C program to get a 4 digit number and display the reverse of
the same number.
AU: Dec.-18, Marks 6

Sol.:

#include <stdio.h>

int main( )

int n, reverse = 0;

printf("\nEnter a four digit number: ");

scanf("%d",&n);

while (n!= 0)

reverse = reverse * 10

int digit n%10;

reverse = reverse + digit;

n = n/10;

printf("\nReverse number is = %d", reverse);

return 0;

Ex.1.11.2 Write a C program to find the following, where A, B and C are the
matrices whose orders are M*N, M*N and N*N respectively. A = A+B*C

AU: Dec.-18, Marks 13


Sol. :

#include<stdio.h>

int main( )

int A[3][3],B[3][3],C[3][3],Temp[3][3],i,j,k,m,n;

printf("Enter the order of the matrix::\n");

scanf("%d %d",&m,&n);

printf("Enter the A matrix::\n");

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

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

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

printf("Enter the B matrix::\n");

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

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

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

}
}

printf("Enter the C matrix::\n");

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

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

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

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

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

Temp[i][j]=0;

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

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

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

{
Temp[i][j]=Temp[i][j]+B[i] [k]*C[k][j]; //performing B*C

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

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

A[i][j]=A[i][j]+Temp[i][j]; //performing A+B*C

printf("The resultant matrix is::\n");

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

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

printf("%d ",A[i][j]);

printf("\n");

}
Two Marks Questions with Answers

Q.1 What is primitive data type?

Ans. : Primitive data types in C are the fundamental data types such as int, float,
char and void.

The int data type is for representing the whole number values.

Q.2 What is the difference between for and while statement ?

Ans. :

Q.3 Explain the use of void data type.

Ans. : • The void data type indicates that the function is returning nothing.
• If the function is not returning anything from the function then its data type is
specified as void.

Q.4 What is the use of arrays ?

Ans. : Array is used to store the elements of same data type. For storing the strings
- the arrays is used.

Q.5 Explain the concept of string in C.

Ans. : String is a collection of characters. For example

char a="hello";

char a=['h', 'e', '1', '1', 'o'];

Q.6 Differentiate between while and do-while loops.

Ans.

Q.7 What do you mean by nested loops ?

Ans.
Nested loops mean loops within the loops. For example for nested, the loop is
given below

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

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

printf("It's My Life!!!");

Q.8 How will you initialize array in C ?

Ans. There are two ways by which an array can be initialized -

i) Initializing an array at declaration.

ii) Initializing an array with the help of loop.

Initializing an array means storing some value in it at some specific location.

i) Initializing an array at declaration -

At declaration of an array it can be initialized..

For example:

int a[5] = {10, 20, 30, 40};

float marks [8] = {33.2, 57.8, 76.5, 81.3};

ii) Initializing array with the help of loop -

Using for loop or while loop an array can be initialized.


For example -

30

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

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

Q.9 What is the purpose of do-while statement ?

Ans. :

The purpose of do-while is to bring looping in programming statements. The way


to write the do... while statement is -

do

statements;

while (some condition);

For example

count = 1

do

printf("\n I am on first line of do-while");


count++;

} while (count < = 5);

Q.10 What are the basic operations performed on an array ?

Ans.: Array is simply a collection of elements which are of same data type.
Mainly we can perform following operations on an array-

i) Storing the elements in an array

ii) Retrieving or printing elements from an array.

Following 'C' program performs these operations-

#include <stdio.h>

#include <conio.h>

main( )

int a[10], index;

clrscr( );

printf ("In Store The Elements In An Array a");

for (index = 0; index < = 9; index++)

scanf("%d", &a[index]);//storing elements in array

printf ("\n Retrieving the array elements");

for (index=0; index <=9; index++)

printf("%d", a[index]); //retrieving elements from array

}
Q.11 List the primary data types in C.

Ans. : Primary data types in C are as given below

Q.12 What are string operations defined in C?

Ans. : Various string operations defined in C are

1) strlen(): For Finding out length of string

2) strcpy(): For copying the one string to another

3) strcat(): For concatenating two strings

4) strcmp(): For comparing two strings

5) strrev(): For reversing two strings

Q. 13 What is a static variable? Give an example.

Ans. : Static variables are those variable that retain their values even after they
come out of the scope.
For example

#include<stdio.h>

int fun( )

static int count = 0;

count++;

return count;

int main( )

printf("\n%d",fun());

printf("\n%d",fun());

printf("\n%d",fun());

printf("\n%d",fun());

return 0;

Output

4
Q.14 Write a C program to get a paragraph of text as input.

AU: Dec.-19

Ans. :

#include<stdio.h>

int main( ) {

char para[100];

printf("Enter Paragraph: ");

scanf("%[^\t]s", para);//accept all the characters except tab

printf("Accepted Paragraph: %s", para);

return 0;

Q.15 How an n dimensional array is represented ?

AU: May-19

Ans. : A multidimensional array is declared using the following syntax : type


array_name[d1][d2] [d3][d4]....................[dn];

where each d is a dimension, and dn is the size of final dimension.

The conceptual syntax for 3D array is this:

data_type array_name[table][row][column];

Q.16 Differentiate between row major and column major representation of


arrays.
AU: Dec.-19

Ans. : In row-major order, consecutive elements of the rows of the array are
contiguous in memory; in column-major order, consecutive elements of the
columns are contiguous.

The difference between row-major and column-major order is simply that the order
of the dimensions is reversed.
C Programming - Advanced Features

Unit II
Chapter - 2
C Programming – Advanced Features

Syllabus
Structures-Union - Enumerated Data Types - Pointers: Pointers to Variables,
Arrays and Functions - File Handling - Preprocessor Directives.

Contents
2.1 Structures …….. May-17, Dec.-18,19, …….. Marks 16

2.2 Union ………. May-19, ……… Marks 13

2.3 Difference between Data Type, Structures and Unions

2.4 Enumerated Data Types

2.5 Pointers ………. May-17, ……. Marks 8

2.6 Arrays and Functions

2.7 File Handling

2.8 Preprocessor Directives

2.9 Two Marks Questions with Answers

Structures
AU May-17, Dec.-18,19, Marks 16
1. Definition
Definition: A structure is a group of items in which each item is defined by some
identifier. These items are called members of the structure. Thus structure is a
collection of various data items which can be of different data types.

The Syntax of declaring structure in C is as follows -

struct name {

member 1;

member 2;

member n;

};

Example :

struct stud {

int roll_no;

char name[10];
float marks;

};

struct stud stud1,stud2;

Using typedef

An alternative to using a structure tag is to use the structure tag is to use the
typed definition in C. For example

typedef struct {

int roll_no;

char name[10];

float marks;

} stud;

The word stud represents the complete structure now. So whenever the word
stud will appear there ever you can assume the complete structure. The stud will
act like a data type which will represent the above mentioned structure. So we
can declare the various structure variables using the tag stud like this-

stud stud1,stud2;

2. Comparison between Arrays and Structures


3. Initializing Structure
There are three different ways by which structure can be defined.

First Way Writing structure variable after structure template

struct student {

int roll_no;

char name[10];

float marks;

}s1;

Second Way: Declare structure variable using struct keyword


struct student {

int roll_no;

char name[10];

float marks;

};

struct student s1;

Third Way: Declaring structure variables using typedef

typedef struct student {

int roll_no;

char name[10];

float marks;

}S;

S, s1;

Ex. 2.1.1 Write a C program to initialize a structure and retrieve the values.

Sol. :

/***********************************************

This Program is for assigning the values to the structure variable. Also for
retrieving the values.

**************************************************/

#include<stdio.h>

#include<conio.h>
#include<stdlib.h>

struct student {

int roll_no;

char name[10];

float marks;

void main(void)

clrscr();

printf("\n Enter the roll number");

printf("\n Enter the name ");

scanf("%s", stud1.name);

printf("\n Enter the marks");

scanf("%f",&stud1.marks);

printf("\n The record of the student is");

printf("\n\n Roll_no Name Marks");

printf("\n-------");
Enter the roll number 1

Enter the name Shrinath

Enter the marks 91.44

The record of the student is

Roll_ no Name Marks

1 Shrinath 91.44

Ex. 2.1.2 Write a C program to represent a complex number using structure and
add two complex numbers.

Sol.:

#include<stdio.h>

#include<conio.h>

typedef struct Complex

float real;

float img;

}C;

void main()

{
C x,y,z;

clrscr();

printf("\n Enter the real part of first complex number");

scanf("%f",&x.real);

printf("\n Enter the imaginary part of first complex number");

toute lebegy

scanf("%f",&x.img);

printf("\n Enter the real part of second complex number");

scanf("%f",&y.real);

printf("\n Enter the imaginary part of second complex number");

scanf("%f",&y.img);

printf("\n\t The First complex number is %3.2f+ %3.2fi",x.real,x.img);

printf("\n\t The second complex number is %3.2f+%.2fi",y.real,y.img);

z.real=x.real+ y.real;

z.img=x.img+ y.img;

printf("\n The Addition is %3.2f+%3.2fi\n",z.real,z.img);

getch( );

}
4. Array of Structures
Definition: Structure is used to store information of one particular object and if
one has to store large number of such objects then array of structure is used.

For example - If there are 10 students in a class then the record of each student is
in structure and 10 such records can be stored in array of structure.

Let us see a sample 'C' program for array of structure.

The program is for storing the record of all the students in a particular class.

/*************************************

Program for maintaining the students' database using structure. The program
shows the use of typedef for a structure variable

************************************/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

typedef struct student {

int roll_no;

char name[20];
int marks;

} stud;

printf("\n Each student's record is");

printf("\n------------");

printf("\n roll_no name marks");

printf("\n-------------");

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

printf("\n%d %s %d",s[i].roll_no,s[i].name,s[i].marks);}

printf("\n--------------“);

getch( );

}
Output

Enter the total number of students 5

Enter Each student's record

Ex. 2.1.3 Database of 100 students is required to be stored. Each student record
contains fields such as roll no, name of student, total marks. Write a program in
'C' to input the database of 100 students with fields mentioned above using:

i) Array ii) Array of structures.

Display record of student who scores maximum marks.

Sol. :

#include<stdio.h>

#include<conio.h>
#include<stdlib.h>

struct student

Int roll_no

char sname[20];

int Total_Marks;

}s[100];

int r[100],m[100];

char n[100][20];

void main( )

int i,j,choice;

clrscr( );

printf("\n 1. Array \n 2.Array of structure ");

printf("\n Enter your choice: ");

scanf("%d", &choice);

switch(choice)

case 1:for(i=0;i< 100;i++)

printf("\n Enter Roll No.: ");

scanf("%d", &r[i]);
printf("\n Enter name of student: ");

scanf("%s",n[i]);

printf("\n Enter Marks: ");

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

j=0;

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

if(m[i]>m[j])/*data with maximum mark is

obtained*/

j=i;/*mark that record by index j*/

printf("\n Student with maximum marks is...");

printf("\n Roll. No.\t Name \t Total Marks ");

printf("\n %d %s %d",r[j],n[j],m[j]);

break;

case 2:for(i=0; i< 100;i++)

printf("\nEnter Roll No: ");

scanf("%d", &s[i].roll no);

printf("\nEnter name of student: ");

scanf("%s",s[i].sname);
printf("\nEnter marks: ");

scanf("%d", &s[i].Total_Marks);

j=0;

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

if(s[i].Total Marks>s[j].Total_Marks)

j=i;

printf("\n Student with maximum marks is...");

printf("\n Roll.No.\t Name \t Total Marks ");

printf("\n %d %S %d",s[j].roll_no,s[j].sname,s[j].Total_Marks);

break;

Ex. 2.1.4 Write down only declaration in 'C' for : A database of 100 students
each with information as roll no, name, address and marks using: i) Only arrays
ii) Array of structures.
Sol. : i) Only arrays:

int roll no [100];

char name [100] [100];

char address [100] [30];

float marks [100];

ii) Array of structures :

struct student

int roll no;

char name [20];

char address [50];

float marks;

}s[100];

Ex. 2.1.5 Develop a structure to represent planet in the solar system. Each
planet has fields for the planet's name, its distance from the sun in miles and
the number of moons it has. Write a program to read the data for each planet
and store. Also print the name of the planet that has less distance from the sun.

Sol.

Following table shows planets in the solar system, their distances from sun in
miles and number of moons.
C Program

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

typedef struct SolarSystem {

char name[20];

int distance;

int no_of_moons;

}Solar;

Solar Planet[10];

void main(void)

{
int n, i, min dist, position;

//clrscr( );

n = 9;//number of planets

printf("\n Enter Each Planet's record"); for (i = 0; i<n; i++)

printf("\n Enter Name of the Planet");

scanf("%s", Planet[i].name);

printf("\n Enter Distance of Planet from sun(in million miles)");

scanf("%d", &Planet[i].distance);

printf("\n Enter Number of Moons");

scanf("%d", &Planet[i].no_of_moons);

printf("\n Each student's record is");

printf("\n----------");

printf("\n Name Distance No_Of_Moons");

printf("\n----------------");

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

printf("\n%s\t%d\t%d", Planet[i].name, Planet[i].distance,


Planet[i].no_of_moons);

printf("\n-----");
min_dist Planet[0].distance;

position = 0;//finding the minimum distant planet from Sun

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

if (min_dist > Planet[i].distance)

min_dist position = Planet[i].distance;

position = i

printf("\n The planet having less distance from the Sun is %s", Planet
[position].name);

Output

Enter Each Planet's record

Enter Name of the Planet Mercury

Enter Distance of Planet from sun(in million miles)36

Enter Number of Moons 0

Enter Name of the Planet Venus

Enter Distance of Planet from sun(in million miles)67

Enter Number of Moons 0

Enter Name of the Planet Earth


Enter Distance of Planet from sun(in million miles)93

Enter Number of Moons 1

Enter Name of the Planet Mars

Enter Distance of Planet from sun(in million miles) 142

Enter Number of Moons 2

Enter Name of the Planet Jupiter

Enter Distance of Planet from sun(in million miles)483

Enter Number of Moons 62

Enter Name of the Planet Saturn

Enter Distance of Planet from sun(in million miles)888

Enter Number of Moons 53

Enter Name of the Planet Uranus

Enter Distance of Planet from sun(in million miles)1784

Enter Number of Moons 21

Enter Name of the Planet Neptune

Enter Distance of Planet from sun(in million miles)2794

Enter Number of Moons 13

Enter Name of the Planet Pluto

Enter Distance of Planet from sun(in million miles)2647

Enter Number of Moons 3

Each student's record is


The planet having less distance from the Sun is Mercury

Ex. 2.1.6 Define a structure to store details of 10 bank customers with customer
name,account no, balance, and city. Write a C program to store the details of
customers in the bank, access and print the customer details for a specified
account no.

Sol. :

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

typedef struct Customer {

int account _ no;

char name[20];

int balance;
char city[20];

}cust;

cust c[10];

int main( )

int n,i;

printf("\n Enter the total number of Customers");

scanf("%d", &n);

printf("\n Enter Each customer's record");

printf("\n Acc_no Name Balance City\n");

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

scanf("%d", &c[i].account_no);

scanf("%s",c[i].name);

scanf("%d", &c[i].balance);

scanf("%s",c[i].city);

printf("\n Each record is");

printf("\n--------");

printf("\n Acc_no Name Balance City");

printf("\n-------------");

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

printf("\n %d\t%s \t%d \t %s",c[i].account_no,c[i].name,c[i].balance,

c[i].city);

return 0;

Output

Enter the total number of Customers 2

Enter Each customer's record

Ex. 2.1.7: Write a C program to get 10 student details using structures from the
user and display these details on the screen.

AU: Dec.-18, Marks 6


Sol. :

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

typedef struct Student {

int roll_no;

char name[20];

int std;

char address [20];

}cust;

cust c[10];

int main()

int i;

printf("\n Enter Each student's record");

printf("\n Roll_no Name Std Address\n”);

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

scanf("%d",&c[i].roll_no);

scanf("%s",c[i].name);

scanf("%d", &c[i].std);

scanf("%s",c[i].address);
}

printf("\n Each record is");

printf("\n---------------“)

printf("\n Roll_no Name Std Address");

printf("\n-------");

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

printf("\n %d\t%s \t%d \t %s",c[i].roll_no,c[i].name,c[i].std,c[i].address);

return 0;

Ex. 2.1.8: Explain structures and write a C program using structures to store
roll_num, name, marks in 10 subjects of 100 students. Calculate the grade of
each student and print the student information. The grades are calculated as
follows -
Sol. :

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

struct student

int roll_no;

char sname[20];

int Marks[10];

char *grade;

}s[100];

void main( )

int i,j;

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

printf("\nEnter Roll No: ");

scanf("%d", &s[i].roll_no);

printf("\nEnter name of student: ");

scanf("%s",s[i].sname);

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

{
printf("\nEnter marks: ");

scanf("%d", &s[i].Marks[j]);

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

int total_marks = 0;

total_marks = total_marks+s[i].Marks [j];

if(total_marks>91 && total_marks <=100)

s[i].grade = "O";

else if(total_marks>81 && total_marks <=90)

s[i].grade = "A+";

else if(total_marks>71 && total_marks < = 80)

s[i].grade ="A";

else if(total_marks>61 && total_marks <=70)

s[i].grade = "B+";

else if(total_marks>50 && total_marks < = 60)

s[i].grade = "B";

else

s[i].grade = "RA";

printf("\n Roll.No.\tName\tGrade ");


for(i-0;i<100;i++)

printf("\n %d\t%s\t%s",s[i].roll_no,s[i].sname,s[i].grade);

5. Structure within a Structure


When a structure is declared in a structure then it is called as nested structure.

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

struct bdate {

int day;

int month;

int year;

}dt;

struct address {

char street[10];

char city[10];

}add;

struct student {
int roll_no;

char name[10];

struct bdate dt;

struct address add;

} std;

void main(void)

clrscr();

printf("\n Enter the student's data");

printf("\n Enter student's rollnumber");

scanf("%d", &std.roll_no);

printf("\n Enter student's name");

scanf("%s",std.name);

printf("\n Enter student's Birth date(mm-dd-yy))";

scanf("%d %d %d", &std.dt.month, &std.dt.day,&std.dt.year);

printf("\n Enter student's Address");

scanf("%s %s",std.add.street,std.add.city);

printf("\n\n You have entered ");

printf("\n roll_no name B'date address");

printf("\n----------");

printf("\n %d %s",std.roll_no,std.name);

printf("%d-%d-%d ",std.dt.month,std.dt.day,std.dt.year);
}

Ex. 2.1.9 Write a C program with appropriate structure definition and variable
declaration to store information about an employee, using nested structures.
Consider the following fields like ENAME, EMPID, DOJ(Date, Month, Year) and
Salary (Basic, DA, HRA)

Sol. :

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

struct JoiningDate

int Date;

int Month;

int Year;

};

struct Amount

float Basic;

float DA;
float HRA;

};

struct Employee {

char ENAME [20];

int EMPID;

struct JoiningDate DOJ;

struct Amount Salary;

}Emp;

void main(void)

printf("\n Enter Name of Employee: ");

scanf("%s",Emp.ENAME);

printf("\n Enter Employee ID: ");

scanf("%d", &Emp.EMPID);

printf("\n Enter Date of Joining of Employee: ");

printf("\n Enter Date: ");

scanf("%d", &Emp.DOJ.Date);

printf("\n Enter Month: ");

scanf("%d", &Emp.DOJ.Month);

printf("\n Enter Year: ");

scanf("%d", &Emp.DOJ.Year);

printf("\n Enter Salary of Employee: ");


printf("\n Enter Basic: ");

scanf("%f",&Emp.Salary.Basic);

printf("\n Enter DA: ");

scanf("%f",&Emp.Salary.DA);

printf("\n Enter HRA: ");

scanf("%f",&Emp.Salary.HRA);

printf("\n Displaying the Employee Record...");

printf("\n Employee Name: %s",Emp.ENAME);

printf("\n Employee ID: %d", Emp.EMPID);

printf("\n Date of Joining (dd-mm-yyyy): %d-%d-%d",

Emp.DOJ.Date,Emp.DOJ.Month, Emp.DOJ.Year);

printf("\n Salary of Employee: %f(Basic) %f(DA)% f(HRA)",

Emp.Salary.Basic,Emp.Salary. DA,Emp.Salary.HRA);

Output

Enter Name of Employee: Anuradha

Enter Employee ID: 101

Enter Date of Joining of Employee:

Enter Date: 10

Enter Month: 10
Enter Year: 2012

Enter Salary of Employee:

Enter Basic: 10000

Enter DA: 5000

Enter HRA: 1000

Displaying the Employee Record...

Employee Name: Anuradha

Employee ID: 101

Date of Joining (dd-mm-yyyy): 10-10-2012

Salary of Employee: 10000.000000 (Basic)5000.000000(DA)

1000.000000(HRA)

6. Structure and Function


There are two simple ways by which the structure can communicate to the
function

1. One can pass the member of the function like an ordinary variable to the
function.
/*******************************************************

Program For passing the structure member as a parameter to the function

********************************************************/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

typedef struct stud

int roll_no;

char name[20];

float marks;

}student;

student st;

void print_rec(int,char[ ],float);

void main( )

char ans;

clrscr( );

do

clrscr( );

printf("\n\t Enter The Record");


printf("\nEnter The roll Number");

scanf("%d", &st.roll_no);

printf("\nEnter The Name");

scanf("%s",st.name);

printf("\nEnter The marks");

scanf("%f",&st.marks);

print_rec(st.roll_no,st.name, st.marks);

printf("\n Do you Want To store more record?");

ans=getche();

}while(ans= ='y');

/**********************************************

This function is for printing the values assigned to structure members

Input :structure members

Output:nones

Called By:main

***********************************************/

void print_rec(int r,char n[],float m)

printf("\n You Have Entered Following Record");

printf("\n %d %S %f",r,n,m);

}
Output

Enter The Record

Enter The roll Number 1

Enter The Name aaa

Enter The marks 76

You Have Entered Following Record

1 aaa 76.000000

Do you Want To store more record?

2. The entire structure can be passed to the function.

/***********************************************

Program For passing the structure as a parameter to the function

************************************************/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

typedef struct stud

int roll_no;

char name[20];

float marks;

}student;
student st;

// Passing entire structure to function

void print_rec(student st);

void main( )

char ans;

clrscr( );

do

clrscr( );

printf("\n\t Enter The Record");

printf("\nEnter The roll Number");

scanf("%d", &st.roll_no);

printf("\nEnter The Name");

scanf("%s",st.name);

printf("\nEnter The marks");

scanf("%f",&st.marks);

print_rec(st);

printf("\n Do you Want To store more record?");

ans=getche();

}while(ans= ='y');

}
/***************************************************

This function is for printing the values assigned to structure members

Input :structure student

Output:none

Called By:main

***************************************************/

void print_rec(student st)

printf("\n You Have Entered Following Record");

printf("\n %d %s %f",st.roll_no,st.name,st.marks);

Output

Enter The Record

Enter The roll Number 1

Enter The Name aaa

Enter The marks 76

You Have Entered Following Record

1 aaa 76.000000

Do you Want To store more record?


Definition: Union is a user defined data structure which is just similar to
structure. It is used to store members of different data types.

Union
AU: May-19, Marks 13

Definition: Union is a user defined data structure which is just similar to structure.
It is used to store members of different data types.

'C' allows another type of structure, the union, which allows the variables to be
interpreted in several different ways.

For example: Consider a structure giving the details of student. Such as his name,
roll number and standard. The categorisation of the standard will be primary or
pre-primary. The primary standard will be denoted by 1, 2 till 4 standards. The
pre-primary standard will be denoted by "Play group", "Jr. K.G.", and "Sr. K.G."
respectively.

Let us see, how it can be denoted in 'C'.

struct student

char name[20];

int roll_no;

union {

int primary;

char pre_pri [10];

}std;

};

For example : If a record of student having name - Rama, roll number as 5 and he
is in 3rd standard. It will be stored in the following manner.
Similarly a record having name Shyam roll number 2 and standard as Jr. K.G will
be mapped as

The structure and the union both are very similar data structures. Both are meant
for storing the various member variables of different data types. But the only
difference between the two is that various members of the structure stored at
various is memory locations. And in case of unions, all the members are stored at
the same memory location and that is why only one member can be accessed at a
time by the unions variable. You just observe the above given example, the union
is defined for the standards primary and pre-primary. Note that the same location
is utilized to store the data of different data types. But at a time you can access
only one data type of union. In case of above example, the memory location for
std will hold either primary data or pre-primary data. The dot operators (exactly
like the structure) are used to access the members of the union.

Ex. 2.2.1 Define union having array of characters of size 2, one integer and one
float as its elements.

Sol. :

union {

char a[2];

int i;

float j;

};
1. Difference between Structure a

Ex. 2.2.2 Illustrate the representation of structure and union for an employee
record having empid, emp-name, DOB, basic pay, allowances, deductions,
grosspay and netpay. Examine their memory allocation.

AU May-19, Marks 13

Sol. : Structure allocates different memory locations for all its members while
union allocates common memory location for all its members. The memory
occupied by a union will be large enough to hold the largest member of the union.

For example - Consider following C program with union w

#include<stdio.h>
union Employee

int empid;

char empName[30];

char dob[20];

float basic_pay;

float allowances;

float deduction;

float grosspay;

float netpay;

};

int main( )

union Employee E;

printf("\nEnter Employee Id : ");

scanf("%d", &E.empid);

printf("\nEnter Employee Name: ");

scanf("%s", &E.empName);

printf("\nEnter Employee dob: ");

scanf("%s", &E.dob);
printf("\nEnter Employee basic_pay: ");

scanf("%f",&E.basic_pay);

printf("\nEnter allowances: ");

scanf("%f",&E.allowances);

printf("\nEnter deductions: ");

scanf("%f",&E.deduction);

E.grosspay = (E.basic_pay+E.allowances);

E.netpay = (E.basic_pay+E.allowances);

- E.deduction;

printf("\n\nEmployee Id : %d",E.empid);

printf("\nEmployee Name: %s",E.empName);

printf("\nEmployee DOB: %s",E.dob);

printf("\nEmployee gross Salary: %f",E.grosspay);

printf("\nEmployee Net Salary: %f",E.netpay);

return 0;

Output

Enter Employee Id: 101

Enter Employee Name: AAA


Enter Employee dob: 12-10-01

Enter Employee basic_pay : 10000

Enter allowances : 2000

Enter deductions : 500

Employee Id: 1148846080

Employee Name :

Employee DOB:

Employee gross Salary: 10000.000000

Employee Net Salary: 0.000000

Note that only one memory location will be used by union at a time, rest of the
locations are treated as garbage. But in structure it is not so, for each member the
structure will allocate the separate memory location

Consider following C program with structure

#include<stdio.h>

struct Employee

int empid;

char empName[30];

char dob[20];

float basic_pay;
float allowances;

float deduction;

float grosspay;

float netpay;

};

int main( )

struct Employee E;

printf("\nEnter Employee Id : ");

scanf("%d", &E.empid);

printf("\nEnter Employee Name : ");

scanf("%s", &E.empName);

printf("\nEnter Employee dob: ");

scanf("%s", &E.dob);

printf("\nEnter Employee basic_pay: ");

scanf("%f",&E.basic_pay);

printf("\nEnter allowances: ");

scanf("%f",&E.allowances);
printf("\nEnter deductions: ");

scanf("%f",&E.deduction);

E.grosspay (E.basic_pay+E.allowances);

E.netpay = (E.basic_pay +E.allowances)

- E.deduction;

printf("\n\nEmployee Id : %d", E.empid);

printf("\nEmployee Name: %s",E.empName);

printf("\nEmployee DOB: %s",E.dob);

printf("\nEmployee gross Salary: %f",E.grosspay);

printf("\nEmployee Net Salary: %f",E.netpay);

return 0;

Output

Enter Employee Id : 101

Enter Employee Name: AAA

Enter Employee dob: 12-10-01

Enter Employee basic_pay : 10000

Enter allowances : 2000

Enter deductions : 500

Employee Id: 101.


Employee Name : AAA

Employee DOB: 12-10-01

Employee gross Salary: 12000.000000

Employee Net Salary: 11500.000000

Difference between Data Type, Structures and Unions


Enumerated Data Types
• Defintion: The enum is an abbreviation used for enumerated data type. When
this keyword is used we can basically initialize the sequence of integer constants.

• The syntax is

enum identifier_name{sequence of items};

• For example :

enum fruit {Mango, Orange, Banana, Grapes, Guava};

• Here fruit is the name given to the set of constants. If there is no value given to
the sequence then by default the first value in the list is 0. For instance here Mango
= 0, Orange = 1, Banana = 2, Grapes = 3 and Guava = 4. We can reassign these
values as well.

• For instance :

Mango = 1, Orange = 2, Banana= 3, Grapes = 4 and Guava = 5.Similarly we can


write

enum fruit {Mango = 2, Orange, Banana-8, Grapes, Guava};

then the values get set automatically as

Mango= 2, Orange = 3

Banana= 8, Grapes = 9, Guava = 10

• The main advantage of enum is that even if we do not initialize the constants,
each one would have a unique value. The first would be zero and the rest would be
one more than the previous one.

• Let us understand the use of enumerated data type with the help of following C
program -

C Program

#include<stdio.h>
#include<stdlib.h>

void main( )

enum fruit {Mango, Orange, Banana, Grapes, Guava};

printf("\n Mango: %d",Mango);

printf("\n Orange: %d", Orange);

printf("\n Banana: %d", Banana);

printf("\n Grapes: %d", Grapes);

printf("\n Guava: %d", Guava);

getch( );

Output

Mango: 0

Orange: 1

Banana: 2

Grapes: 3

Guava: 4

We can declare some variable of enum type and assign the integer constants to this
variable. Just go through the following program and its output:

#include<stdio.h>

#include<stdlib.h>
#include<conio.h>

void main( )

enum fruit {Mango=10,Orange, Banana, Grapes,Guava};

enum fruit points;

clrscr( );

points=Mango;

printf("\n If I eat Mango then I will get %d points", points);

points=(Banana+Grapes);/Banana=12 and Grapes=13/

printf("\n But if I eat Banana and Grapes then");

printf(" I will get %d points",points);

getch( );

Output

If I eat Mango then I will get 10 points

But if I eat Banana and Grapes then I will get 25 points

Review Questions

1. What is the purpose of enumeration type?

2. Explain the data type enumeration? What are the various operations that can
perform on enumeration?

Pointers
AU: May-17, Marks 8
1. Pointers to Variables
Definition : Pointer is a variable that represents the memory location of some
other variable. The purpose of pointer is to hold the memory location and not the
actual value.

In C declaration if the variable is preceded by asterisk or then it is called pointer


variable.

2. Advantages of Pointers
Following are some advantages of using pointer that illustrates its significance.

1. Pointers allow the dynamic memory management.

2. It helps to return more than one values from the function.

3. It allows to pass arrays, strings and structures efficiently.

4. It provides direct access to the memory.

5. It improves the execution speed of the program.

6. It reduces the storage space of the program.

7. Pointers help to build the complex data structures such as linked list, stack,
queues, tree, graphs etc.
3. Initialization
Once the pointer variable is declared then it can be used further. In the sense we
can assign some value to it. But note that the pointer variable is basically used to
store some address of the variable which is holding some value.

Consider,

Line 1- > int *ptr;

Line 2- > int a,b;

Line 3- > a =10; /* storing some value in a*/

Line 4 - > ptr = &a;/*storing address of a in ptr*/

Line 5- > b=*ptr;/*getting value from address in ptr and storing it in b*/

Here we have used two important operators * and &. The * means 'contents at
the

specified address' and & means the 'address at'.

On Line 1 and Line 2 we have declared the required variables out of which ptr is a
pointer variable and variables a and b are our normal variables. On Line 3 we have
assigned value 10 to variable a. The Line 4 tells us that address of variable a is
stored in a pointer variable ptr. And on Line 4 we have written that in ptr variable
we have stored some address and at that address whatever value is stored, store
that value in variable b. That means at ptr we have stored address of variable a.
Then at the address of a whatever is a value we have to store that value in
variable b. This can be illustrated by following Fig. 2.5.1.
We can declare pointer variables of various types such as int, char, double etc.

Consider the declarations as given below -

int *iptr;

char *cptr;

float *fptr;

The iptr will store the address of a variable which is of type integer, similarly cptr
will store the address of a variable which is of character type and so on.

Similarly we cannot initialize the pointer variable in this way-

iptr = 0XCF00; ……………….. is wrong

Similarly we cannot assign one variable of some data type to a pointer variable of
different type

For example,

int *ptr;

float a,b;

a=3.14;
b=10.51;

ptr=&a; /*this is wrong*/

4. Accessing Variable through Pointer


To understand how to access the variables through pointer let us understand the
program given below -

#include<stdio.h>

#include<conio.h>

void main( )

int *ptr;

int a,b;

clrscr();

a=10; /* storing some value in a*/

ptr=&a;/*storing address of a in ptr*/

b=*ptr;/*getting value at ptr in b*/

printf("\n a= %d", a);/*printing value stored at a*/

printf("\n ptr= %u",ptr);/*printing address stored at ptr*/

printf("\n ptr=%d", *ptr); /*Level of indirection at ptr*/

printf("\n b= %d",b);/*printing the value stored at b*/


getch();

Output

a= 10

ptr= 65524

ptr=10

b= 10

Program Explanation :

In above program, firstly we have stored 10 in variable a, then we have stored an


address of variable a in variable ptr. For that we have declared ptr as pointer type.
Then on the next line value at the address stored in ptr is 10 which is been
transferred to variable b. Finally we have printed all these values by some printf
statements.

The following program illustrates the concept of & and * in more detail

#include<stdio.h>

#include<conio.h>

void main()

int *ptr;

int a,b;

clrscr();

a=10;

b=20;
}

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

ptr=&a;

b=*ptr;

printf("\n\n Now the changed values are\n\t

a= %d, b=%d",a,b);

printf("\n ptr = %u",ptr);

printf("\n &ptr = %u", &ptr);

printf("\n *ptr = %d", *ptr);

printf("\n *(&ptr) = %u",*(&ptr));

printf("\n Address of a is &a= %u",&a);

printf("\n Address of b is &b = %u", &b);

getch();

Output

Originally a=10 b=20

Now the changed values are

a=10,b=10

ptr = 65522

&ptr = 65524

*ptr = 10

*(&ptr) = 65522
Address of a is &a= 65522

Address of b is &b = 65520

In above program there are 2 variables and 1 pointer variable. The values stored
in these variables are - Refer Fig. 2.5.2.

Key Point: Whenever we want to store address of some variable into another
variable, then another variable should be of pointer type.

Ex. 2.5.1

Given the following declaration :

int x = 10, y = 10;

int *p1 = Ɛx, *p2 = Ɛy;

What is the value of each of the following expressions?

1) (*p1)++

2) - - (*p2)

3) *p1 + (*p2)- -

4) ++(*p2) - *pl
5) *p1 + *p2

6) - (*p1) + *p2

Sol. :

1) (*p1) ++

Ans: 10

Explanation: First value at p1 is accessed through p1 and then value is


incremented by 1. i.e. (11).

2) -- (*p2)

Ans : 9

Explanation: First value at (p2) is accessed then it is decremented by one (- -) and


then printed as (- -) is used as predecrement operator.

3) *p1 + (* p2) -

Ans: Output 20

Explanation: Here value at p1 and value at p2 are added and then value at p2 is
decremented by 1.

so* p2 = 9

4) ++ (*p2) - * p1

Ans: Output = 1

Explanation: Value at px is considered, then preincrement operator (++) is applied


on that value i.e. (it will be 11) then value at p1 is considered and then
substraction is performed.

5) *p1 + *p2ola

Ans. Output = 20

Value at p1 is added with value at p2.


6) - - (*p1) + *p2

Ans: Output = 19

Explanation: Value at pl is considered, then it is decremented by 1 and then value


at p2 is added with the result.

Ex. 2.5.2 Explain the effect of the following statements:

i) int p, *p;

ii) int q, *p = Ɛ q;

iii) int (* p) ++;

iv) int p++;

v) char *p;

vi) int a = p+5; *

Sol. :

i) int p, *p: This statement will cause a compiler error for multiple declarations of
variable p.

ii) int q, *p = & q: The variable p will act as an interger pointer and will hold the
address of q. Hence the result of q and *p will be the same.

iii) int (* p) ++: The (*p)++ means increment the value of p by 1. But at the
declaration, if we try to increment *p then it will generate syntax declaration
error.

iv) int p + + : The p++ means increment the value of p by 1, but during declaration
we cannot increment the value of variable. A declaration syntax error will be
generated.

v) char *p;: The *p will be a character pointer that means it will store the address
of character variable.
vi) int a = *p + 5; : If *p will store some value then variable a will store the value
of *p + 5.

1) Due to use of pointers the execution of the programs become fast.

2) Pointers are used for dynamic memory allocation. We allocate a block of


memory to an array and it can be accessed using a single pointer.

3) Functions can be handled using pointers.

4) Using pointers the wastage of memory can be avoided.

5) The pointer can be used as a scalar data type as well as the derived data type.

Ex. 2.5.3 Given the following declarations: int m = 50, n = 50, int *p1 = Ɛ m, *p2 =
Ɛ n; What is the value of each of the following expressions?

i) (* p1) ++;

ii) -- (* p2);

iii) *p1 + (*p2) --;

iv) ++ (*p2) - *pl

i) (*p1) ++ gives 50:

Explanation: The value at pl is accessed first. The post increment operator is


given. Hence value will be incremented latter.

ii) - - (*p2) gives 49

Explanation: The -- is a predecrement operator. Hence value at p2 i.e. 50 is


decremented first and then displayed
iii) *p1 + (*p2) -- gives 100

Explanation: Here value at p1 and value at p2 are added and then decremented
by 1.

iv) ++ (*p2) - *p1 gives 1

Explanation: The value at p2 is preincremented which becomes equal to 51 which


value at p1 i.e. 50 is subtracted. Hence is the output.

5. Pointer Arithmetic
Basic Concept: Pointer arithmetic is a method of calculating the address of an
object with the help of arithmetic operations on pointers.

Various operations can be performed using pointer variables as follows -

Let

int *ptr1,*ptr2;

int x;
But here is a list of some invalid operations. These operations are not allowed in
any C program -
Now consider

int *ptr;

This is a pointer variable which is of integer type. This allocates the memory of 2
bytes for each such variable. If there are 10 integer pointers then total 20 bytes of
memory block will be reserved.

Consider a block in memory consisting of ten integers in a row. That is, 20 bytes of
memory are set aside to hold 10 integers.

Now, let's say we point our integer pointer ptr at the first of these integers.
Furthermore lets say that integer is located at memory location 100 (decimal).
What happens when we write :
ptr + 1;

it points to an integer it adds 2 to ptr instead of 1, so the pointer "points to" the
next integer, at memory location 102. The same goes for other data types such as
floats, doubles, or even user defined data types such as structures. This is
obviously not the same kind of "addition" that we normally think of. In C it is
referred to as addition using "pointer arithmetic".

The ptr++ or ++ptr is equivalent to ptr+1

As a block of 10 integers in a contiguous fashion is similar to the concept of array


we will now discuss an interesting relationship between arrays and pointers.

Consider the following:

int my_array[ ] = {1,23,17,4,-5,100};

Here we have an array containing 6 integers. We refer to each of these integers


with the help of subscript of my_array, i.e.
using my_array[0] through my_array[5]. Alternatively, we can also access them
via a pointer as follows:

int *ptr;

/* point out pointer at the first integer in our array */

ptr = &my_array[0];

my_array

my_array [0] is 1 or it is (my_array + 0)

my_array [1] is 25 or it is (my_array + 1) ant

my_array [2] is - 17⇒ (my_array + 2)


my_array [3] is 4 ⇒ (my_array + 3)

my_array [4] is 45 ⇒ (my_array + 4)

my_array [5] is 10 ⇒(my_array + 5)

Fig. 2.5.4 Method 1 for accessing elements of an array

ptr = & my_array [0] i.e. location 0th in array

then * ptr will contain 1 i.e. my-array [0] value

* (Ptr + 1) ⇒ a[1] i.e. 25

* (Ptr + 2) ⇒ a[2] i.e. - 17

* (Ptr + 3) ⇒ a[3] i.e. 4

*(Ptr + 4) ⇒ a[4] i.e. 45

* (Ptr + 5) ⇒ a[5] i.e. 10

Fig. 2.5.5 Method 2 for accessing array elements

then * ptr will contain 1 i.e. my_array [0] value

Thus there are two ways by which array element can be accessed -

1. Using the array subscript

2. Using the pointer to array

Then we can print all the elements of an array. This is illustrated by following
program -

#include <stdio.h>
int my_array[] = {1,25,-17,4,45,10};

int *ptr;

int main(void)

int i;

ptr = &my_array[0]; /* point our pointer to the first element of the array */

printf("\n\n");

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

printf("\nUsing 1st Method: my_array[%d] = %d",i,my_array[i]); /*<-- A */

printf("\nUsing 2nd Method: ptr + %d %d\n",i,

*(ptr + i)); /* < -- B*/

return 0;

Compile and run the above program and carefully note lines A and B and that the
program prints out the same values in either case. Also observe how we
dereferenced our pointer in line B, i.e. we first added i to it and then
dereferenced the new pointer. Thus the output will be -

Output

Using 1st Method: my_array[0] = 1

Using 2nd Method: ptr + 0 = 1


Using 1st Method: my_array[1] = 25

Using 2nd Method: ptr + 1 = 25

Using 1st Method: my_array[2] = - 17

Using 2nd Method: ptr + 2 = - 17.

Using 1st Method: my_array[3] = 4

Using 2nd Method: ptr + 3 = 4

Using 1st Method: my_array[4] = 45

Using 2nd Method: ptr + 4 = 45

Using 1st Method: my_array[5] = 10

Using 2nd Method: ptr + 5 = 10

Now, Change line B to:

printf("ptr + %d %d\n",i, *ptr++);

and run it again...you will get the same result.

Now, change it to :

printf("ptr + %d %d\n",i, *(++ptr));

Try once more. Each time try and predict the outcome and carefully look at the
actual outcome. Again the same result will be achieved.

In C, instead of
ptr = &my_array[0];

we can write :

ptr = my_array;

to achieve the same result. This means that the name of an array is a pointer.

Key Point: "The name of the array is the address of first element in the array".
Using pointer arithmetic (increment or decrement operator) we can access the
subsequent elements of the array.

Ex. 2.5.4 Write a C program using pointer for searching the desired element
from the array.

Sol. :

#include<stdio.h>

#include<conio.h>

void main( )

int a[10],i, n,*ptr,key;

clrscr( );

printf("\n How Many elements are there in an array?");

scanf("%d",&n);

printf("\n Enter the elements in an array");

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

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

ptr=&a[0];/*copying the base address in ptr */


printf("\n Enter the Key element");

scanf("%d", &key);

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

if(*ptr==key)

printf("\n The element is present");

break;

else

ptr++; /*pointing to next element in the array*/

/*Or write ptr=ptr+i*/

getch( );

Output

How many elements are there in an array?5

Enter the elements in an array

10

20

30

40
50

Enter the Key element40

The element is present

Ex. 2.5.5 Write a program using pointer to compute the sum of all elements
stored in any array.

Sol. :

#include<stdio.h>

void main()

int a[ ]={10,20,30,40,50};

int sum=0;

int n=5;

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

sum=sum+(*(a+i));

printf("%d", sum);

Ex. 2.5.6 If we declare an array a [i] [j] and p is pointer to first row find out
i) Pointer to ith row

ii) Pointer to first element in the ith row

iii) Pointer to jth element in ith the row

iv) Value store in the cell a [i][j]

Sol. :

i)

void main( )

int a[][3]={{10,20,30}, {40,50,60}};

int *ptr;

for(int j=0;j<3;j++)

ptr=&a[0][j];

printf("%d", *ptr);

ii)

void main( )

int a[][3]={{10,20,30}, {40,50,60}};

int *ptr;
ptr=&a[0][0];

printf("%d", *ptr);

iii)

void main( )

int a[3][3]={{10,20,30}, {40,50,60}};

int *ptr;

ptr=&a[1][2];

printf("%d", *ptr);

iv)

void main( )

int a[3][3]={{10,20,30}, {40,50,60}};

int *ptr;

for(int i=0;i<2;i++)

for(int j=0;j<3;j++)

ptr=&a[i][j];
printf("%d", *ptr);

printf("\n");

Ex. 2.5.7 Write the output for the following code:

1) int t[3][2][4]={2,4,3,6,1,6,7,9,8,2,1,1,2,3,7,3,1,6,2, 4,0,7,9,5};

printf("%d", *(*(*(t+2)+1)+3));

2) char *cp;

int *ip;

cp=(char *)0×100;

ip=(int *)cp;

ip++;

cp++;

printf("cp=%x ip=%x", cp, ip)'

Sol. :

1) The output is 5 because, the elements are arranged in two rows and four
columns. And there will be 3 such blocks. The arrangement of elements will be
*(t + 2) = {{1, 6, 2, 4}, {0, 7, 9, 5}}

*(*(t + 2) + 1) = {0, 7, 9,.5}

*(*(*(t+2)+1)+3) = 5.

2) The address assigned to cp variable is 100. The same base address i.e. 100 is
assigned to ip. The cp represents character pointer and ip represents interger
pointer. The size of character variable is 1 byte and size of interger variable is 2
bytes.

Hence output is cp = 101 and ip = 102.

6. Strings and Pointers


We can access the string by using the pointer variable. Here is a simple C program
that illustrates the use of pointer for string.
Program for accessing the string using a pointer variable.

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#define size 10

void main(void)

char name[size];

char *i;

clrscr();

printf("\n What is Your name?");

gets(name);

i=name;

printf("\nNow printing your name as ");

while(*i!= '\0')

printf("%c", *i);

i++;

getch();

Output
What is Your name? Parth

Now printing your name as Parth

Now we will use the pointer arithmetic and copy the contents of one string to
another using pointer variable.

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

void main(void)

char *ptr1; /* a pointer to type character */

char *ptr2; /* another pointer to type character */

char str1[] = "Hello India";

char str2[20];

clrscr();

printf("\n The first string i.e. str1 is: ");

puts(str1); /* displays first string */

ptr1 = str1; /* pointer to str1 is set */

printf("\n The pointer ptr1 contains: %s",ptr1);

ptr2 = str2; /* pointer to str2 is set */

while(*ptr1 != '\0')

{ /*copying the contents of ptr1 to ptr2*/

*ptr2++= *ptr1++;
}

*ptr2 = '\0';/*placing the '\0' at the end of the string*/

printf("\n\n The second string i.e. str2 is: ");

puts(str2); /* displays the second string */

getch();/*to avoid pressing alt+F5 to see the console*/

Output

The first string i.e. str1 is: Hello India

The pointer ptr1 contains: Hello India

The second string i.e. str2 is: Hello India

In above program, there are two strings str1 and str2. The string str1 contains a
string "Hello India"

We have taken two pointer variables: ptr1 and ptr2. The starting address (base
address) is assigned to ptr1.

ptr1=str1;

Now we can get the same string "Hello India" in ptr1. Now we have set the ptr2 as
a pointer to second string str2.

ptr2 = str2;

There is nothing in str2, so we will copy the contents of first string to second
string using pointers

while(*ptr1 != '\0')

{/*copying the contents of ptr1 to ptr2*/

*ptr2++= *ptr1++;
}

To terminate str2 we will put '\0' at the end of str2 by assigning

*ptr2 = '\0';

Finally we have printed the contents of str2.

Key Point: We can store one string in a pointer variable of character type. i.e

char *ptr="Hello";

is possible. We can apply pointer arithmetic to access the characters within the
string.

Ex. 2.5.8 Write a C program to concatenate two strings using pointer.

Sol. :

#include<stdio.h>

#include <conio.h>

void main()

char str1[20],str2[10];

char *ptr1,*ptr2;

printf("\n Enter first string ");}

gets(str1);

printf("\n Enter second string ");

gets(str2);

ptr1=str1;
ptr2=str2;

while(*ptr1!= '\0')//reaching at the end of first string

*ptr1++;

while(*ptr2!= '\0')

*ptr1= *ptr2;

*ptr2++;

*ptr1++;

*ptr1='\0';

printf("\n The concatenated string is %s", str1);

getch();

Output

Enter first string Hello

Enter second string India

The concatenated string is HelloIndia

Ex. 2.5.9 Write a "C" function using pointer for string reversal.

Sol. Program for string reversal -

void main()

{
char s1[10],s2[10];

clrscr();

printf("\n Enter The String");

scanf("%s",s1);

char *i=s1;

char *j=s2;

while(*i!= '\0')

i++;

i--; /*reaching at the last character*/

while(i>=&s1[0])/* copying the characters*/

*j++=*i--;

*j='\0';

printf("\n The Reversed string is %s",s2);

getch();

Ex. 2.5.10 Write pseudo C routine using pointers for checking whether a given
string is palindrome.

Sol. Palindrome (char* a) // a is a string

int *p, *q; int flag = 0;

p = q = a;
while (* q!= '10')

q++;

q --;

while (p < q)

if (* p! = *q)

flag = 1;

p++; q--;

if (flag ==0)

printf ("string is palindrome");

else

printf ("\n string is not palindrome");

Ex. 2.5.11 Write a C program to implement any four string handling functions
using functions and pointers.AU May-17, Marks 8

Sol. :

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

int main(void)
{

int choice;

void str_len(),str_concat(), str_copy(), str_reverse();

char ans='y';

do

printf("\n Main Menu");

printf("\n1. Length \n2. Concatenation \n3. Copy \n4. Reverse");

printf("\n Enter your choice: ");

scanf("%d", &choice);

switch(choice)

case 1:str_len();

break;

case 2:str_concat();

break;

case 3:str_copy();

break;

case 4:str_reverse();

break;

printf("\n Do you want to go to main menu?");


} while(ans=='y' || ans == 'Y');

void str_len()

char *ptr,str[10];

int len=0;

printf("Enter some string: ");

scanf("%s", str);

ptr=str;

while(*ptr!='\0')

*ptr++;

len++;

printf("\n The length of string is: %d ",len);

void str_concat()

char str1[20], str2[10];

char *ptr1,*ptr2;

printf("\n Enter first string ");

scanf("%s", str1);
printf("\n Enter second string ");

scanf("%s",str2);

ptr1=str1;

ptr2=str2;

while(*ptr1!= '\0')//reaching at the end of first string

*ptr1++;

while(*ptr2!='\0')

*ptr1=*ptr2;

*ptr2++;

*ptr1++;

*ptr1='\0';

printf("\n The concatenated string is %s", str1);

void str_copy()

char *ptr1; /* a pointer to type character */

char *ptr2; /* another pointer to type character */

char str1[10],str2[20];

printf("\n Enter the first string: ");

scanf("%s", str1);
printf("\n The first string i.e. str1 is: ");

puts(str1); /* displays first string */

ptr1 = str1; /* pointer to str1 is set */

ptr2 = str2; /* pointer to str2 is set */

while(*ptr1 != '\0')

{ /*copying the contents of ptr1 to ptr2*/

*ptr2++ = *ptr1++;

*ptr2 = '\0';/*placing the '\0' at the end of the string*/

printf("\n\n The copied string is: ");

puts(str2); /* displays the second string */

}.

void str_reverse()

char str1[10],str2[10];

printf("\n Enter The String");

scanf("%s", str1);

char *ptr1=str1;

char *ptr2=str2;

while(*ptr1!= '\0')

ptr1++;

ptr1--;
while(ptr1>=&str1[0])/*copying the characters*/

*ptr2++= *ptr 1--;-

*ptr2='\0';

printf("\n The Reversed string is %s", str2);

7. Pointer to Function
The pointer to the function means a pointer variable that stores the address of
function. The function has an address in the memory same like variable. As
address of function name is a memory location we can have a pointer variable
which will hold the address of function. The data type of pointer will be same as
the return type of the function. For instance: if the return type of the function is
int then the integer pointer variable should store the address of that function.

Syntax

Return_Type *pointer_variable (data_type);

For example,

float (*fptr)(float);

Here fptr is a pointer to the function which has float parameter and returns the
value float. Note that the parenthesis around fptr otherwise the meaning will be
different. For example,

float *fptr(float);

This means fptr is a function with a float parameter and returns a pointer to float.

float fun(float);

float (*fptr) (float);


fptr=&fun;

Thus

/*function returning pointer to float */

float *fptr (float a);

/*pointer to function returning float */

float (*fptr) (float a);

The following program illustrates the use of pointer to the function

#include<stdio.h>

#include<conio.h>

void main()

void display(float(*)(int),int);

float area(int);

int r;

printf("\n Enter the radius ");

scanf("%d", &r);

display(area,r);/*function is passed as a parameter to another function*/

void display(float (*fptr) (int), int r)

/*call to pointer to function*/

printf("\n The area of circle is %f", (*fptr) (r));


}

float area(int r)

return (3.14*r*r);

Output

Enter the radius 10

The area of circle is 314.000000

Program Explanation

The function display calls the function area through pointer variable fptr. Thus
fptr is actually a pointer to the function area. As function area returns the float
value we have the pointer as of float type.

Now we will discuss "How to pass a pointer variable as a parameter to the


function?" Let us understand it with the help of following C program

Passing a pointer variable to the function

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>

void main()

int *m;

void fun(int *);

*m=5;
clrscr();

printf("\n Following value is just before function call \n");

printf("%d", *m);

printf("\n Following value is obtained from the function \n");

fun(m);

printf("%d",*m);

void fun(int *x)

*x=10;

Output

Following value is just before function call

Following value is obtained from the function

10

Ex. 2.5.12 What is the effect of the following statements :

i) int a, *b = Ɛa ii) int p, *p iii) a = (float *)Ɛ x iv) int (*fun) ().

Sol. :

i) The pointer variable b is initialized by an address of a.

ii) It will cause an error "multiple declaration for p"


iii) Variable x may be of int type, hence to store the address of x into a float type
variable, the type casting to pointer type float value is done.

iv) This is pointer to a function. This function returns the pointer to integer value.

Ex. 2.5.13 Write a "C" function using pointers to multiply two matrices and
return the resultant matrix to calling function.

Sol. : Multiplication of two matrices using pointers

int *mul(int m,int n,int (*a) [3], int (*b)[3], int (*c)[3])

int i,j,k;

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

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

*(*(c+i)+j)=0;

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

*(*(c+i)+j)= *(*(c+i)+j)+((*(*(a+i)+k))*(*(*(b+k)+j)));

return *(c+0);

Review Questions
1. What is a pointer variable? Explain declaration, initialization and accessing a
pointer variable with an example.

2. What is the data type pointer in C? How do we declare the pointer? Give any
four advantages of using pointers.

3. Explain pointer variable with example.

4. Explain about how to declare pointer to a function with an example. AU: May-
17, Marks 8

Arrays and Functions


When an array is passed as an argument to the function then we are actually
passing the base address of an array to the function. Using this base address we can
access the remaining elements of the array in the function. Thus instead of actual
value, the address is passed as a parameter to the function hence it is
called parameter passing by address.

We will understand this concept with the help of following example -

#include<stdio.h>

#include<conio.h>

void main()

void fun(int a[5]);/*function declaration*/

int a[]={10,20,30,40,50};

clrscr();

fun(a);/*call to the function*/ Passing the base address of an array

getch();

}
void fun(int a[6])

int i;

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

printf("%d",*(a+i));

/* or printf("%d",a[i]);*/

Output

10 20 30 40 50

In above program array name is passed as an argument to the function then


automatically the base address is passed to the function. This should be done when
we give call to the function. While declaring such a function the array name along
with its data type and square brackets [ ] should be specified. Even though we do
not specify the actual size, it is allowed in C.

For example :

While declaring the function with an argument as array -

void fun(int);/*is invalid*/

void fun(a);/*is invalid*/

void fun(a[ ]);/*is invalid*/

void fun(int a);/*is invalid*/

But,

void fun(int a[6]); /*is valid*/

void fun(int a[ ]); /*is valid*/


void fun(int [6]); /*is valid*/

void fun(int []);/*is valid*/

Similarly in function definition -

void fun(int [6]) /*is invalid*/

void fun(int a) /*is invalid*/

void fun(int[])/*is invalid*/

void fun(a[6]) /*is invalid*/

void fun(int) /*is invalid*/

But

void fun(int a[6]); /*is valid*/

void fun(int a[]); /*is valid*/

Program: Write a C program to calculate the sum of all the integers in an


array using pointer.

#include<stdio.h>

#include<conio.h>

void main()

int fun(int []);/*function declaration*/

int a[]={10,20,30,40,50};

clrscr();

printf("\nSum = %d",fun(a));/*call to the function*/

getch();
}

int fun(int a[])

int i,sum=0;

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

sum=sum+ *(a+i);

Using pointer the next location in array is = (a + i) and the value at that location is
obtained by * (a + i)

return sum;

Output

Sum = 150

File Handling
• Definition: File is a collection of records. In generalized form, a file of size n has
n records in sequence where each record is a collection of one or more fields.

• For example:

So with respect to above example we say that the file has 3 records.
To identify each record, a unique key is associated with it. In the above example
Roll No. can be thought of as an key. Using this key, we are in position to access
the information for that student.

• In C file can be declared using the pointer.

• Syntax: FILE *filepointer

• Example: FILE *fp;

FILE is a structure which is defined in "stdio.h". Each file we open will have its own
FILE structure. The structure contains information like usage of the file, its size,
memory location and so on. The fp is a pointer variable which contains the
address of the structure FILE.

1. Classification of File
• There are two types of files - Text file and Binary file.

• The text files are files in which textual information may be stored with
essentially no formatting.

• Binary files in which any type of data (it might be text, image, or audio) encoded
in binary form. The binary files contain the binary digits. That means it contains
the sequence of 1's and 0's.

Comparison between Text File and Binary File


2. File Operations
1. Creating a file / Opening a file :

Syntax filepointer = fopen("filename","mode");

where filename is the name of file you want to create or open

mode can be read - "r"

write - "w"

append - "a"

• Depending on the type of file we want to open/create we use -"rb", "wb", or


just "r", "w", "a".

• Using "r" opens the file in read mode. If the file does not exist, it will create a
new file, but such a file created is of no use as you cannot write to any file in read
mode.

• Using "r+" allows to read from file as well as write to the file.
• Using "w" opens a file in write mode. If the file does not exist, it will create a
new file.

• Using "w+" allows you to write contents to file, read them as well as modify
existing contents.

• Using "a" opens the file in append mode. If the file does not exist, then it
creates a new file. Opening a file in append mode allows you to append new
contents at the end of the file.

• Using "a+" allows to append a file, read existing records, cannot modify existing
records.

Example :

fp = fopen("Student.dat","w");

2. Closing the file:

Syntax: fclose(filepointer);

Example :

fclose(fp); /* closes the file pointed by the fp */

3. Setting the pointer to start of file:

Syntax: rewind (filepointer);

Example :

rewind(fp); /* places pointer at the start of the file */

4. Writing a character to file :

Syntax: fputc( character, filepointer);

Example:

Suppose we have

char ch='a';
To write the character to the file, we use

fputc(ch,fp);

Note: If the file is opened in "w" mode, it will overwrite the contents of the entire
file and write the only character we want to write. To write it at the end of the
file, open the file in "a+" mode.

5. Reading a character from file :

Syntax fgetc( filepointer);

Example :

char ch; /* ch is the character where you are going to get the char from file*/ ch=
fgetc(fp);

6. Writing string to file :

Syntax fputs(string, filepointer);

Example :

Suppose you have a string

char s[]="abcd";

then we write as

fputs(s,fp);

The above operation writes the string "abcd" to the file pointed by fp.

7. Reading string from file :

Syntax fgets(stringaddress, length, filepointer);

Example :

char s[80]; /* declared a string into which we want to read the string from file
*/esolat fgets(s,79,fp); /* Will read the 78, (79-1) characters of string from file
into s */
8. Writing of characters, strings, integers,floats to file :

Syntax :

fprintf(filepointer, "format string", list of variables);

We are already aware of the printf function. fprintf has the same arguments as
that of printf, addition to which filepointer is added. The variables included in the
fprintf are written to the file. But how can we write the data without knowing
their values, so we need to have a scanf function before it and then can write the
data to file. You will understand this better by following example.

'C' Program

/**************************************************************

Program for introducing the file primitives such as fopen,fclose, fprintf.

**************************************************************/

#include<stdio.h>

/*

The main Function

Input:none

Output:none

Called By:O.S.

*/

main()

FILE *fp;

int rno;
char name[20];

clrscr();

fp = fopen("Student.dat", "w");

if(fp== NULL)

printf("File opening error");

exit(1);

printf("Enter the rollno and name:");

scanf("%d %s", &rno,&name);/* asking user to enter data */

fprintf(fp,"%d %s", &rno,&name); /* writing data to file */

fclose(fp);

getch();

return;

/************End Of Program************/

Output

Enter the rollno and name:

aaa

student.dat

1 aaa
9. Reading of variables from file:

Syntax:

fscanf(filepointer, "format string",list of addresses of variables);

Having similar arguments as that of the fprintf statement, the fscanf reads the
contents of the file into the variables specified.

Example :

fscanf(fp,"%d %s", &rno,&name);

printf("Read data is: %d %s",rno,name);

Note: The fprintf and fscanf statements are useful only when the data we want to
enter is less, or rather they have disadvantage that when the number of variables
increase, writing them or reading them becomes clumsy.

10. Writing contents to file through structure :

Syntax: fwrite(pointer to struct, size of struct,no.of data items, filepointer);

/************************************************************

Program for file primitives such as fopen, fwrite. This program writes the string to
the file.

**************************************************************/

#include<stdio.h>

#define MAX 20

struct stud /* structure declaration */

int rno;

char name[MAX];
};

main() {

struct stud s;

FILE *fp;

clrscr();

s.rno=1;

/* fill the structure contents*/

strcpy(s.name,"Sachin");

fp = fopen("Student.dat", "w");

if(fp== NULL)

printf("File opening error");

exit(1);

fwrite(&s,sizeof(s),1,fp); /* write the structure contents to file*/

fclose(fp);

return;

Output

student.dat

Sachin 0 =+ 2
Thus we can see from the output of the program that fwrite writes the data in the
file in binary mode.

11. Reading contents of file through structure :

Syntax:- fread(pointer to struct,size of struct,no.of data items, filepointer);

Example :

To read the contents written in file we can have:-

fread(&s,sizeof(s),1,fp);

Note: Prior to this statement it is necessary that the pointer is located at the
proper position from where we want to read the file. Here you can use the
rewind(filepointer) function.

An fread or fwrite function moves the pointer to the beginning of the next record
in that file.

12. Moving the pointer from one record to another :

Syntax: fseek(filepointer, offset, whence);

where

offset is difference in bytes between offset and whence position.

whence can be:

1) SEEK_SET move the pointer with reference to beginning of the file.

2) SEEK_CUR move the pointer with reference to its current position in file.

3) SEEK_END move the pointer from end of file.

Example :

Let us take the example where we have written a record in file. Suppose we want
to read that record, we have two options:

1) To use rewind function.


2) To use fseek.

We can use fseek in following fashion :

prior to the fclose(fp), we can have

fseek(fp,-sizeof(s), SEEK_CUR);

This will place the pointer to the beginning of the record we have currently
written. Then we can make use of fread(...) to read that record again.

/******************************************************

Use of fseek for positioning the pointers in file

***********************************************************/

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

struct record

int a;

};

void main()

int i,j;

FILE *fp;

struct record r;

clrscr();

/* create the file of 10 records */


fp=fopen("input.dat","w");

for (i=1;i<=10; i++)

r.a=i;

fwrite(&r,sizeof(struct record),1,fp);

fclose(fp);

printf("\n Reading First Record\n");

fp=fopen("input.dat","r");

fseek(fp,OL,SEEK_SET);

fread(&r,sizeof(struct record),1,fp);

printf("%d\n",r.a); fclose(fp); w sw

printf("\n");

printf("Reading all the records sequentially\n");

fp=fopen("input.dat","r");

for (i=1;i<=10; i++)

fread(&r,sizeof(struct record),1,fp);

printf("%d\n",r.a);

fclose(fp);

printf("\n");
printf(" Reading all the records in reverse order\n");

fp=fopen("input.dat","r");

for (i=9; i>=0; i--)

fseek(fp,sizeof(struct record)*i,SEEK_SET);

fread(&r,sizeof(struct record),1,fp);

printf("%d\n",r.a);

fclose(fp);

printf("\n");

/* use fseek to read alternate record */

printf("Reading every Alternate Record from beginning\n");

fp=fopen("input.dat","r");

fseek(fp,0,SEEK_SET);

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

fread(&r,sizeof(struct record),1,fp);

/*After each fread moving to next successive record*/

printf("%d\n",r.a);

/*positioning the pointer to current record in the file*/

fseek(fp,sizeof(struct record), SEEK_CUR);

}
fclose(fp);

printf("\n");

printf("Modifying the desired record");

fp=fopen("input.dat","r+");

/*seeking the 5th record in order to read it*/

fseek(fp,sizeof(struct record)*4,SEEK_SET); fread(&r,sizeof(struct record),1,fp);

/*modifying it by some value*/

r.a=-999;

/*seeking the 5th record in order to write*/

fseek(fp,sizeof(struct record)*4,SEEK_SET);

/*writing the modified value*/.

fwrite(&r,sizeof(struct record),1,fp);

fclose(fp);

printf("\n");

/* read the 10 records to insure 4th record was changed */

fp=fopen("input.dat","r");

for (i=1;i<=10; i++)

fread(&r,sizeof(struct record),1,fp);

printf("%d\n",r.a);

fclose(fp);
printf("\n");

printf("Reading the Last Record\n");

fp=fopen("input.dat","r+");

fseek(fp,sizeof(struct record), SEEK_END);

fread(&r,sizeof(struct record),1,fp);

printf("%d\n",r.a);

Output

Reading First Record

Reading all the records sequentially

10

Reading all the records in reverse order


10

Reading every Alternate Record from beginning

Modifying the desired record

-999
6

10

Reading the Last Record

10

In above program we have used fseek with different modes. The output itself is
self explanatory!!

Reading the characters from the file and printing them on console using getc()

test.cpp

/*************************************************************

Reading the contents of the file using getc and printing them on the console

***********************************************************/

#include <stdio.h>

void main()

FILE *fp;

int ch;

fp = fopen("d:\input.dat","r");

ch = getc(fp);

while (ch!= EOF)


{

putchar(ch);

ch= getc(fp);

fclose(fp);

} 090

Before running this program we should create an input file as d:\input.dat which
is as given below -

input.dat

T
A
S
T
R
U
C
T
R
E
S
Output

T
A

Program Explanation :

In above program we have to first create an input file say input.dat and store
some characters in it. Then the test.cpp is written in which we are opening the
input.dat file in reading mode using fopen(). By using getc(ch) function we can
read the file character by character. The putchar() is a function for printing a
single character on console. The EOF is a marker that indicates end of file. At the
end of program the file is closed using fclose().

/***********************************************************

Program for counting total number of lines and total number of characters from
the input file

************************************************************/

#include <stdio.h>

#include<conio.h>

void main()
{

FILE *fp;

int ch,chara,lines;

char fname[40];

clrscr();

lines = 0;

chara = 0;

printf("Enter file name: "); gets(fname);

fp = fopen( fname, "r" );

if (fp ===NULL)

printf("Error: Cannot open %s \n", fname );

return;

ch= getc( fp);

while (ch != EOF)

if (ch=='\n')/*if new line char is read*/

lines++;/* increment the counter for that*/

chara++;/*increment no. of characters */

ch=getc(fp);

}
{

fclose(fp);

printf("\n In File %s ",fname);

if (chara != 0)

printf("\n Total number of characters = %d\n", chara);

printf("\n Total number of lines = %d", lines );

Input.dat

hello students

we are learning

C and

Files

Output

Enter file name: d:\input.dat

In File d:\input.dat

Total number of characters = 42

Total number of lines = 4

Use of putw and getw

The putw is a function useful for inputting the integer value to the file and getw is
a function used to read the integer value from the input file
/**********************************************************

Program using putw and getw

**********************************************************/

#include <stdio.h>

#include<conio.h>

#include<io.h>

void main()

FILE *fp;

int roll;

char fname[40];

clrscr();

printf("Enter file name: ");

gets(fname);

fp = fopen( fname, "w" );

if (fp==NULL)

printf("Error: Cannot open %s \n", fname );

return;

printf("\n Enter some Roll number");

scanf("%d", &roll);
putw(roll,fp);

fclose(fp);

fp=fopen(fname,"r");

printf("\n The contents in the file %s are..\n",fname);

roll=getw(fp);

printf("\n%d",roll);

fclose(fp);

getch();

Output

Enter file name: d:\input.dat

Enter some Roll number 10

The contents in the file d:\input.dat are... 10

Use of fprintf and fscanf

The purpose of fprintf is to write the contents to the file. That's why we have to
open the file in write mode. Following program illustrates the idea of
using fprintf.

test.cpp

/************************************************************

Program for writing the contents to some input file using fprintf

*************************************************************/

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

void main()

FILE *fp;

int roll;

char fname[40],name [40]="ABC";

float marks;

clrscr();

roll=5;

marks=10.1;

printf("Enter file name: ");

gets(fname);

fp = fopen( fname, "w");

if (fp == NULL)

printf("Error: Cannot open %s \n", fname);

return;

fprintf(fp,"%d\n%s\n%f", roll,name,marks);

fclose(fp);

Output
Enter file name: d:\input.dat

The input file d:\input.dat will have some contents written by our
program test.cpp. Hence input.dat file is

d:\Input.dat

ABC

10.100000

The same program can be modified by adding fscanf. The purpose of fscanf is to
read the contents from the input file. We will

1. Open the input file in writing mode.

2. Write the contents to input file using fprintf.

3. Close the file.

4. Reopen the file in reading mode.

5. Using fscanf we will read the contents from the input file.

6. Print them on the console.

/***********************************************************

The use of fprintf and fscanf for writing to the file And reading from the file

********************************************************/

#include <stdio.h>

#include<conio.h>

void main()

{
FILE *fp;

int roll;

char fname[40],name [40]="ABC";

float marks;

clrscr();

roll=5;

marks=10.1;

printf("Enter file name: "); gets(fname);

fp = fopen( fname, "w" );"

if (fp == NULL)

printf("Error: Cannot open %s \n", fname);

return;

fprintf(fp,"%d\n%s\n%f", roll,name,marks); ni

fclose(fp);

fp=fopen(fname,"r");

printf("\n The contents in the file %s are... \n",fname);

while(!feof(fp))

fscanf(fp,"%d\n%s\n%f",&roll,name,&marks);

printf("%d\n%s\n%f", roll,name,marks);
}

getch();

Output

Enter file name: d:\input.dat

The contents in the file d:\input.dat are...

ABC

10.100000

Detecting End of File

The end of file is detected using a macro EOF (i.e. End Of File) when this condition
occurs then we should not read the contents further.

For example:

#include<stdio.h>

void main()

FILE *fp;

char c;

fp = fopen("try.c","r");

c = getc(fp);

while (c!= EOF)

{
putchar( c );

c = getc (fp);

fclose(fp);

In above program "try.c" file is first created in which we have to store some
characters. Another way of detecting end of file is use of feof() function. In this
function the file pointer is passed as an argument.

For example :

The syntax is

feof(file_pointer);

Let us see the C program based on it.

#include<stdio.h>

void main()

FILE *fp;

char c;

fp = fopen("try.c","r");

c = getc(fp);

while (!feof(fp) )/* feof returns 1 on detecting end of file */

putchar( c );
ic = getc (fp);

fclose(fp);

Review Questions

1. Explain any four functions used for file handling.

2. Explain the different modes of operating a file in C using fopen() function.

3. Sequential File Organization


For understanding the concept of sequential file organization consider one
example : We want to store the marks of 10 students in a file. We will organize
the file in following manner

The C program is as given below -

/***********************************************************
Implementation of various file operations such as create, display, search and
modification on student database with USN,Name and marks of three subjects

*************************************************************/

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<conio.h>

struct record

int USN;

char name[20];

int marks1,marks2, marks3;

};

struct record r;

FILE *fp;

void main()

int n,choice;

char ch;

void Create_file(int);

void Display_file(int);

void Modify_file();
struct record *Search_file();

clrscr();

printf("\n How many Records are there in the file?");

scanf("%d",&n);

do

clrscr();

printf("\n\t Main Menu");

printf("\n1. Create a file");

printf("\n2. Display a file");

printf("\n3. Search a file");

printf("\n4. Modify a file");

printf("\n5. Exit");

printf("\n Enter Your Choice ");

scanf("%d", &choice);

switch(choice)

case 1: Create_file(n);

break;

case 2: Display_file(n);

break;

case 3: r=*Search_file();
printf("\n USN Name marks1 marks2 marks3\n");

printf("\n---------\n");

flushall();

printf("%d %S %d %d %d \n",r.USN, r. name, r. marks1, r. marks2,r.marks3);

printf("\n-----------------\n”);

break;

case 4: Modify_file();

break;

case 5 exit(0);

printf("\n Do You want To Continue?");

ch=getch();

} while (ch=='y' || ch=='Y');

getch();

void Create_file(int n)

int i;

fp=fopen("stud.dat", "a+");

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

printf("\n Enter The name of the student ");


flushall();

gets(r.name);

printf("\n Enter University Seat Number ");

scanf("%d", &r.USN);

printf("\n Enter marks for First Subject ");

scanf("%d", &r.marks1);

printf("\n Enter marks for second Subject ");

scanf("%d", &r.marks2);

printf("\n Enter marks for Third Subject ");

scanf("%d", &r.marks3);

fwrite(&r,sizeof(struct record),1,fp);

fclose(fp);

void Display_file(int n)

int i;

printf("\nReading all the records sequentially\n");

fp=fopen("stud.dat","r");

printf("\n USN Name marks1 marks2 marks3\n");

printf("\n------\n");

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


{

fread(&r,sizeof(struct record),1,fp);

flushall();

printf("%d %S %d %d %d \n",r.USN,r.name, r. marks1, r. marks2,r.marks3);

printf("\n------------------\n");

fclose(fp);

void Modify_file()

int i;

int key,new_USN,new_marks1,new_marks2,new_marks3;

char new_name[20];

printf("Modifying the desired record");

printf("\n Enter the University Seat Number for modification of record ");

scanf("%d", &key);

fp=fopen("stud.dat","r+");

i=0;

while(!feof(fp))

fread(&r,sizeof(struct record),1,fp);

if(r.USN==key)
{

fseek(fp,sizeof(struct record)*i, SEEK_SET);

printf("\n Enter the new record");

printf("\n Enter new name ");

flushall();

gets(new_name);

printf("\n Enter New USN "); scanf("%d",&new_USN);

printf("\n Enter new marks1 ");

scanf("%d",&new_marks1);

printf("\n Enter new marks2 ");

scanf("%d", &new_marks2);

printf("\n Enter new marks3 ");

scanf("%d", &new_marks3);

r.USN=new_USN;

strcpy(r.name,new_name);

r.marks1=new_marks1;

r.marks2=new_marks2;

r.marks3=new_marks3;

fseek(fp,sizeof(struct record)*i, SEEK_SET);

fwrite(&r,sizeof(struct record),1,fp);

i++;
}

fclose(fp);

struct record *Search_file()

int key,i;

printf("\n Enter the University Seat Number for Searching the record ");

scanf("%d", &key);

fp=fopen("stud.dat","r+");

i=0;

while(!feof(fp))

fread(&r,sizeof(struct record),1,fp);

if(r.USN==key)

fseek(fp,sizeof(struct record)*i, SEEK_SET);

fclose(fp);

return &r;

i++;

printf("\n The Record is not present ");


return NULL;

Output

How many Records are there in the file?5

Main Menu

1. Create a file

2. Display a file

3. Search a file

4. Modify a file

5. Exit

Enter Your Choice 1

Enter The name of the student aaa

Enter University Seat Number 1

Enter marks for First Subject 40

Enter marks for second Subject 50

Enter marks for Third Subject 60

Enter The name of the student bbb

Enter University Seat Number 2

Enter marks for First Subject 55

Enter marks for second Subject 66

Enter marks for Third Subject 77

Enter The name of the student cccb02


Enter University Seat Number 3

Enter marks for First Subject 99

Enter marks for second Subject 44

Enter marks for Third Subject 70

Enter The name of the student ddd

Enter University Seat Number 4

Enter marks for First Subject 45

Enter marks for second Subject 65

Enter marks for Third Subject 76

Enter The name of the student eee

Enter University Seat Number 5

Enter marks for First Subject 32

Enter marks for second Subject 43

Enter marks for Third Subject 40

Do You want To Continue?

Main Menu

1. Create a file

2. Display a file

3. Search a file

4. Modify a file

5. Exit

Enter Your Choice 2


Reading all the records sequentially

Do You want To Continue?

Preprocessor Directives
• Pre-processing is a separate step applied on the source file before presenting it to
compilation process.

• The C- preprocessor is a text substitution toll. It instructs the compiler to do all


the necessary preprocessing before and after the compilation

• The pre-processor directive is written at the beginning of the program with the #
preceded to it.

• Following is a list of important Preprocessor directives -


• Pre-processor Examples

(1) #define SIZE 10

This directive tells the compiler to replace the instance of SIZE with 10.

(2) #include<stdio.>

This directive tells to get stdio.h from system libraries and add the text to the
current source file.

(3) #include "myfile.h"

This line tells the compiler to get myfile.h from local director and add the contents
with the current source file.

(4)

#undef F_SIZE

#define F_SIZE 80

It tells to undefine existing F_SIZE and define it as 80.


(5)

#ifndef MSG

#define MSG "Welcome" a

#endif

It tells to define MSG only if MSG isn't already defined.

Two Marks Questions with Answers

Q.1 What is union ?

Ans. : Union is a user defined data structure which is just similar to structure. It is
used to store members of different data types.

Q.2 What is the difference between structure and union ? AU: Dec.-18

Ans. :

Q.3 While handling the structure keyword struct is used.


Ans. :

1) Both the structure and union are user defined data types.

2) The structure and union are meant for storing the various member variables of
different data types.

3) The dot operators are used to access the members of the union and structures.

Q.4 How do you access the address, where the elements of a matrix, whose index
is given is stored ?

Ans : Following program shows how to access the address of particular array

#include<stdio.h>

#include<conio.h>

void main()

int a[]={1,2,3,4,5},i;

int *ptr;

ptr=a;

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

printf("\nAddress of a[%d]=%u",i,ptr);

ptr++;

}
expected output will be

Address of a[0]=65516

Address of a[1]=65518

Address of a[2]=65520

Address of a[3]=65522

Address of a[4]=65524

Q.5 Declare a variable 'code' of type union item consisting of an integer m,float
x and char c. Explain what would be the output of the following statements:

code.c='A';

code.m=385;

code.x=14.7;

printf("%c%d",code.c,code.m);

Ans.:

The output of above code is some garbage value

3 13107

These are basically garbage values because the union assigns memory of the
member occupying highest memory space. In above example float requires highest
memory space(i.e. 4 bytes). And at a time union keeps only one member active.
We have lastly accessed

code.x=14.7;

Hence the variable x will be currently active and remaining members will hold the
garbage values. Hence code.c and code.m are printing garbage values.

Q.6 What do you mean by tag of a structure ?


Ans. :

The structure tag is a name used along with the structure declaration. This tag is
useful in declaration of structure variables.

For example

typedef struct student

int roll;

char name [20];

}st;

Here st is used as a tag for the structure student.

We can declare then

st s1, s2, s3;

The variables s1, s2, s3 are of structure type.

Q.7 What is the use of. operator in structures ?

Ans. :

The operator is used to access the members of the structure.

For example

s1.name or s1.roll

Q.8 Define structure within a structure. What is its scope?


Ans. : The structure within a structure is called nested structure. When we have to
handle a collection of data which is related to another kind of collection of data
then it is comfortable to use nested structures.

For example

struct bdata {

int day;

int mnth;

int year;

} dt;

struct student {

int roll.no;

Char name [10];

struct bdate dt;

} std;

One can access the birthdate of a student by following statements -

printf("\n Enter Student's birth date (mm.dd.yy)");

scanf("%d %d %d", &std.dt.month, &std.dt.day,&std.dt.year);

The scope of the nested structure is within the outer structure, and it can be
accessed with the tag of outer and inner structure.

Q.9 Define preprocessor directives and list out a few examples. AU; Dec.-18,
May-19

Ans. :
• Preprocessor directive is a kind of program which is used to preprocess the C
program before compiling.

• Commands used in preprocessor are called preprocessor directives and they begin
with symbol #.

• Examples of Preprocessor Directives :

• Macro: Using #define the constant value can be defined.

• Header file inclusion: Using #include the required header file can be included in
the C program.

• Conditional compilation: Using #ifdef,#endif#if,#else the conditions can be


included in the program before compilation.

Q.10 Define pointer and initialize it. AU: May-19

Ans. : Pointer is a variable that represents the memory location of some other
variable. It can be initialized as

int a = 10;

int *ptr=&a;

Q.11 What does #include < header_name> do? How is it possible to tell the
preprocessor where to look for header files? AU: Dec.-19

Ans. : The #include is a preprocessor directive which requests the header file. It is
possible to tell the preprocessor to look for the desired header file by specifying its
name and path of the file. For standard header files of C program the system
directories are searched.
Linear Data Structures - List

Unit III
Chapter - 3
a. Linear Data Structures - List

Syllabus
Abstract Data Types (ADTS) - List ADT - Array-Based Implementation - Linked
List - Doubly- Linked Lists - Circular Linked List.

Contents
3.1 Introduction to Data Structure

3.2 Abstract Data Types (ADTs).. May-19,.... Marks 9

3.3 List ADT

3.4 Array-Based Implementation..... May-14, Dec.-18,......Marks 16

3.5 Linked List ..............Dec.-15,18,19, May-16,....Marks 16

3.6 Difference between Array and Linked List

3.7 Doubly Linked List..... Dec.-15, May-16, Dec.-18,.....Marks 16

3.8 Circular Linked List..... Dec.-18,...· Marks 6

3.9 Applications of Linked Lists......Dec.-19,.......Marks 13

3.10 Two Marks Questions with Answers

Introduction to Data Structure


Definition : The data structure can be defined as the collection of elements and all
the possible operations which are required for those set of elements. In other
words data structure will tell us the required elements as well as the legal
operations on those set of elements.

For example :

Consider a set of elements which are required to store in an array. Various


operations such as reading of the elements and storing them at appropriate index
can be performed. If we want to access any particular element then that element
can be retrieved from the array. Thus reading, printing, searching would be the
operations required to perform these tasks for the elements. Thus data object
integer elements and set of operations form the data structure-array.

1. Types of Data Structures

The data structures can be divided into two basic types Primitive and Non
primitive data structures The Fig. 3.1.1. shows various types of data structures.
Linear data structures are the data structures in which data is arranged in a list or
in a straight sequence.

For example

Arrays, List

Non linear data structures are the data structures in which data may be arranged
in hierarchical manner.

For example

Trees, Graphs

Abstract Data Types (ADTs)


AU: May-19, Marks 9

The abstract data type is a triple of D- Set of domains, F - Set of functions, A -


Axioms in which only what is to be done is mentioned but how is to be done is not
mentioned.

In ADT, all the implementation details are hidden. In short

ADT = Type + Function names + Behavior of each function

1. ADT Operations
• While modeling the problems the necessary details are separated out from the
unnecessary details. This process of modeling the problem is called abstraction. It
is why represented by Fig. 3.2.1.
• The model defines an abstract view to the problem. Thus the model focuses
only on problem related stuff and that you try to define properties of the
problem.

• These properties include

i) The data which are affected and

ii) The operations which are identified

• Various Abstract Data Type operations are

1. Create: This operation creates the database

2. Display: This operation is for displaying all the elements of the data structure.

3. Insertion: By this operation the element can be inserted at any desired


position.

4. Deletion: By this operation any desired element can be deleted from the data
structure.

5. Modification: This operation modifies the desired element's value by any


desired new value.
2. ADT Data Structures
The ADT operations are carried out with the help of data structure. This part
describes the structure of the data used in the ADT in an informal way. Various
data structures that can be used for ADT are Arrays, Set, Linked list, Stack, Queues
and so on.

Examples

1. ADT for Set

If we want to write ADT for a set of integers, then we will use following
method AbstractDataType Set

Instances: Set is a collection of integer type of elements.

Preconditions: none

Operations:

1. Store (): This operation is for storing the integer element in a set.

2. Retrieve (): This operation is for retrieving the desired element from the given
set.

3. Display (): This operation is for displaying the contents of set.

There is a specific method using which an ADT can be written. We begin with
keyword AbstractDataType which is then followed by name of the data structure
for which we want to write an ADT. In above given example we have
taken Set data structure.

• Then inside a pair of curly brackets ADT must be written.


• We must first write instances in which the basic idea about the corresponding
data structure must be given. Generally in this section definition of corresponding
data structure is given.

• Using Preconditions or Postconditions we can mention specific conditions that


must be satisfied before or after execution of corresponding function.

• Then a listing of all the required operations must be given. In this section, we
must specify the purpose of the function. We can also specify the data types of
these functions.

2. ADT for Arrays

AbstractDataType Array

Instances: An array A of some size, index i and total number of elements in the
array n.

Operations:

1. Store () - This operation stores the desired elements at each successive


location.

2. display () This operation displays the elements of the array.

Review Question

1. Define data abstraction. Write the ADT for the data structure in which the same
condition can used appropriately, for checking over flow and underflow. Define all
basic function of this ADT. (Hint: Check stack ADT in section 4.2) AU: May-19,
Marks 9

List ADT
• List is a collection of elements in sequential order.
• In memory we can store the list in two ways, one way is we can store the
elements in sequential memory locations. This is known as arrays. And the other
way is, we can use pointers or links to associate the elements sequentially. This
known as Linked Lists.

• Following Fig. 3.3.1 represents this idea of List.

• In ADT the implementation details are hidden. Hence the ADT will be -

AbstractDataType List

Instances: List is a collection of elements which are arranged in a linear manner.

Operations: Various operations that can be carried out on list are -

1. Insertion: This operation is for insertion of element in the list.

2. Deletion: This operation removed the element from the list.

3. Searching: Based on the value of the key element the desired element can be
searched.

4. Modification: The value of the specific element can be changed without


changing its location.

5. Display: The list can be displayed in forward or in backward manner.

• The List can be implemented by two ways -


1. Array based implementation

2. Linked List based implementation

Let us discuss these in detail.

Array Based Implementation


AU: May-14, Dec.-18, Marks 16

• The linked list that can be represented by arrays is called static linked list.

• In this section we will discuss in detail how exactly the list can be represented
using arrays.

• Basically list is a collection of elements.

• To show the list using arrays we will have 'data' and 'link' fields in the array.

• The array can be created as array of structure as

struct node

int data;

int next;

} a[10];

• For instance : Consider a list of (10,20,30,40,50). We can store it in arrays as:


First node. The next field in this node gives the index as 0. Then we get the address
of next node. We can further trace the list using next field

Last node. The next field gives the index as - 1 and - 1 is not any subscript in the
array. Hence - 1 is taken as end of the list.

• Various operations that can be performed on static linked list are -

1. Creation of list.

2. Display of list.

3. Insertion of any element in the list.

4. Deletion of any element from the list.

5. Searching of desired element in the list.

Let us understand each operation one by one.


1. Creation of list

The list can be created by placing the node of list in an array. Each node consists of
two fields 'data' and 'next' pointer. We need to give the address of starting node
which is to be placed in the array.

Thus the list can be created as follows

While creating the list we have to first enter the location in an array where the first
node is placed and then input the pair: data and next.

Int Create()

int head,i;
printf("\n Enter the index for first node");

scanf("%d", &i);

head=i;

while(i!= -1)/*means terminate*/

2. Display

After creation we can display the list. Normally when the list is displayed simply
the data fields are to be displayed.

After creation we can display the list. Normally when the list is displayed simply
the data fields are to be displayed.

void Display(int i)

printf("(");

while(i!= -1)

if(a[i].data==-1)/*no data item present at a[i]*/

printf(" ");

else
{

printf("%d, ",a[i].data);

i=a[i].next;

printf(" NULL)"); YSTS AS

In Insert function, consider that we have already created a list (10, 20, 30, 40) as -

Suppose we want to insert value 21 after 20 then


Now using for loop we will search 'temp' in array 'a'. When we get the value 'temp'
we will come out of loop by using break statement and check for whether the next
location is empty or not.
The list after insertion of 21 will look like this
3. Deletion of a node

While deleting a node from the list we simply manipulate the next pointer of
previous node in the list. And the data field of the node to be deleted is initialized
to - 1.

Consider that the list is

(10,20, 21,30,40)
While deleting this node copy 6 (a[i].next) to the next pointer of previous node in
the list. Here 20 comes before 21 in the list. Hence we will copy a[2].next to
a[1].next. And actual deletion takes place when a[2].data is assigned to -1.
Let us see a C program based on it -

/*************************************************************

Implementation of various List operations using arrays

*************************************************************/

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<conio.h>

/*data structure for list using array*/

struct node

{
int data;

int next;

}a[10];

void main()

char ans;

int i,head, choice;

int Create();

void Display(int);

void Insert();

void Delete();

void Search();

do

clrscr();

printf("\n Main Menu");

printf("\n1. Creation");

printf("\n2. Display");

printf("\n3. Insertion of element in the list");

printf("\n4. Deletion of element from the list");

printf("\n5. Searching of element from the list");

printf("\n6. Exit");
printf("\n Enter Your choice");

scanf("%d", &choice);

switch(choice)

head=Create();

break;

This for loop initialize the data field of list to -1

case 2:Display(head);

break;

case 3:Insert();

break;

case 4:Delete();

break;

case 5:Search();

break;

case 6:exit(0);

}
printf("\n Do you Wish to go to Main Menu?");

ans=getch();

} while(ans =='y' || ans == 'Y');

getch();

int Create()

int head,i;

printf("\n Enter the index for first node");

scanf("%d",&i);

head=i;

while(i!= -1)

printf("\n Enter the data and index of the first element");

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

i=a[i].next;

return head;

void Display(int i)

At data field if value is -1 then it indicates that the location is empty.


printf("(");

while(i!= -1)

if(a[i].data==-1)

printf(" ");

else

printf("%d, ",a[i].data);

i=a[i].next;

printf(" NULL)");

void Insert()

int i,new_data,temp;

printf("\n Enter the new data which is to be inserted");

scanf("%d", &new_data);

printf("\n Enter the data after which you want to insert");

scanf("%d", &temp);

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

{
if(a[i].data==temp)

break;

if(a[i+1].data==-1)/*next location is empty*/

a[i+1].next=a[i].next;

a[i].next=i+1;

a[i+1].data=new_data;

void Delete()

int i,temp,current,new_next;

printf("\n Enter The node to be deleted");

scanf("%d",&temp);

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

if(a[i].data==temp)

if(a[i].next==-1)

a[i].data=-1;/*writing -1 means deleting the element*/


}

current=i;/*marking the index of an array at which record is placed*/


new_next=a[i].next;/*storing the next pointer value at that index*/

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

if(a[i].next== current)

a[i].next=new_next;

a[current].data=-1;

void Search()

int i,temp,flag=0;

printf("\n Enter the node to be searched ");

scanf("%d",&temp);

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

if(a[i].data==temp)
{

flag=1; /*flag 1 means the element is present*/

break;

if(flag==1)

printf("\n The %d node is present in the list",temp);

else

printf("\n The node is not present ");

Output

Main Menu

1. Creation

2. Display

3. Insertion of element in the list

4. Deletion of element from the list

5. Searching of element from the list

6. Exit

Enter Your choice1

Enter the index for first node4

Enter the data and index of the first element10 11

Enter the data and index of the first element20 6


Enter the data and index of the first element30 7

Enter the data and index of the first element40 -1

Do you Wish to go to Main Menu?

Main Menu

1. Creation

2. Display

3. Insertion of element in the list

4. Deletion of element from the list s odra

5. Searching of element from the list

6. Exit

Enter Your choice2

(10, 20, 30, 40, NULL)

Do you Wish to go to Main Menu?

Main Menu

1. Creation

2. Display

3. Insertion of element in the list

4. Deletion of element from the list

5. Searching of element from the list

6. Exit

Enter Your choice6


Although this type of implementation is possible using arrays, it is usually not
preferred to have list implementation using arrays because of two main reasons-

Limitations

1. There is a limitation on the number of nodes in the list because of fixed size of
array. Hence sometimes memory may get wasted because of less elements in the
list or there may be large number of nodes in the list and we could not store some
elements in the array.

2. Insertions and deletions of elements in the array(list) is complicated (Just refer


the functions Insert() and Delete() and feel how complicated they are!)

Hence we will go for dynamic memory allocation for implementing the list.

Key Point: The list creation using dynamic memory management is called linked
list.

Ex. 3.4.1: Consider an array A[1:n]. Given a position, write an algorithm to


insert an element in the array. If the position is empty, the element is inserted
easily. If the position is already occupied the element should be inserted with the
minimum number of shifts.

(Note: The elements can shift to the left or to the right to make the minimum
number of moves) AU: May-14, Marks 16

Sol. :

Algorithm for Insertion of Element in array

Step 1: Enter the number of elements present in the array. Also enter the elements
in the array.

printf("\n How many elements are present in the array?");

scanf("%d",&n);

printf("\n Enter the elements (Type -99 for empty location): ");
for(c=0;c<n;c++)

scanf("%d",&array[c]);

Step 2: Enter the value of the element which is to be inserted in the array, say Key
Element. Also enter the position at which this element is to be
inserted.Say Key_Position.

printf("\n Enter the element to be inserted 2in the array: ");

scanf("%d", &Key_Element);

printf("\n Enter the position at which the element is to be inserted: ");

scanf("%d", &Key_Postion);

Step 3:

//If the Key_Position is empty then insert the Key_Element at that position.
if(array[Key_Postion] ==-99)

array[Key_Position]=Key_Element;

Step 4:

//Otherwise, Count the number of elements present left and right to


this Key_Element. We call it
as LeftElementCount and RightElementCount. for(i=0;i<=Key_Position-1;i++);
//note the semicolon after this for loop

LeftElementCount=i;

for(j=n-1;j>=Key_Position;j—);

RightElementCount=j;

Step 5: If Left ElementCount < RightElementCount then

Search for empty location in this left sublist.


If empty location is present then move the elements to the left by creating ebon to
space at Key_Position then

Insert Key_Element at Key_Position.

else goto step 8

Step 6: If Left ElementCount> RightElementCount then

Search for empty location in this right sublist.

If empty location is present then move the elements to the right by creating space
at Key_Position then

Insert Key_Element at Key_Position.

Else

goto step 8

Step 7:

//Create the space at Key_Position by shifting the last position elements to the
rightmost //empty space.

for(k=n-1;k>=Key_Position-1;k--)

array[k+1]=array[k];

array[Key_Position-1] =Key_Element;

Step 8: Display the list of elements in the array


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

printf("%d", array[c]);

Review Question

1. What are the various operations on array ? Write a procedure to insert an


element in the middle of the array. AU: Dec.-18, Marks 7

Linked List
AU: Dec.-15,18,19, May-16, Marks 16

• Definition: A linked list is a set of nodes where each node has two fields 'data'
and a 'link'. Where data field stores the actual piece of information and 'link' field
is used to point to next node. Basically link field is nothing but the address only.

• Note that the link field of last node consists of 'NULL' which indicates end of
linked list.

1. 'C' Representation of Linked List


'C' structure

typedef struct node

int data; /* data field */


struct node * next; /* link field */

} SLL;

while declaring C structure for a linked list -

• Declare a structure in which two members are there i.e. data member and next
pointer member.

• The data member can be character or integer or real kind of data depending
upon the type of the information that the linked list is having.

• The 'next' member is essentially of a pointer type. And the pointer should be of
structure type. Because the 'next' field holds the address of next node. And each
node is basically a structure consisting of 'data' and 'next'.

2. Types of Linked List


There are various types of linked lists such as,

• Singly linear linked list

• Singly circular linked list

• Doubly linear linked list

• Doubly circular linked list.

Let us see each of the above one by one.

• Singly linear linked list :


It is called singly because this list consists of only one link, to point to next node or
element. This is also called linear list because the last element points to nothing it
is linear is nature. The last field of last node is NULL which means that there is no
further list. The very first node is called head or first.

• Singly circular linked list :

In this type of linked list only one link is used to point to next element and this list
is circular means that the last node's link field points to the first or head node.
That means according to example after 40 the next number will be 10. So the list
is circular in nature.

• Doubly linear linked list :

This list called doubly because each node has two pointers previous and next
pointers. The previous pointer points to previous node and next pointer points to
next node. Only in case of head node the previous pointer is obviously NULL and
last node's next pointer points to NULL. This list is a linear one.

• Doubly circular linked list:

In circular doubly linked list the previous pointer of first node and the next pointer
of last node is pointed to head node. Head node is a special node which may have
any dummy data or it may have some useful information such as total number of
nodes in the list which may be used to simplify the algorithms carrying various
operations on the list.

3. Linked List Implementation


• Various operations of linked list are -

1. Creation of linked list.

2. Display of linked list.

3. Insertion of any element in the linked list

4. Deletion of any element from the linked list

5. Searching of desired element in the linked list.

We will discuss each operation one by one

1. Creation of linked list

node* create()

node *temp, *New, *head;

int val, flag;

char ans='y';

node *get_node();

temp = NULL;

flag = TRUE; /* flag to indicate whether a new node is created for the first time or
not */

do
{

printf("\nEnter the Element :");

scanf("%d", &val);

seoqug /* allocate new node */

New = get_node();

if (New == NULL)

printf("\nMemory is not allocated");

New → data =val;

if (flag==TRUE) /* Executed only for the first time */

head = New;

0.ebon Jer

temp = head; /*head is a first node in the SLL*/

flag = FALSE;

else

/* temp keeps track of the most recently created node */

temp → next = New;

temp = New;

printf("\n Do you Want to enter more elements? (y/n)");


ans=getche();

} while(ans == 'y');

printf("\nThe Singly Linked List is created\n");

getch();

clrscr();

return head;

node *get_node()

node *temp;

temp=( node *) malloc(sizeof(node));

temp → next = NULL;

return temp;

Creation of linked list (logic explanation part) :

Initially one variable flag is taken whose value is initialized to TRUE (i.e. 1). The
purpose of flag is for making a check on creation of first node. That means if flag is
TRUE then we have to create head node or first node of linked list. Naturally after
creation of first node we will reset the flag (i.e. assign FALSE to flag). Consider that
we have entered the element value 10 initially then,

Step 1:
New = New get_node ();

/* memory gets allocated for New node */

New → data=: Val;

/* value 10 will be put in data field of New */

Step 2:

if (flag == TRUE)

head=New

temp=head;

/* We have also called this node as temp because head's address will be
preserved in 'head' and we can change 'temp' node as per requirement */

flag = FALSE;

/* After creation of first node flag is reset */

Step 3:
If head node of linked list is created we can further create a linked list by
attaching the subsequent nodes. Suppose we want to insert a node with value 20
then,

Step 4:

If user wants to enter more elements then let say for value 30 the scenario will
be,

Then for value 40

Step 5:
is the final linked list.

2. Display of linked list

We are passing the address of head node to the display routine and calling head
as the 'temp' node. If the linked list is not created then naturally head-temp node
will be NULL. Therefore the message "The list is empty" will be displayed.

void display(node *head)

{to iluests A gool sli

node *temp;

temp = head;

if (temp==NULL)

printf("\nThe list is empty\n");

getch();

clrscr();

return;
}.

while (temp != NULL)

printf("%d → ", temp →data);

temp = temp →next;

printf("NULL");

getch();

clrscr();

If we have created some linked list like this then -


As now value of temp becomes NULL we will come out of while loop. As a result
of such display routine we will get,

10 20 30 40 50 → NULL

will be printed on console.

3. Insertion of any element at anywhere in the linked list

There are three possible cases when we want to insert an element in the linked
list -

a) Insertion of a node as a head node


b) Insertion of a node as a last node

c) Insertion of a node after some node.

We will see the case a) first -

node *insert_head(node *head)

node *New,*temp;

New-get_node();

printf("\n Enter The element which you want to insert");

scanf("%d", &New→data);

if(head== NULL)
Now we will insert a node at the end -

void insert last (node *head)


{

node *New,*temp;

New get_node();

printf("\n Enter The element which you want to insert");

scanf("%d", &New→data);

if(head == NULL)

head=New;

else

Finding end of the linked list. Then temp will be a last node

temp=head;

while(temp →next!= NULL)

temp-temp →next;

temp →next=New;

New →next=NULL;

To attach a node at the end of linked list assume that we have already created a
linked list like this-
Now we will insert a new node after some node at intermediate position

void insert after(node *head)

int key;

node *New,*temp;

New= get_node();

printf("\n Enter The element which you want to insert");

scanf("%d",&New→data);

if(head= NULL)

{
head=New;

Else

printf("\n Enter The element after which you want to insert the node");

scanf("%d", &key);

temp=head;

do

if(temp →data==key)

New →next=temp →next;

temp →next=New;

return;

else

temp-temp →next;

}while(temp!= NULL);

If we want to insert 31 in the linked list which is already created. We want to


insert this 31 after node containing 30 then
Thus desired node gets inserted at desired position.

4. Deletion of any element from the linked list

void dele(node **head)

node *temp, *prev;


int key;

temp =*head;

if (temp == NULL)

printf("\nThe list is empty\n");

getch();

Always check before deletion whether come? the linked list is empty or not.
Because if the list is empty there is no point in performing deletion

clrscr();

return

clrscr();

printf("\nEnter the Element you want to delete: ");

scanf("%d", &key);

temp = search(*head,key);

if (temp != NULL)

Firstly, Node to be deleted is searched in the linked list

prev = get_prev(*head,key);

if (prev != NULL)

prev → next = temp→next;


free (temp);

Once the node to be deleted is found then get the previous node of that node in
variable prev

else

*head=temp →next;

free(temp);

If we want to delete head node then set adjacent node as a new head node and
then deallocate the previous head node

printf("\nThe Element is deleted\n");

getch();

Suppose we have,

Suppose we want to delete node 30. Then we will search the node containing 30,
using search (*head, key) routine. Mark the node to be deleted as temp. Then we
will obtain previous node of temp using get_prev () function. Mark previous node
as prev
This can be done using following statements.

*head = temp → next;

free (temp);

5. Searching of desired element in the linked list

The search function is for searching the node containing desired value. We pass
the head of the linked list to this routine so that the complete linked list can be
searched from the beginning.

node *search(node *head, int key)

{
node *temp;

int found;

temp =head

if (temp == NULL)

printf("The Linked List is empty\n");

getch();

clrscr();

return NULL;

found = FALSE;

while (temp != NULL && found == FALSE)

if (temp→data != key)

temp = temp→next;

else

Compare each node with the key value. If not matching then move to next node

Found =TRUE;

if (found ==TRUE)

{
If the node containing desired data is obtained in the linked list then found
variable is set to TRUE.

printf("\nThe Element is present in the list\n");

getch();

return temp;

else

printf("The Element is not present in the list\n");

getch();

return NULL;

Consider that we have created a linked list as

Suppose key = 30 i.e. we want a node containing value 30 then compare temp→
data and key value. If there is no match then we will mark next node as temp.
Hence print the message "The Element is present in the list".

Thus in search operation the entire list can be scanned in search of desired node.
And still, if required node is not obtained then we have to print the message.

"The Element is not present in the list"

Let us see the complete program for it -

Ex. 3.5.1: Implementation of various operations on singly linked list

/*****************************************************************

Program to perform various operations such as creation, insertion, deletion,


search and display on singly link lists.

************************************************************/

#include <stdio.h>

#include <conio.h>
#include <stdlib.h>

#define TRUE 1

#define FALSE 0

typedef struct SLL

int data;

struct SLL *next;

}node;

node *create();

void main()

/* Local declarations */

int choice, val;

char ans;

node *head;

void display(node *);

node *search(node *,int);

node *insert(node *);

void dele(node **);

head =NULL;

do

{
clrscr();

printf("\nProgram to Perform Various operations on Linked List");

printf("\n1.Create");

printf("\n2.Display");

printf("\n3.Search for an item");

printf("\n4.Insert an element in a list");

printf("\n5.Delete an element from list");

printf("\n6.Quit");

printf("\nEnter Your Choice (1-6) ");

scanf("%d", &choice);

switch( choice)

case 1: head=create();

break;

case 2: display(head);

break;

case 3: printf("Enter the element you want to search");

scanf("%d", &val);

search(head, val);

break;

case 4: head-insert(head);

break;
case 5: dele(&head);

break;

case 6 exit(0);

default:clrscr();

printf("Invalid Choice, Try again");

getch();

} while(choice != 6);

node* create()

node *temp, *New, *head;

int val, flag;

char ans='y';

node *get_node();

temp = NULL;

flag=TRUE; /* flag to indicate whether a new node is created for the first time or
not */

do

printf("\nEnter the Element :");

scanf("%d", &val);
/* allocate new node */

New = get_node();

if (New==NULL)

printf("\nMemory is not allocated");

New → data = val;

if (flag==TRUE) /* Executed only for the first time */

head = New;

temp-head; /*head is a first node in the SLL*/

flag = FALSE;

else {

/* temp keeps track of the most recently created node */

temp →next=New;

temp =New;

rintf("\n Do you Want to enter more elements?(y/n)");

ans=getche();

}while(ans=='y');

printf("\nThe Singly Linked List is created\n");

getch();

clrscr();
return head;

node *get_node()

node *temp;

temp=( node *) malloc(sizeof(node) );

temp →next = NULL;

return temp;

void display(node *head)

node *temp;

temp=head;

if (temp == NULL)

printf("\nThe list is empty\n");

getch();

clrscr();

return;

while (temp != NULL)

{
printf("%d → ", temp →data);

temp=temp →next;

printf("NULL");

getch();

clrscr();

node *search(node *head, int key)

node *temp;

int found;

temp = head;

if (temp==NULL)

printf("The Linked List is empty\n");

getch();

clrscr();

return NULL;

found = FALSE;

while (temp != NULL && found == FALSE)

if (temp →data != key)


temp = temp →next;

else

found=TRUE;

if (found ==TRUE)

printf("\nThe Element is present in the list\n");

getch();

return temp;

else

printf("The Element is not present in the list\n");

getch();

return NULL;

/*

The insert function

Input:Address of starting node of the list

Output:inserts an element into the list

Parameter Passing Method: call by value


Called By:main

Calls search()

*/

node *insert(node *head)

int choice;

node *insert_head(node *);

void insert_after(node *);

void insert last(node *);

printf("\n 1. Insert a node as a head node");

printf("\n 2. Insert a node as a last node");

printf("\n 3. Insert a node at intermediate position in the linked list");

printf("\n Enter the your choice for insertion of node");

scanf("%d", &choice);

switch(choice)

case 1:head-insert_head (head);

break;

case 2:insert_last(head);

break;

case 3:insert_after(head);

break;
}

New head is returned from function insert_head().

Hence we have to return the new head from the insert function to main

return head;

/* Insertion of node at first position*/

node *insert_head(node *head)

node *New,*temp;

New=get_node();

printf("\n Enter The element which you want to insert");

scanf("%d",& New →data);

if(head == NULL)

head=New;

else

temp-head;

New →next=temp;

head=New;

return head;

}
/*Insertion of node at last position*/

void insert_last (node *head)

No node in the linked list. i.e. when linked list is empty.

node *New,*temp;

New=get_node();

printf("\n Enter The element which you want to insert");

scanf("%d", &New→data);

if(head == NULL)

head=New;

else

:{

temp=head;

while(temp →next!= NULL)

temp-temp →next;

temp →next=New;

New →next = NULL;

/*Insertion of node at intermediate position */

void insert_after(node *head)

{
int key;

node *New,*temp;

New= get_node();

printf("\n Enter The element which you want to insert");

scanf("%d", &New →data);

if(head == NULL)

head=New;

else

printf("\n Enter The element after which you want to insert the node");

scanf("%d", &key);

temp=head;

do

if(temp →data==key)

New →next=temp →next;

temp →next=New;

return;

}
else

temp-temp→next;

}while(temp!= NULL);

node* get_prev(node *head, int val)

node *temp, *prev;

int flag;

temp = head;

if (temp==NULL)

return NULL;

flag = FALSE;

prev = NULL;

while (temp != NULL && !flag)

if (temp→data != val)

prev =temp;

temp = temp →next;

else
flag = TRUE;

if (flag )/*if flag is true*/

return prev;

else

return NULL;

/*

The dele function

Input:Address of the starting node of the list

Output:deletes the desired element from the list

Parameter Passing Method: call by value

Calls search(), get_prev()

*/

void dele(node **head)

node *temp, *prev;

int key;

temp = *head;

if (temp == NULL)

printf("\nThe list is empty\n");


getch();

clrscr();

return;

clrscr();

printf("\nEnter the Element you want to delete: ");

scanf("%d", &key);

temp=search(*head,key);

if (temp != NULL)

prev =get_prev(*head,key);

if (prev != NULL)

prev → next = temp →next;

free (temp);

Else

*head = temp →next;

free(temp);

printf("\nThe Element is deleted\n");


getch();

clrscr();

Output

Program to Perform Various operations on Linked List

1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 1

Enter the Element :10

Do you Want to enter more elements?(y/n)y

Enter the Element :20

Do you Want to enter more elements?(y/n)y

Enter the Element :30

Do you Want to enter more elements? (y/n)y

Enter the Element :40

Do you Want to enter more elements?(y/n)y

Enter the Element :50


Do you Want to enter more elements? (y/n)n

The Singly Linked List is created

Program to Perform Various operations on Linked List

1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 2

10 → 20 → 30 → 40 → 50 → NULL

Program to Perform Various operations on Linked List

1.Create

2. Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 3

Enter the element you want to search 40

The Element is present in the list

Program to Perform Various operations on Linked List


1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 4

1. Insert a node as a head node

2. Insert a node as a last node

3. Insert a node at intermediate position in the linked list

Enter the your choice for insertion of node 1

Enter The element which you want to insert 9

Program to Perform Various operations on Linked List

1.Create

2.Display

3.Search for an item

4.Insert an element in a list oil or

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 2

9 → 10 →20 → 30 → 40 → 50 → NULL

Program to Perform Various operations on Linked List


1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 4

1. Insert a node as a head node

2. Insert a node as a last node

3. Insert a node at intermediate position in the linked list

Enter the your choice for insertion of node 2

Enter The element which you want to insert 60

Program to Perform Various operations on Linked List

1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 2

9 → 10 →20 → 30 → 40 → 50 → 60 → NULL

Program to Perform Various operations on Linked List


1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 4

1. Insert a node as a head node

2. Insert a node as a last node

3. Insert a node at intermediate position in the linked list

Enter the your choice for insertion of node 3

Enter The element which you want to insert 31

Enter The element after which you want to insert the node 30

Program to Perform Various operations on Linked List

1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 2

9 → 10 → 20 → 30 → 31 → 40 → 50 → 60 → NULL
Program to Perform Various operations on Linked List

1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 5

Enter the Element you want to delete: 40

The Element is present in the list

The Element is deleted

Program to Perform Various operations on Linked List

1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 2

9 → 10 → 20 → 30 → 31 → 50 → 60 → NULL
4 More Programs on Linked List
In this section we will discuss various operations that can be performed on the
linked list. For the sake of convenience we will discuss only functions performing
these operations assuming that the list is already created.
The create() and display() functions will be common to all these operations.

Ex. 3.5.2: Counting the nodes of linked list.

Sol. :

void count()

node *temp;

int c=0;

temp=head;

if(temp== NULL)

printf("\n The list is empty");

return;

while(temp!= NULL)/*visiting each node */

c=c+1;/*c is for counting the node*/

temp-temp →next;

}
printf("\nThe Total number of nodes are: %d",c);

getch();

Ex. 3.5.3: Concatenation of two linked list

Sol. :

void concat(node *head1,node *head2)

node *temp1,*temp2;

temp1=head1;

temp2=head2;

while(temp1→next!= NULL)

temp1=temp1→next;/*searching end of first list*/

temp1→next=temp2;/* attaching head of the second list*/

printf("\n The concatenated list is ...\n");

temp1=head1;

while(temp1!= NULL)

{ /*printing the concatenated list*/

printf("%d",temp1→Data);

temp1=temp1→next;

}
Ex. 3.5.4 Algorithm to copy one singly list to another

Sol. :

void copy(node *head1,node *head2)

node *temp1,*temp2;

temp1=head1;/*first non empty linked list*/

head2=(node *)malloc(sizeof(node));

temp2=head2;/* second empty linked list*/

while(temp1!= NULL)/*while not end of first linked list*/

temp2 →data=temp1→data;/*copy the content to other node*/

temp2 →next = (node *)malloc(sizeof(node));

temp2=temp2 →next;/* moving one node ahead */

temp1=temp1 →next;

temp2=NULL;/*set the next pointer of last node of second list to NULL*/ printf("\
n The list is copied \n");

while(head2→next!= NULL)

/*printing the second list i.e. copied list*/

printf("%d",head2 →data);
head2-head2 →next;

Ex. 3.5.5 Recursive routine to erase a linked list (delete all node from the linked
list)

Sol.:

struct node *list_free(struct node *temp)

if(temp →next!= NULL)

temp1=temp→next;/*temp1 is declared globally*/

temp→next=NULL;

free(temp);

list_free(temp1);/*recursive call*/

temp=NULL;

return temp;

Ex. 3.5.6: Write a routine to merge two sorted linked lists. AU : Dec.-15 Marks 8
Sol. Consider two linked lists

node *merge(node *temp1,node *temp2)

node *prev_node1,*next_node2, *head;

if(temp1== NULL)

temp1=temp2;

head=temp2;

if(temp1→data<temp2→data)

head=temp1;

else

head=temp2;

while(temp1!= NULL && temp2!= NULL)

{ /*while data of 1st list is smaller then traverse*/


while((temp1→data<temp2→data) && (temp1!= NULL))

prev_node1=temp1; /* store prev node of Sl11 */

temp1=temp1→next;

if(temp1== NULL)

break;
/*when temp1's data>temp1 it will come out of while loop so adjust links with
temp1's prev node*/

prev_node1→next=temp2;

next_node2=temp2→next; /* store next node of Sl12*/

temp2→next=temp1;

temp1=temp2;

temp2=next_node2;

if(temp1==NULL&&temp2!= NULL) /* attach rem nodes of S112*/

while(temp2!= NULL)

prev_node1→next=temp2;

prev_node1=temp2;

temp2=temp2→next;

return head;

}
Ex. 3.5.7: Returning the position of an element X in a list L

Sol. The routine is as given below -

Return_position(node *head,int key)

/* head represents the starting node.of the List*/

/* key represents the element X in the list*/

int count=0;

node *temp;

temp=head;

while(temp→data!=key)&&(temp!= NULL)

temp-temp→next;

count=count+1;
}

if(temp→data==key)

return count;

else if(temp== NULL)

return -1; /* -1 indicates that the element X is not presentin the list*/

Ex. 3.5.8 Write a C function to display the sum of all the elements in a singly
linked list.

Sol. :

void sum(node *head)

node *temp;

int s=0;

temp=head;

while(temp!= NULL)

s=s+temp→data;

temp-temp→next;

printf("%d",s);

}
Ex. 3.5.9: Assume a singly linked list where each node contains student details
like name, rollno and percentage of marks. Write a "C" function COUNTO to
traverse the linked list and count how many students have obtained more than
60 %.

Sol. The data structure can be -

struct student

char *name;

int roll;

float marks;

struct student *next;

};

The COUNT function can be written as -

void COUNT(struct student *temp)

int count=0;

while(temp!= NULL)

if(temp→marks>60)

count++;

temp-temp→next;

}
printf("\n\n %d students have obtained more than 60 Percentage", count);

Ex. 3.5.10 : Write a C program to create a singly linked list and split it at the
middle. And make the second half as the first and vice versa, display the final
list.

Sol. :

typedef struct node

int data;

struct node *next;

}node;

void main()

node*head=NULL,*p, *q;

int n,i,x;

printf("\nEnter number of nodes:");

scanf("%d",&n);

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

printf("\nEnter element:");

scanf("%d", &x);
p=(node*)malloc(size of(node));

p→data=x;

p→next=NULL;

if(head == NULL)

head=q=p;

else {

q→next=p;

q=p;

p=q=head;

while(q next!= NULL)

p=p→next;

q=q→next;

if(q→next!= NULL)

q-q→next;

q→next-head;

head=p→next;

p→next=NULL:

for(p=head;p!= NULL;p=p→next)
printf("\n%d",p-data);

Ex. 3.5.11: Write a function that removes all duplicate elements from a linear
singly linked list.

Sol. :

void dupdelete(node *head)

node *p,*q,*r;

p=head;

q=p→next;

while(q!= NULL)

if(p→data!-q→data)

p=p→next;

q=q→next;

else

if(p→data==q-data)

p→next-q→next;

r=q;
q=q→next;

free(r);

return(head); }

Ex. 3.5.12: Suppose a linked list consists of numerical values. Write a function
for finding the maximum element of the list and the product of all the numbers
in the list.

Sol. i) To find the maximum element in the linked list :

void maxElement(node *root)

node *temp;

int Maxval;

temp=root;

Maxval-temp→data;

while(temp!= NULL)

{.

if(temp→data>Maxval)

Maxval-temp→data;

}
temp-temp→next;

printf("\n Maximum Value is: %d", Maxval);

ii) To find the product of all numbers in the linked list :

void Product(node *root)

node *temp;

int p=1;

temp=root;

while(temp!= NULL)

p=p*temp→data;

temp-temp→next;

printf("\n Product of all the elements: %d",p);

Review Questions

1. Write C code for singly liked list with insert, delete, display operations using
structure pointer.D AU: May-16, Marks 16

2. What are the ways to insert a note in linked list? Write an algorithm for
inserting a node before a given node in a linked list.AU: Dec.-18, Marks 6
3. Explain the insertion operation linked list. How nodes are inserted after a
specified node? AU: Dec.-19, Marks 13

Difference between Array and Linked Listed


The comparison between linked list and arrays is as shown below -

Ex. 3.6.1 Compare linked list with arrays with reference to the following
aspects :

i) Accessing any element randomly

ii) Insertion and deletion of an element

iii) Utilization of computer memory.


Sol. i) Accessing any element randomly: Using array, any element can be
accessed easily.

a) It takes constant time.

b) In linked list, we can access elements in sequence. So it is very difficult and


time consuming to access a element randomly.

ii) Insertion and deletion of an element :

a) Insertion and deletion of elements is time consuming.

b) In linked list, we can insert and delete elements easily and it is less time
consuming.

iii) Utilization of computer memory:

a) Array requires contiguous memory. First we have to declare array and compiler
allocates memory at declaration.

b) If we utilize less memory than allocated, then unutilized memory is


unnecessarily reserved for array. It can't be used by other programs. il sewed
noensgroo

c) If we want to add more elements than the actual size of array, it is not possible.

d) In linked list, memory is utilized efficiently. Memory is not pre-allocated like


static data structure. Memory is allocated as per the need. Memory is deallocated
when it is no longer needed.

Doubly Linked List


AU: Dec.-15, May-16, Marks 16

• Definition: The doubly linked list has two link fields. One link field is previous
pointer and the other link field is that next pointer.

• The typical structure of each node in doubly linked list is like this.
• C Structure

'C' structure of doubly linked list is as follows -

typedef struct node

int data;

struct node *prev;

struct node *next;

}dnode;

• Representation

The linked representation of a doubly linked list is

Thus the doubly linked list can traverse in both the directions, forward as well as
backwards.

Now, there may be one question in your mind that how do the empty doubly
circular linked lists look ? Here is the representation.
That means the prev and next pointers are pointing to the self node.

Ex. 3.7.1: Implementation of doubly linked list

/************************************************

Program to perform various operations

such as creation, insertion, deletion, search and display on doubly link lists.

******************************************/

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>

#define TRUE 1

#define FALSE 0

typedef struct DLL

int data;

struct DLL *next;

struct DLL *prev;

}node;
node *create();

/*

The main function

*/

void main()

/* Local declarations */

int choice, val;

char ans;

'node *head;

void display(node *);

node *search(node *,int);

node *insert(node *);

void dele(node **);

head = NULL;

do

clrscr();

printf("\nProgram to Perform Various operations on Linked List");

printf("\n1.Create");

printf("\n2.Display");

printf("\n3.Search for an item");


printf("\n4.Insert an element t in a list");

printf("\n5.Delete an element from list");

printf("\n6.Quit");

printf("\nEnter Your Choice ( 1–6) ");

scanf("%d", &choice);

switch( choice)

case 1:head = create();

break;

case 2:display(head);

break;

case 3:printf("Enter the element you want to search");

scanf("%d", &val);

search(head, val);

break;

case 4:head-insert(head);

break;

case 5:dele(&head);

break;

case 6:exit(0);

default:clrscr();

printf("Invalid Choice, Try again");


getch();

} while(choice != 6);

/*

The create function

*/

node* create()

node *temp, *New, *head;

int val, flag;

char ans='y';

node *get_node();

temp = NULL;

flag=TRUE; /* flag to indicate whether a new node is created for the first time or
not */

do

printf("\nEnter the Element :");

scanf("%d", &val);

/* allocate new node */

New = get_node();

if (New == NULL)
gell edt to

printf("\nMemory is not allocated");

New → data = val;

if (flag==TRUE) /* Executed only for the first time */

head=New;

temp=head; /*head is a first node in the DLL*/

flag = FALSE;

Else

/* temp keeps track of the most recently created node */

temp→next = New;

New→prev=temp;

temp = New;

printf("\n Do you Want to enter more elements? (y/n)"); med

ans=getche();

} while(ans=='y');

printf("\nThe Doubly Linked List is created\n");

getch();

clrscr();
return head;

node *get_node()

node *temp;

temp=(node *) malloc(sizeof(node) );

temp→next = NULL;

temp→prev=NULL;

return temp;

/*

The display function

Input:Address of the first node of the list

Output:Displays the Linked List

Parameter Passing Method : call by value

Called by main

*/

void display(node *head)

node *temp;

temp=head;

if (temp==NULL)
{

printf("\nThe list is empty\n");

getch();

clrscr();

return;

printf("\n List in Forward direction is ...\n");

while (temp != NULL)

printf("%d → ", temp→data );

temp= temp→next;

printf("NULL");

temp=head;

while(temp→next!= NULL)

temp-temp→next;//reaching at the last node

printf("\n List in Reverse direction is ...\n");

while (temp != NULL)

printf("%d→", temp→data );

temp=temp → prev;

}
printf("NULL");

getch();

clrscr();

/*

The search function

*/

node *search(node *head, int key)

node *temp;

int found;

temp = head;

if (temp==NULL)

printf("The Linked List is empty\n");

getch();

clrscr();

return NULL;

found=FALSE;

while (temp != NULL && found == FALSE)

{
if (temp→data != key)

temp=temp→next;

else

found = TRUE;

if (found ==TRUE)

printf("\nThe Element is present in the list\n");

getch();

return temp;

else

printf("The Element is not present in the list\n");

getch();

return NULL;

/*

The insert function

Input:Address of starting node of the list

Output:inserts an element into the list

*/
node *insert(node *head)

int choice;

node *insert_head(node *);

void insert_after(node *);

void insert_last(node *);

printf("\n 1. Insert a node as a head node");

printf("\n 2. Insert a node as a last node");

printf("\n 3. Insert a node at intermediate position in the linked list");

printf("\n Enter the your choice for insertion of node");

scanf("%d", &choice);

switch(choice)

case 1:head-insert head(head);

break;

case 2:insert_last(head);

break;

case 3:insert_after(head);

break;

return head;

}
/* Insertion of node at first position*/

node *insert head(node *head)

node *New,*temp;

New=get_node();

printf("\n Enter The element which you want to insert");

scanf("%d", &New→data);

if(head= NULL)

head=New;

else

temp=head;

New→next=temp;

temp→prev=New;

head=New;

return head;

/*Insertion of node at last position*/

void insert_last (node *head)

node *New,*temp;
New=get_node();

printf("\n Enter The element which you want to insert");

scanf("%d", &New→data);

if(head == NULL)

head=New;

else

temp=head;

while(temp→next!= NULL)

temp=temp→next;

temp→next=New;

New→prev=temp;

New→next = NULL;

/*Insertion of node at intermediate position*/

void insert_after(node *head)

int key;

node *New,*temp;

New= get_node();

printf("\n Enter The element which you want to insert"); (b-wal


scanf("%d", &New→data);

if(head == NULL)

head=New;

else

printf("\n Enter The element after which you want to insert the node");

scanf("%d", &key);

temp=head;

do

if(temp→data==key)

New→next=temp→next;

(temp→next)→prev=New;

temp→next=New;

New→prev=temp;

return;

else

temp=temp→next;
} while(temp!= NULL);

*/

The dele function

Input:Address of the starting node of the list

Output:deletes the desired element from the list

Parameter Passing Method: call by value

void dele(node **head)

node *temp, *prev_node;

int key;

temp = *head;

if (temp==NULL)

printf("\nThe list is empty\n");

getch();

clrscr();
return;

clrscr();

printf("\nEnter the Element you want to delete: ");

scanf("%d", &key);

temp = search(*head,key);

if (temp!= NULL)

prev_node = temp->prev;

if (prev_node != NULL)

prev_node->next = temp->next;

(temp->next)->prev = prev_node;

free (temp);

else

*head = temp->next;

(*head)->prev=NULL;

free(temp);

printf("\nThe Element is deleted\n");


getch();

clrscr();

Output

1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 1

Enter the Element :10

Do you Want to enter more elements?(y/n)y

Enter the Element :20

Do you Want to enter more elements?(y/n)y

Enter the Element :30

Do you Want to enter more elements?(y/n)y

Enter the Element :40

Do you Want to enter more elements?(y/n)n-

The Doubly Linked List is created

Program to Perform Various operations on Linked List


1. Create

2. Display

3. Search for an item

4. Insert an element in a list

5. Delete an element from list 6. Quit

Enter Your Choice (1-6) 2

List in Forward direction is ...

10-> 20 -> 30 -> 40-> NULL

List in Reverse direction is ...

40-> 30-> 20 -> 10-> NULL

Program to Perform Various operations on Linked List

1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 3

Enter the element you want to search 30

The Element is present in the list

Program to Perform Various operations on Linked List

1.Create
2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 4

1. Insert a node as a head node

2. Insert a node as a last node

3. Insert a node at intermediate position in the linked list

Enter the your choice for insertion of node 1

Enter The element which you want to insert 9

Program to Perform Various operations on Linked List

1.Create

2.Display

3.Search for an item

4.Insert an element in a list

5.Delete an element from list

6. Quit

Enter Your Choice (1-6) 2

List in Forward direction is ...

9-> 10 -> 20 -> 30-> 40 -> NULL

List in Reverse direction is ...


40 -> 30-> 20 -> 10 -> 9-> NULL

Program to Perform Various operations on Linked Lists at

1. Create

2. Display

3.Search for an item

4. Insert an element in a list

5. Delete an element from list

6. Quit

Enter Your Choice (1-6) 2

Enter the Element you want to delete: 20

The Element is present in the list

The Element is deleted

Program to Perform Various operations on Linked List

1.Create

2. Display

3. Search for an item

4. Insert an element in a list

5. Delete an element from list

6. Quit

Enter Your Choice (1-6) 2

List in Forward direction is ...

9-> 10 -> 30 -> 40 -> NULL


List in Reverse direction is ...

40 -> 30 -> 10 -> 9-> NULL

Logic explanation of DLL program

1. Creation of doubly linked list

Step 1: Initially one variable flag is taken whose value is initialized to TRUE. The
purpose of this flag is for making a check on creation of first node. After creating
first node reset flag (i.e. assign FALSE to flag)

Now, set flag = FALSE;

Step 2: If head node is created, we can further create a linked list by attaching the
subsequent nodes. Suppose, we want to insert a node with value 20 then

Step 3: If user wants to insert a node with a value say 30 then -


Continuing in this fashion doubly linked can be created.

2. Display of DLL

As each of DLL contains two link fields -

Previous link and next link. Hence we can display DLL in forward as well as in
reverse direction.

Suppose we have created a DLL as


As now temp becomes NULL, we will come out of the while loop. Hence as a
result forward display will be

10->20->30->40

Reverse Display

First of all we must reach at the last node by using while statement.

Finally temp will represent the last node


Now if we set temp = temp → prev, then temp becomes NULL, hence we will
come out of while loop. Hence we get the display as

40→30→20→10
3. Insertion of a node in DLL

There are three cases for insertion of a node

1)Insertion of a node at the beginning.

2) Insertion of a node at the end.

3) Insertion of a node at intermediate position.

Case 1: Inserting a node at the beginning

Suppose we want to insert a node with value 9 then

Case 2: Insertion of a node at the end suppose we want to insert a node with
value 40 then, first move temp pointer to the last node
Case 3: Inserting a node at the intermediate position

Suppose, we want to insert a node with value 22 after node with value 20, then
first search the node with value 20

4. Deletion of node

Suppose we want to delete a node with a value 20 then, first search this node, call
it as temp.
After setting these links, free (temp) in order to delete this node physically no
thus we get
1. Singly and Doubly Linked List Comparison

Review Questions

1. What is meant by doubly linked list? Write the functions to perform the
following operations in a doubly linked list.

i) Insert after a specified node ii) Delete the node at a given position iii) Display-
from the beginning to end.AU: Dec.-15, Marks 16

2. Illustrate the algorithms to implement the doubly linked list and perform all the
operations on the created list.AU May-16, Marks 16

Circular Linked List


AU: Dec.-18, Marks 6

• Definition: The Circular Linked List (CLL) is similar to singly linked list except
that the last node's next pointer points to first node.

• The circular linked list is as shown below -


• Various operations that can be performed on circular linked list are,

1. Creation of circular linked list.2. Insertion of a node in circular linked list.

3. Deletion of any node from linked list. 4. Display of circular linked list.

We will see each operation along with some example.

1. Creation of circular linked list

struct node *Create()

char ans;

int flag=1;

struct node *head,*New,*temp;

struct node *get_node();

clrscr();

do

New = get_node();

printf("\n\n\n\tEnter The Element\n");


scanf("%d", &New->data);

if(flag==1)/*flag for setting the starting node*/

head = New;

New->next=head; Creating a single node in linked list

flag=0;/*reset flag*/

Else /* find last node in list */

temp-head;

while (temp->next!= head)/*finding the last node */

temp-temp->next; /*temp is a last node */

temp->next=New;/* attaching the node*/

New->next-head; /*each time making the list circular*/

printf("\n Do you want to enter more nodes?");

ans=getch();

} while(ans =='y' || ans == 'Y');

return head;

/* function used while allocating memory for a node*/

struct node *get_node()


{

struct node *New;

New (node *) malloc(sizeof(struct node));

New->next = NULL;

return(New);/*created node is returned to calling function*/

Initially we will allocate memory for New node using a function get_node(). There
is one variable flag whose purpose is to check whether first node is created or not.
That means flag is 1 (set) then first node is not created. Therefore after creation of
first node we have to reset the flag (making flag = 0).

Initially,

Here variable head indicates starting node.

Now as flag = 0, we can further create the nodes and attach them as follows.

When we have taken element '20'


If we want to insert 30 then

If we want to insert 40 then


Thus we can create a circular linked list by inserting one no one more element 50.
It is as shown :

2. Display of circular linked list

void Display(struct node *head)

struct node *temp;

temp = head;

if(temp == NULL)

printf("\n Sorry,The List Is Empty\n");

else

do
{

printf("%d\t",temp->data);

temp = temp->next;

} while(temp != head);, The next node of last node is head node

getch();

3. Insertion of circular linked list

While inserting a node in the linked list, there are 3 cases -

a) Inserting a node as a head node

b) Inserting a node as a last node

c) Inserting a node at intermediate position

The functions for these cases is as given below -

struct node *insert_head(struct node *head)

struct node *get_node();

struct node *New,*temp;

New=get_node();

printf("\n Enter The element which you want to insert ");

scanf("%d",&New->data);

if(head == NULL)

head=New;
else

temp=head;

while(temp->next!=head)

temp=temp->next;

temp->next=New;

New->next = head;

head=New;

printf("\n The node is inserted!");

return head;

/*Insertion of node at last position*/

void insert_last(struct node *head)

struct node *New,*temp;

New=get_node();

printf("\n Enter The element which you want to insert ");

scanf("%d", &New->data);

if(head == NULL)

head= New;

else
{

temp=head;

while(temp->next!=head)

temp=temp->next;

temp->next=New;

New->next = head;

printf("\n The node is inserted!");

void insert_after(struct node *head)

int key;

struct node *New,*temp;

New= get_node();

printf("\n Enter The element which you want to insert ");

scanf("%d", &New->data);

if(head == NULL)

head=New;

else

{
printf("\n Enter The element after which you want to insert the node ");

scanf("%d", &key);

temp=head;

do

if(temp->data==key)

New->next-temp->next;

temp->next=New;

printf("\n The node is inserted"); D-ED-ED-ED

return;

else

temp-temp->next;

}while(templ=head);

Suppose linked list is already created as


If we want to insert a New node as a last node consider a linked list

If we want to insert an element 35 after node 30 then,


4. Deletion of any node

struct node *Delete(struct node *head)

int key;

struct node *temp, *temp1;

printf("\n Enter the element which is to be deleted");

scanf("%d", &key);

temp=head;

if(temp->data==key)/*If header node is to be deleted*/inil s botes svari sw seqque

temp1=temp->next; If a single node is present in the list and we want to delete it

if(temp1==temp)

temp=NULL;
head=temp;

printf("\n The node is deleted");

else

while(temp->next!=head)

temp-temp->next;/*searching for the last node*/

temp->next=temp1;

head=temp1;/*new head*/

printf("\n The node is deleted");

else

while(temp->next!=head) /* if intermediate node is to be deleted*/

if((temp->next)->data==key) The previous node of the node to be deleted is


searched. temp1 is the node to be deleted

temp1=temp->next;

temp->next-temp1->next;

temp1->next=NULL;
free(temp1);

printf("\n The node is deleted");

else

temp-temp->next;

return head;

Suppose we have created a linked list as,

If we want to delete temp → data i.e. node 10 then,

If we want to delete an intermediate node from a linked list which is given below
The linked list can be -

5. Searching a node from circular linked list

struct node *Search(node *head,int num)

struct node *temp;

temp=head;

while(temp->next!=head)
{

if(temp->data == num)

return temp; /*if node is found*/

else

temp=temp -> next

return NULL;

while searching a node from circular linked list we go on comparing the data field
of each node starting from the head node. If the node containing desired data is
found we return the address of that node to calling function.

Ex. 3.8.1: Implementation of circular linked list

/*********************************************************

Program To Perform The Various Operations On The Circular Linked List

*************************************************************/

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

struct node

int data;
struct node *next;

};

void main()

char ch;

int num,choice;

struct node *head, *New,*temp;

struct node *Create(void);

void Display(struct node *);

struct node *Insert(node *);

struct node *Delete(struct node *);

struct node *Search(struct node *,int);

head=NULL;

do

clrscr();

printf("\n Program For Circular Linked List\n");

printf(" 1.Insertion of any node\n\n");

printf(" 2. Display of Circular List\n\n");

printf(" 3. Insertion of a node in Circular List\n\n");

printf(" 4. Deletion of any node \n\n");

printf(" 5. Searching a Particular Element in The List\n\n");


printf(" 6.Exit");

printf("\n Enter Your Choice"); sino

scanf("%d", &choice);

switch(choice)

case 1 :head=Create();

break;

case 2 :Display(head);

break

case 3:head=Insert(head);

break;

case 4:head=Delete (head);

break;

case 5:printf("\n Enter The Element Which Is To Be Searched");

scanf("%d", &num);

temp Search(head,num);

if(temp!= NULL)

printf("\n The node is present");

else

printf("\n The node is not present");

break;

case 6:exit(0);
}

printf("\nDo you want to go to Main Menu?\n");

ch=getch();

} while(ch== 'y' || ch == 'Y');

struct node *Create()

char ans;

int flag=1;

struct node *head, *New, *temp;

struct node *get_node();

clrscr();

do

New = get_node();

printf("\n\n\n\tEnter The Element\n");

scanf("%d",&New->data);

if(flag==1) /*flag for setting the starting node*/

head =New;

New->next = head; /*the circular list of a single node*/

flag=0;/*reset flag*/
}

else /* find last node in list */

temp=head;

while (temp->next!= head)/*finding the last node*/)

temp=temp->next; /*temp is a last node*/

temp->next=New;

New->next-head; /*each time making the list circular*/

printf("\n Do you want to enter more nodes?");

ans=getch();

}while(ans=='y' || ans == 'Y');

return head;

struct node *get_node()

struct node *New;

New (node *) malloc(sizeof(struct node));

New->next = NULL;

return(New);/*created node is returned to calling function*/

void Display(struct node *head)


{

struct node *temp;

temp = head;

if(temp ==NULL)

printf("\n Sorry,The List Is Empty\n");

else

do

printf("%d\t",temp->data); boa pitiate ori prie rol ge*\_(==gs)

temp = temp->next;

} while(temp != head);/*Circular linked list*/

getch();

struct node *Insert(node *head)

int choice;

struct node *insert_head(node *);

void insert_after(struct node *);

void insert_last(struct node *);

printf("\n 1. Insert a node as a head node");


printf("\n 2. Insert a node as a last node");

printf("\n 3. Insert a node at intermediate position in the linked list");

printf("\n Enter your choice for insertion of node");

scanf("%d", &choice);

switch(choice)

case 1: head=insert_head(head);

break;

case 2: insert_last(head);

break;

case 3: insert_after(head);

break;

return head;

struct node *insert_head(struct node *head)

struct node *get_node();

struct node *New,*temp;

New=get_node();

printf("\n Enter The element which you want to insert ");

scanf("%d", &New->data);
if(head= NULL)

head=New;

else

temp=head;

while(temp->next!=head)

temp=temp->next;

temp->next=New;

New->next-head;

head=New;

printf("\n The node is inserted!");

return head; }

/*Insertion of node at last position*/

void insert_last(struct node *head)

struct node *New,*temp;

New=get_node();

printf("\n Enter The element which you want to insert ");

scanf("%d",&New->data);

if(head == NULL)

head=New;
else

temp=head;

while(temp->next!=head)

temp=temp->next;

temp->next=New;

New->next = head;

printf("\n The node is inserted!");

void insert_after(struct node *head)

int key;

struct node *New,*temp;

New= get_node();

printf("\n Enter The element which you want to insert ");

scanf("%d",&New->data);

if(head == NULL)

head=New;

else
{

printf("\n Enter The element after which you want to insert the node");

scanf("%d", &key);

temp=head;

do

if(temp->data==key)

New->next-temp->next;

temp->next=New;

printf("\n The node is inserted");

return;

else

temp=temp->next;

}while(temp!=head);

struct node *Search(node *head,int num)

struct node *temp;

temp=head;
while(temp->next!=head)

if(temp->data == num)

return temp;/*if node is found*/

else

temp-temp->next;

return NULL;

struct node *Delete(struct node *head)

int key;

struct node *temp, *temp1;

printf("\n Enter the element which is to be deleted");

scanf("%d", &key);

temp=head;

if(temp->data==key)/*If header node is to be deleted*/

temp1=temp->next;

if(temp1==temp)

/*if single node is present in circular linked listand we want to delete it*/

{
temp=NULL;

head=temp;

printf("\n The node is deleted");

else /*otherwise*/

while(temp->next!=head)

temp=temp->next;/*searching for the last node*/

temp->next=temp1;

head=temp1;/*new head*/

printf("\n The node is deleted");

else

while(temp->next!=head) /* if intermediate node is to be deleted*/

if((temp->next)->data==key)

temp1=temp->next;

temp->next=temp1->next;

temp1->next = NULL;
free(temp1);

printf("\n The node is deleted");

else

temp-temp->next;

return head;

Output

Program For Circular Linked List

1. Insertion of any node

2. Display of Circular List

3. Insertion of a node in Circular List o

4. Deletion of any node

5. Searching a Particular Element in The List

6. Exit

Enter Your Choice 1

Enter The Element

10

Do you want to enter more nodes?

Enter The Element


20

Do you want to enter more nodes?

Enter The Element

30

Do you want to enter more nodes?

Enter The Element

40

Do you want to enter more nodes?

Do you want to go to Main Menu?

Program For Circular Linked List

1. Insertion of any node

2. Display of Circular List

3. Insertion of a node in Circular List

4. Deletion of any node

5. Searching a Particular Element in The List

6. Exit

Enter Your Choice 2

10 20 30 40

Do you want to go to Main Menu?

Program For Circular Linked List

1.Insertion of any node

2. Display of Circular List


3. Insertion of a node in Circular List

4. Deletion of any node

5. Searching a Particular Element in The List

6.Exit

Enter Your Choice 3

1. Insert a node as a head node

2. Insert a node as a last node

3. Insert a node at intermediate position in the linked list

Enter your choice for insertion of node 3

Enter The element which you want to insert 33

Enter The element after which you want to insert the node 30

The node is inserted

OF

Do you want to go to Main Menu?

Program For Circular Linked List

1. Insertion of any node

2. Display of Circular List

3. Insertion of a node in Circular List

4. Deletion of any node

5. Searching a Particular Element in The List

6. Exit

Enter Your Choice 2


10 20 30 33 40

Program For Circular Linked List

1. Insertion of any node

2. Display of Circular List

3. Insertion of a node in Circular List

4. Deletion of any node

5. Searching a Particular Element in The List

6. Exit

Enter Your Choice 4

Enter the element which is to be deleted 20

The node is deleted

Do you want to go to Main Menu?

Program For Circular Linked Lis

1. Insertion of any node

2. Display of Circular List

3. Insertion of a node in Circular List

4. Deletion of any node

5. Searching a Particular Element in The List

6. Exit

Enter Your Choice 2

10 30 33 40

Do you want to go to Main Menu?


Program For Circular Linked List

1. Insertion of any node

2. Display of Circular List

3. Insertion of a node in Circular Lister Icimonyloq orli gnithsesi

4. Deletion of any node

5. Searching a Particular Element in The List

6. Exit

Enter Your Choice 5

Enter The Element Which Is To Be Searched 30

The node is present

Do you want to go to Main Menu?

Program For Circular Linked List

1. Insertion of any node

2. Display of Circular List

3. Insertion of a node in Circular List

4. Deletion of any node

5. Searching a Particular Element in The List

6. Exit

Enter Your Choice 5

Enter The Element Which Is To Be Searched 101

The node is not present

Do you want to go to Main Menu?


Program For Circular Linked List

1. Insertion of any node.

2. Display of Circular List

3. Insertion of a node in Circular List

4. Deletion of any node

5. Searching a Particular Element in The List

6. Exit

Enter Your Choice 6

Advantages of Circular Linked List over Singly Linked List

In circular linked list the next pointer of last node points to the head node. Hence
we can move from last node to the head node of the list very efficiently. Hence
accessing of any node is much faster than singly linked list.

Applications of circular list :

1) The circular list is used to create the linked lists in which the last node points to
the first node.

2) In round robin method the circular linked list is used.

3) The circular linked list is used in solving Josephus problem.

4) For representing the polynomial the circular linked list.

Review Question

1. Write a procedure to deleting the last node from a circular linked list. AU:
Dec.-18, Marks 6

Applications of Linked Lists


AU: Dec.-19, Marks 13
The linked list is a data structure which makes use of dynamic memory. Hence it is
possible to handle the list of any desired length using the linked list. Various
applications of linked list are -

1. The linked list is used for performing polynomial operations such as addition,
multiplication evaluation and so on.

2. The linked list is used for handling the set operations.

3. The stack data structure can be implemented using linked list.

4. The queue data structure can be implemented using linked list.

Review Question

1. What are the applications of linked list in dynamic storage management? AU:
Dec.-19, Marks 13

Two Marks Questions with Answers

Q. 1 Explain the term data structure.

Ans. : The data structure can be defined as the collection of elements and all the
possible operations which are required for those set of elements. Formally data
structure can be defined as a data structure is a set of domains D, a set of functions
F, and a set of axioms A. This triple (D, F, A) denotes the data structure d.

Q. 2 What do you mean by non linear data structure? Give examples.

Ans. : The non linear data structure is the kind of data structure in which the data
may be arranged in hierarchical fashion. For example - Trees and graphs.

Q. 3 What do you mean by linear data structure ? Give example.


Ans. : The linear data structure is a kind of data structure in which the data is
linearly arranged. For example - Stacks, queues, linked list.

Q. 4 Enlist the various operations that can be performed on data structure.

Ans. : Various operations that can be performed on the data structure are -

1. Create

2. Insertion of element

3. Deletion of element

4. Searching for the desired element

5. Sorting the elements in the data structure.

6. Reversing the list of elements.

Q. 5 What is abstract data type? What are all not concerned in an ADT ? AU:
Dec.-19

Ans. : The abstract data type is a triple of D i.e. set of axioms, F-set of functions
and A- Axioms in which only what is to be done is mentioned but how is to be
done is not mentioned. Thus ADT is not concerned with implementation details.

Q. 6. List out the areas in which data structures are applied extensively.

Ans. : Following are the areas in which the data structures are applied extensively.

1. Operating system - The data structures like priority queues are used for
scheduling the jobs in the operating system.

2. Compiler design - The tree data structure is used in parsing the source program.
inil vlduob Stack data structure is used in handling the recursive calls.
3. Database management system The file data structure is used in database
management systems. Sorting and searching techniques can be applied on these
data in the file.

4. Numerical analysis package - The array is used to perform the numerical


analysis ble on the given set of data.

5. Graphics - The array and linked list are useful in graphics applications.

6. Artificial intelligence - The graph and trees are used for the applications like
building expression trees, game playing.

7. Networking - The graph is used for finding the shortest path length between any
two computers that are connected in a LAN.

8. Simulation - The queue is used for simulation and modeling.

Q. 7 What is a linked list ? 10 AU: Dec.-19

Ans. : A linked list is a set of nodes where each node has two fields 'data' and
'link'. The data field is used to store actual piece of information and link field is
used to store address of next node.

Q. 8 Write down the steps to modify a node in linked lists.

Ans. :

1. Enter the position of the node which is to be modified.

2. Enter the new value for the node to be modified.

3. Search the corresponding node in the linked list.

4. Replace the original value of that node by a new value.

5. Display the message as "The node is modified".


Q. 9 State the properties of LIST abstract data type with suitable example.

Ans. Various properties of LIST abstract data type are –

1. It is linear data structure in which the elements are arranged adjacent to each
other. elinteb neilstrsms.

2. It allows to store single variable polynomial.

3. If the LIST is implemented using dynamic memory then it is called linked list.

Example of LIST are - Stacks, Queues, Linked List.

Q. 10 State the advantages of circular lists over doubly linked list.

Ans. In circular list the next pointer of last node points to head node, whereas in
doubly linked list each node has two pointers: One previous pointer and another is
next pointer. The main advantage of circular list over doubly linked list is that with
the help of single pointer field we can access head node quickly. Hence some
amount of memory get saved because in circular list only one pointer field is
reserved.

Q. 11 What are the advantages of doubly linked list over singly linked list?

Ans. : The doubly linked list has two pointer fields. One field is previous link
field and another is next link field.

Because of these two pointer fields we can access any node efficiently whereas in
singly linked list only one pointer field is there which stores forward pointer,
which makes accessing of any node difficult one.

Q. 12 What is the advantage of linked list over arrays ? AU: May-19


Ans. : The linked list makes use of the dynamic memory allocation. Hence the
user can allocate or de allocate the memory as per his requirements. On the other
hand, the array makes use of the static memory location. Hence there are chances
of wastage of the memory or shortage of memory for allocation.

Q. 13 What is circular linked list ? AU: Dec.-14, May-16

Ans. The circular linked list is a kind of linked list in which the last node is
connected to the first node or head node of the linked list.

Refer section 3.6.

Q. 14 What is the basic purpose of header of the linked list?

Ans. : The header node is the very first node of the linked list. Sometimes a
dummy value such as -999 is stored in the data field of header node. Refer Fig.
3.10.1.

This node is useful for getting the starting address of the linked list. As there is
only a forward link present in the linked list, for accessing the entire linked list it is
necessary to obtain the starting address of the linked list.

Q. 15 What is advantage of an ADT ? AU: May-14, Dec.-18

Ans. : The advantages of ADT are

1. Change: The implementation of the ADT can be changed without making


changes bruin the client program that uses the ADT.
2. Understandability: ADT specifies what is to be done and does not specify the
implementation details. Hence code becomes easy to understand due to ADT.

3. Reusability: The ADT can be reused by some program in future.

4. Flexibility: Different implementations are possible for the same ADT.

Q. 16 Should arrays of linked lists be used for the following type of applications.
Justify your Answer.

a) Many search operations in sorted list.

b) Many search operations in unsorted list. AU: May-14

Ans. :

a) If the list is sorted then using linked list the desired element can be searched,
simply by moving forward using 'next' pointer.

b) If a list is not sorted then using arrays the desired element can be searched. The
arrays facilitates the access to random element.

Q. 17 What are abstract data type? AU: Dec.-14

OR Define ADT AU: May-15

Ans. : Refer Q. 5.

Q. 18 What is static linked list? State any two applications of it. AU: May-15

Ans. The linked list structure which can be represented using arrays is called static
linked list.

1. It is easy to implement, hence for creation of small databases, it is useful.


2. The searching of any record is efficient, hence the applications in which the
record need to be searched quickly, the static linked lists are used.

Q. 19 Write syntax of calloc() and relloc() and mention its applications in the
linked list AU: May-15

Ans. : calloc() is for allocating the required amount of memory. The syntax is void
*calloc(size_t nitems, size_t size)

This function returns the pointer to the allocated memory. The calloc function is
just similar to malloc but it initializes the allocated memory to zero and malloc
does not.

The realloc() function modifies allocated memory size by malloc() and calloc()
functions to new size. The syntax is

void *realloc (void *ptr, size_t size)

If insufficient memory exists then to expand the memory block, realloc() is used.

Q. 20 What are the disadvantages of linked list over arrays. AU: Dec.-18

Ans. 1) In linked list, we can access elements in sequence. So it is very difficult


and time consuming to access element randomly.

2) Some amount of memory gets wasted in storing the next node's address in each
nodes.
Linear Data Structures Stacks and Queues

Unit III
Chapter 4
Linear Data Structures Stacks and Queues

Syllabus

Stack ADT - Implementation of Stack - Applications - Queue ADT - Priority


Queues - Queue Implementation - Applications.

Contents

Part I: Stacks

4.1 Concept of Stack

4.2 Stack ADT

4.3 Implementation of Stack

4.4 Applications of Stack..... May-15,........ Marks 12

4.5 Expression

4.6 Infix to Postfix Conversion .... May-14,16, Dec.-16,..... Marks 16


4.7 Evaluation of Postfix Expressions.... Dec.-15,18,..... Marks 16

Part II: Queues

4.8 Concept of Queue

4.9 Queue ADT

4.10 Queue Implementation....May-15, .....Marks 16

4.11 Priority Queues......Dec.-19, .......Marks 15

4.12 Applications of Queue.......Dec.-19,...Marks 15

4.13 Two Marks Questions with Answers

Concept of Stack
• Definition :

A stack is an ordered list in which all insertions and deletions are made at one end,
called the top. If we made at on have to make stack of elements 10, 20, 30, 40, 50,
60 then 10 will be the bottommost element and 60 will be the topmost element in
the stack. A stack is shown in Fig. 4.1.1.

• Example
The typical example can be a stack of coins. The coins can be arranged one on
another, when we add a new coin it is always placed on the previous coin and
while removing the coin the recently placed coin can be removed. The example
resembles the concept of stack exactly.

Stack ADT
• Stack is a data structure which posses LIFO i.e. Last In First Out property.

• The abstract data type for stack can be as given below.

AbstractDataType stack

Instances: Stack is a collection of elements in which insertion and deletion of


elements is done by one end called top.

Preconditions:

1. Stfull (): This condition indicates whether the stack is full or not. If the stack is
full then we cannot insert the elements in the stack.

2. Stempty(): This condition indicates whether the stack is empty or not. If the
stack is empty then we cannot pop or remove any element from the stack.

Operations:

1. Push: By this operation one can push elements onto the stack. Before
performing push we must check stfull () condition.

2. Pop: By this operation one can remove the elements from stack. Before popping
the elements from stack we should check stempty() condition.

Implementation of Stack
• A stack is a special case of an ordered list, i.e. it is a ordered list with some
restrictions on the way in which we perform various operations on a list.

• We need an integer variable top which will keep track of the top of the stack as
more and more elements are inserted into and deleted from the stack.

• The declarations in C are as follows.

• Declaration 1: Using Arrays

#define size 100

int stack[size], top = -1;

In the above declaration stack is nothing but an array of integers. And most recent
index of that array will act as a top.

The stack is of the size 100. As we insert the numbers, the top will get
incremented. The elements will be placed from oth position in the stack. At the
most we can store 100 elements in the stack, so at the most last element can be
at (size - 1) position, i.e. at index 99.

• Declaration 2: Using Structure

#define size 10

struct stack {

int s[size];

int top; 2 ...

}st;
In the above declaration stack is declared as a structure.

Now compare declaration 1 and 2. Both are for stack declaration only. But the
second declaration will always preferred. Why? Because in the second declaration
we have used a structure for stack elements and top. By this we are binding or co-
relating top variable with stack elements. Thus top and stack are associated with
each other by putting them together in a structure. The stack can be passed to the
function by simply passing the structure variable.

We will make use of the second method of representing the stack in our program.

• The stack can also be used in the databases.

• For example if we want to store marks of all the students of forth semester we
can declare a structure of stack as follows

# define size 60

typedef struct student

int roll.no;

char name[30];
float marks;

}stud;

stud S1[size];

int top = -1;

• The above stack will look as shown in Fig. 4.3.3:

• Thus we can store the data about whole class in our stack.

• The above declaration means creation of stack.

• Hence we will write only push and pop function to implement the stack.

• Before pushing or popping we should check whether stack is empty or full.

1. Stack Empty Operation

• Initially stack is empty. At that time the top should be initialized to -1 or 0. 10


• If we set top to - 1 initially then the stack will contain the elements from oth
position and if we set top to 0 initially, the elements will be stored from
1st position, in the stack.

• Elements may be pushed onto the stack and there may be a case that all the
elements are removed from the stack. Then the stack becomes empty.

• Thus whenever top reaches to - 1 we can say the stack is empty.

int stempty()

if(st.top==-1)

return 1;

else

return 0;

Key Point If top=-1 means stack empty.


2. Stack Full Operation
• In the representation of stack using arrays, size of array means size of stack.

• As we go on inserting the elements the stack gets filled with the elements.

• So it is necessary before inserting the elements to check whether the stack is


full or not.

• Stack full condition is achieved when stack reaches to maximum size of array.

int stfull()

if(st.top>=size-1)

return 1;

else

return 0;

Thus stfull is a Boolean function if stack is full it returns 1 otherwise it returns 0.

Key Point: If top > = size means stack is full.


3. The 'Push' and 'Pop' Functions
• We will now discuss the two important functions which are carried out on a
stack.

• push is a function which inserts new element at the top of the stack. The
function is as follows.

void push(int item)

st.top++; /* top pointer is set to next location */

st.s[st.top] = item; /* placing the element at that location */

• Note that the push function takes the parameter item which is actually the
element which we want to insert into the stack - means we are pushing g the
element onto the stack.
• In the function we have checked whether the stack is full or not, if the stack is
not full then only the insertion of the element can be achieved by means of push
operation.

• Now let us discuss the operation pop, which deletes the element at the top of
the stack. The function pop is as given below -

• Note that always top element can be deleted.

int pop()

int item;

item = st.s[st.top];

st.top--;

return(item);

• In the choice of pop - it invokes the function 'stempty' to determine whether


the stack is empty or not. If it is empty, then the function generates an error as
stack underflow! If not, then pop function returns the element which is at the top
of the stack.

• The value at the top is stored in some variable as item and it then decrements
the value of the top, which now points to the element which is just under the
element being retrieved from the stack.

• Finally it returns the value of the element stored in the variable item. Note that
this is what called as logical deletion and not a physical deletion, i.e. even when
we decrement the top, the element just retrieved from the stack remains there
itself, but it no longer belongs to the stack. Any subsequent push will overwrite
this element.

• Push operation can be shown by following Fig. 4.3.6.


• The pop operation can be shown by following Fig. 4.3.7.

Key Point If stack is empty we cannot pop and if stack is full we cannot push any
element.
4. Implementation

Ex. 4.3.1: Implementing stack using Arrays.

/*************************************************************

Program for implementing a stack using arrays. It involves various operations such
as push,pop,stack empty, stack full and display.

*************************************************************/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#define size 5

/* stack structure*/

struct stack {

int s[size];

int top;

}st;

int stfull()

if(st.top>=size-1)

return 1;

else
return 0;

void push(int item)

st.top++;

st.s[st.top] = item;

int stempty()

if(st.top ==-1)

else

return 1;

else

return 0;

int pop()

int item;

item=st.s[st.top];

st.top--;

return(item);

}
/*

The display Function

Input:none

Output:none-displays the contents of the stack

Called By:main

Calls:none

*/

void display()

int i;

if(stempty())

printf("\n Stack Is Empty!");

else

for(i=st.top;i>=0;i--) Displaying stack from top to bottom

printf("\n%d", st.s[i]);

void main(void)

int item,choice;

char ans;
st.top=-1;

clrscr();

printf("\n\t\t Implementation Of Stack");

do

printf("\n Main Menu");

printf("\n1.Push\n2.Pop\n3.Display\n4.exit");

printf("\n Enter Your Choice");

scanf("%d", &choice);

switch(choice)

case 1:printf("\n Enter The item to be pushed");

scanf("%d", &item);

if(stfull()) Before pushing we should check stack full condition

printf("\n Stack is Full!");

else

push(item);

break;

case 2:if(stempty()) Before popping we should check stack empty condition

printf("\n Empty stack!Underflow !!");

else

{
item=pop();

printf("\n The popped element is %d",item);

break;

case 3:display();

break;

case 4:exit(0);

printf("\n Do You want To Continue?");

ans=getche();

} while(ans == 'Y' || ans =='y');

getch();

/******End Of Program****************?

Output

Implementation Of Stack

Main Menu

1. Push

2. Pop

3. Display

4. exit

Enter Your Choice1


Enter The item to be pushed 10

Do You Want To Continue?y

Main Menu

1. Push

2. Pop

3. Display

4. exit

Enter Your Choice 1

Enter The item to be pushed 20

Do You want To Continue?y

Main Menu

1. Push

2. Pop

3. Display

4. exit

Enter Your Choice3

20

10

Do You Want To Continue?y

Main Menu

1. Push

2. Pop
3. Display

4. exit

Enter Your Choice2

The popped element is 20

Do You want To Continue?y

Main Menu

1. Push

2. Pop

3. Display

4. exit

Enter Your Choice 2

The popped element is 10

Do You want To Continue?y

Main Menu

1. Push

2. Pop

3. Display

4. exit

Enter Your Choice

Empty stack!Underflow !!

Do You want To Continue?n


Applications of Stack
AU: May-15, Marks 12

Various applications of stack are,

1. Expression conversion

2. Expression evaluation

3. Parsing well formed parenthesis

4. Decimal to binary conversion

5. Reversing a string

6. Storing function calls

Ex. 4.4.1: Write a C program that checks if expression is correctly parenthesized


using stack.AU: May-15, Marks

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#define size 5

/* stack structure*/

struct stack {

char s[size];

int top; }st;

void push(char item)

{
st.top++;

st.s[st.top] = item;

int stempty()

if(st.top==-1)

return 1;

else

return 0;

char pop()

char item;

item=st.s[st.top];

st.top--;

return(item);

void main(void)

char item;

char ans,bracket[10];

int i; 80
st.top=-1;

clrscr();

printf("\n\t\t Enter The expression and put $ at the end");

scanf("%s", bracket);

i=0;

if(bracket[i]==')')

printf("\n The expression is invalid");

else

do

while(bracket[i]=='')

push(bracket[i]);

i++;

}while(bracket[i]==')')

item=pop();

i++;

} while(bracket[i]!='$');
if(!stempty())

printf("\n The expression is invalid");

else

printf("\n The expression has well formed parenthesis");

getch();

Output

Enter The expression and put $ at the end(()())$

The expression has well formed parenthesis

Enter The expression and put $ at the end())$

The expression is invalid

Expression
Expression is a string of operands and operators. Operands are some numeric
values and operators are of two types: Unary operators and Binary operators.
Unary operators are '+' and '-' and binary operators are '+', '-', '*', '/' and exponential.
In general, there are three types of expressions:

1. Infix expression 2. Postfix expression 3. Prefix expression.

One of the application of stack is conversion of expression. First of all, let us see
these expressions with the help of examples :

1. Infix Expression :

In this type of expressions the arrangement of operands and operator is as follows:

Infix expression = operand1 operator operand2


For example

1. (a+b)

2 (a+b) * (c-d)

3. (a+b/e) * (d+f).

Parenthesis can be used in these expressions. Infix expression are the most natural
way of representing the expressions.

2. Postfix Expression :

In this type of expressions the arrangement of operands and operator is as follows:

Postfix expression = operand1 operand2 operator

For example

1. ab+

2. ab + cd - *

3. ab+e/df + *

In postfix expression there is no parenthesis used. All the corresponding operands


come first and then operator can be placed.

3. Prefix Expression :

In prefix expression the arrangement of operands and operators is as follows

Prefix expression = operator operand1 operand2

For example

1. + ab

2. *+ ab - cd

3. */ +abe + df
In prefix expression, there is no parenthesis used. All the corresponding operators
come first and then operands are arranged.

To evaluate infix expression, we need the precedence and associativity of the


operators. And which is really a complex task. But in prefix and postfix
expressions corresponding operators are with their respective operands. But these
algorithms strongly recommend the use of stack.

Let us now, discuss the conversion procedures of these expression.

Infix to Postfix Conversion


AU: May-14,16, Dec.-16, Marks 16

Read an expression from left to right each character one by one

1. If an operand is encountered then add it to postfix array.

2. If '(' is read, then simply push it onto the stack. Because the ( has highest priority
when read as an input.

3. If ')' is reads, then pop all the operands until ( is read. Discard (. Store the
popped characters in the postfix array.

4. If operator is read then,

1. If instack operator has greatest precedence (or equal to) over the incoming
operator then pop the operator and add it to postfix expression. Repeat this step
until we get the instack operator of higher priority than the current incoming
operator. Finally push the incoming operator onto the stack

2. Else push the operator.

5. The postfix expression present in postfix array is then printed.

The priorities of different operators when they are in stack will be called instack
operators and the priorities of different operator when they are read from input
will be called as incoming priorities. These priorities are as given below -
Note that higher value represents higher priority.

Ex. 4.6.1: A*B + C $. Obtain postfix expression.

Sol. :
Ex. 4.6.2: Obtain the postfix expression for (A+B)*(C-D)$.

Sol. :
When closing parenthesis comes pop everything and print except '("

So finally the converted expression is


AB+CD-*

Ex. 4.6.3: Write an algorithm to convert an infix to postfix expression Trace the
algorithm to convert the infix expression "(a+b)*c/d+elf" to a postifx
expression. Explain the need for infix and postfix expressions.AU: May-14,
Marks 16

Sol. :
The infix expressions are used in mathematical expressions and postfix expressions
are used in compilers for checking the syntax of an expression. The postfix
expressions are also used in evaluating the expressions.
Ex. 4.6.4: Convert the following infix expression to the postfix expression. Show
stack traces. (i) A/B$C+D*E/F-G+H (ii) (A+B) *D+E/(F+G*D)+C.

Sol.: (i)
(ii)
Ex. 4.6.5: Show the simulation using stack for the following expression to
convert infix to postfix: p q + (r-s/t) AU: May-16, Marks 6

Sol. Consider expression p*q+(r-s/t)


The postfix expression is pq * rst / - +

Ex. 4.6.6 Simulate the conversion of infix to postfix expression using stack for
the following expression : 3-(4/2)+(1*5)+6 AU: Dec.-16, Marks 8

Sol. :
The equivalent postfix expression is 342/-15*+6+
Ex. 4.6.7 Conversion of infix expression to postfix using C.

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#define SIZE 20

char stk[SIZE];

char in[SIZE],post[SIZE];

int top=-1;

void push(char item)

top++;

stk[top] = item;

char pop()

char temp;

temp = stk[top];

top--;

return temp;

int stempty()

{
if(top==-1)

return 1;

else

return 0;

void inTopost();

int precedence(char);

int main()

printf("Enter the infix expression: ");

gets(in);

inTopost();

return 0;

int precedence (char ch)//highest num-highest priority

switch(ch)

Case '^ ': return 3;

case '/':

case '*':

return 2;
case '+':

case '-':

return 1;

default: return 0;

void inTopost()

int i,j=0;

char ch,next_ch;

for(i=0;i<strlen(in);i++)

ch= in[i];

switch(ch)

case '(': push(ch);

break;

case ')':while((next_ch=pop())!='()

post [j++] = next_ch;

break;

case '+':

case '-':
case '*':

case '/':

case '^ ':while(!stempty()&&(precedence(stk[top])>=precedence(ch)))

vns be post[j++]=pop(); r

push(ch);//else partn

break;

default:post [j++]=ch;//if operand is encountered simply add it to postfix

while(!stempty())

post[j++]=pop();

post [j]='\0';

for(i=0;i<strlen(post);i++)

printf("%c",post[i]);

Output

Enter the infix expression: (a+b)*(c-d)

ab+cd-*

Evaluation of Postfix Expressions


AU: Dec.-15,18, Marks 16

As we have seen how to convert given infix expression to postfix form. It's the
time to learn an evaluation of postfix expression. Again use of stack is necessary in
postfix expression evaluation. But here we will use the stack for storing operands
rather than operators. Operands are taken as numeric values. Let us see an
algorithm first,

Algorithm for evaluation of postfix.

1. Read the postfix expression from left to right.

2. If the input symbol read is an operand then push it on to the stack.

3. If the operator is read POP two operands and perform arithmetic operations if
operator is

+ then result = operand 1 + operand 2

- then result = operand 1-operand 2

* then result = operand 1 * operand 2

/ then result = operand 1 / operand 2

4. Push the result onto the stack.

5. Repeat steps 1-4 till the postfix expression is not over.

Ex. 4.7.1: Evaluate given postfix expression.

ABC-BA + C $ - for A = 1, B = 2 and C = 3

Sol. Now as per the algorithm of postfix expression evaluation, we scan the input
from left to right. If operand comes we push them onto the stack and if we read any
operator, we must pop two operands and perform the operation using that operator.
Here $ is taken as exponential operator.
Now since there is no further input we should pop the contents of stack and print it
as a result of evaluation.

Hence output will be - 27.

Ex. 4.7.2 : Program for evaluation of postfix expression.

Sol. :

/******************************************************************

Program to evaluate a given postfix expression.

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

#include <conio.h>

#include <stdlib.h>

#include <string.h>

#include <math.h>

#define size 80

/*declaration of stack data structure*/

struct stack

double s[size];

int top;

}st;

void main()
{

char exp[size];

int len;

double Result;

double post();

clrscr();

printf("Enter the postfix Expression\n");

scanf("%s", exp);

len = strlen(exp);

exp[len] = '$'; /* Append $ at the end as a endmarker*/

Result = post(exp);

printf("The Value of the expression is %f\n", Result);

getch();

exit(0);

double post( char exp[])

char ch,*type;

double result, val, op1, op2;

void push(double);

double pop();

int i;
st.top = 0;

i=0;

ch = exp[i];

while (ch != '$' )

if (ch >= '0' && ch <= '9')

type="operand";

else if (ch== '+'|| ch == '|| ch == "*'|| ch == '/' || ch == '^')

type="operator";

if(strcmp(type, "operand")==0)/*if the character is operand*/

val=ch- 48;

push(val); The characters '0', '1', ... '9' will be converted to their values, so that they
will perform arithmatic operation

else

if (strcmp(type, "operator")==0)/*if it is operator*/

op2 = pop();Popping two operands to perform arithmatic operation

op1 = pop();

switch(ch)

}
case '+' result = op1 + op2;

break;

case '-': result = op1 - op2;

break;

case '*' : result = op1 * op2;

break;

case '/' result = op1 / op2;

break;

case '^': result =pow(op1,op2);

break;

}/* switch */

push(result); Finally result will be pushed onto the stack

i++;

ch=exp[i];

} /* while */

result = pop(); /*pop the result*/

return(result);

void push(double val)

if (st.top+1 >= size)


printf("\nStack is Full\n");

st.top++;

st.s[st.top] = val;

double pop()

double val;

if(st.top == -1)

printf("\nStack is Empty\n");

val = st.s[st.top];

st.top--;

return(val);

Output

Enter the postfix Expression

12+34*+

The Value of the expression is 15.0000

Logic of evaluation of postfix expression [Refer the above program]

Let us take some example of postfix expression and try to evaluate it 123+*

Step 1: Assume the array exp[] contains the input


The $ symbol is used as an end marker. Read from first element of the array if it is
operand push it onto the stack.

Step 2: If the operator isv read pop two operands

Again pop two operands and perform the operation.

Step 4:

At this point the stack is empty and the input is read as $. So here stop the
evaluation procedure and return the result = 5.

Ex. 4.7.3: Write an algorithm to convert a infix expression into an postfix


expression. Consider following arithmatic expression in postfix notation: 752 +
* 415 -/-
i) Find the value of the expression.

ii) Find the equivalent prefix form of above expression.

Sol. : Algorithm to convert infix expression to postfix - Refer section 4.6.

i) Let, the given postfix expression be -

752 + * 415 -/-


ii) Let 752 + * 415 -/-

Step 1: Read expression from left to right. Go on pushing operands onto the stack.
When operator is read, pop two operands and form prefix expression push it onto
the stack.
Ex. 4.7.4 : Evaluate the following expression using stack 5 6 2 + * 84/- AU:
Dec.-15, Marks 2

Sol. :

The result of evaluation is 38.


Ex. 4.7.5 : Write the procedure to convert the infix expression to postfix
expression and the expression steps involved in evaluating the postfix
expression. Convert A-(B/C+(D%E*F)/F)*H to postfix form. Evaluate the given
postfix expression 9 3 4 * 8 +4 / -

AU: Dec.-18, Marks 7

Sol. : Procedure to convert infix to postfix: Refer section 4.6.

Conversion of A-(B/C+(D%E*F)/F)*H
Postfix Form : A B C / DE F *% F/ + H * -

The result of evaluation is 4

Review Question

1. Discuss any two applications of stack with relevant examples. AU: Dec.-15,
Marks 16

Part II: Queues

Concept of Queue
• Definition :

The queue can be formally defined as ordered collection of elements that has two
ends named as front and rear. From the front end one can delete the elements
and from the rear end one can insert the elements.
• For Example :

The typical example can be a queue of people who are waiting for a city bus at the
bus stop. Any new person is joining at one end of the queue, you can call it as the
rear end. When the bus arrives the person at the other end first enters in the bus.
You can call it as the front end of the queue.

Following Fig. 4.8.1 represents the queue of few elements

Queue ADT
AbstractData Type Queue

Instances: The queue is a collection of elements in which the element can be


inserted by one end called rear and elements can be deleted by other end called
front.

Operations :

1. Insert : The insertion of the element in the queue is done by the end called rear.
Before the insertion of the element in the queue it is checked whether or not the
queue is full.

2. Delete: The deletion of the element from the queue is done by the end called
front. Before performing the delete operation it checked whether the queue is
empty or not.

Queue Implementation
AU: May-15, Marks 16
• Queue is nothing but the collection of items. Both the ends of the queue are
having their own functionality.

• The Queue is also called as FIFO i.e. a First In First Out data structure.

• All the elements in the queue are stored sequentially.

• Various operations on the queue are -

1.Queue overflow.

2.Insertion of the element into the queue.

3.Queue underflow.

4. Deletion of the element from the queue.

5.Display of the queue.

Let us see each operation one by one

• 'C' representation of queue.

struct queue

int que [size];

int front;

int rear;

}Q;

1. Insertion of element into the queue

The insertion of any element in the queue will always take place from the rear end.
We have inserted first 10, then 20, then 30, then 40, then 50, in the queue.

Before performing insert operation you must check whether the queue is full or
not. If the rear pointer is going beyond the maximum size of the queue then the
queue overflow Occurs.

2. Deletion of element from the queue

The deletion of any element in the queue takes place by the front end always.

The number 10 gets deleted logically

That means queue is from front to rear only. i.e. from 20 to 60


Before performing any delete operation one must check whether the queue is
empty or not. If the queue is empty, you cannot perform the deletion. The result of
illegal attempt to delete an element from the empty queue is called the queue
underflow condition.

Let us see the 'C' implementation of the queue.

Ex. 4.10.1 Implementation of queue using arrays.

/******************************************************************

Program for implementing the Queue using arrays

***************************************************************/

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

#define size 5

struct queue Queue data structure declared with array que[], front and rear

int que[size];

int front,rear;

}Q;

/*

The Qfull Function


*/

Qfull()

if(Q.rear >=size-1) If Queue exceeds the maximum size of the array then it returns
1 - means queue full is true otherwise 0 means queue full is false

return 1;

else

return 0;

/*

The insert Function

*/

int insert(int item)

if(Q.front == -1)

Q.front++;

Q.que[++Q.rear] = item; Always increment the rear pointer and place the element
in the queue

return Q.rear;

int Qempty()

{
if((Q.front == -1) || (Q.front > Q.rear))

The display Function

*/

void display()

int i;

for(i=Q.front;i<=Q.rear;i++). Printing the queue from front to rear

printf("%d", Q.que[i]);

void main(void)
{

int choice,item;

char ans;

clrscr();

Q.front =-1;

do

printf("\n Main Menu");

printf("\n1.Insert\n2.Delete\n3.Display");

printf("\n Enter Your Choice");

scanf("%d", &choice);

switch(choice)

case 1:if(Qfull()) //checking for Queue overflow

printf("\n Can not insert the element");

else

{
printf("\n Enter The number to be inserted");

scanf("%d",&item);

insert(item);

break;

case 2:if(Qempty())

printf("\n Queue Underflow!!");

else

delet();

break;

case 3:if(Qempty())

printf("\nQueue Is Empty!");

else

display();

break;

default:printf("\n Wrong choice!");

break;

printf("\n Do You Want to continue?");

ans = getche();

} while(ans == 'Y' || ans =='y');

}
/**************************End Of Program ***************/

Output

Main Menu

1. Insert

2. Delete

3. Display

Enter Your Choice 1

Enter The number to be inserted 10

Do You Want to continue?y

Main Menu

1. Insert

2. Delete

3. Display

Enter Your Choice 1

Enter The number to be inserted 20

Do You Want to continue?y

Main Menu

1. Insert

2. Delete

3. Display

Enter Your Choice 3

10 20
Do You Want to continue?y

Main Menu

1. Insert

2. Delete

3. Display

Enter Your Choice 2

The deleted item is 10

Do You Want to continue?y

Main Menu

1. Insert

2. Delete

3. Display

Enter Your Choice 3

20

Do You Want to continue?n

Key Point Always check queue full before insert operation and queue empty
before delete operation.

Ex. 4.10.2: Write a C program to implement queue functions using arrays and
macros. AU: May-15, Marks 16

Sol. :

#include<stdio.h>
#include<stdlib.h>

#include<conio.h>

/* Macro definitions */

#define size 5

#define Isfull Q.rear >=size-1

#define Isempty (Q.front == -1) || (Q.front > Q.rear)

struct queue

int que[size]; //Queue using Arrays

int front,rear;

}Q;

Qfull()

if(Isfull)

return 1;

else

return 0;

int insert(int item)

if(Q.front ==-1)

Q.front++;
Q.que[++Q.rear] = item;

return Q.rear;

int Qempty()

if(Isempty)

return 1;

else

return 0;

int delet()

int item;

item = Q.que[Q.front];

Q.front++;

printf("\n The deleted item is %d",item);

return Q.front;

void display()

int i;

for(i=Q.front;i<=Q.rear;i++)
printf("%d", Q.que[i]);

void main(void)

int choice,item;

char ans;

Q.front = -1;

Q.rear =-1;

do

printf("\n Main Menu");

printf("\n1.Insert\n2.Delete\n3.Display");

printf("\n Enter Your Choice");

scanf("%d", &choice);

switch(choice)

case 1:if(Qfull()) //checking for Queue overflow

printf("\n Can not insert the element");

else

printf("\n Enter The number to be inserted");

scanf("%d", &item);
insert(item);

break;

case 2:if(Qempty())

printf("\n Queue Underflow!!");

else

delet();

break;

case 3:if(Qempty())

printf("\nQueue Is Empty!");

else

display();

break;

default:printf("\n Wrong choice!");

break;

printf("\n Do You Want to continue?");

ans = getche();

} while(ans =='Y' || ans =='y');

Review Question
1. Develop an algorithm to implement Queue ADT. Give relevant examples and
diagrammatic representations.AU: May-16, Marks 12

Priority Queues
AU: Dec.-19, Marks 15

• Definition: The priority queue is a data structure having a collection of elements


which are associated with specific ordering.

• There are two types of priority queues-

1. Ascending priority queue 2. Descending priority queue.

Application of Priority Queue

1. The typical example of priority queue is scheduling the jobs in operating system.
Typically operating system allocates priority to jobs. The jobs are placed in the
queue and position of the job in priority queue determines their priority. In
operating system there are three kinds of jobs. These are real time jobs, foreground
jobs and background jobs. The operating system always schedules the real time
jobs first. If there is no real time job pending then it schedules foreground jobs.
Lastly if no real time or foreground jobs are pending then operating system
schedules the background jobs.

2. In network communication, to manage limited bandwidth for transmission the


priority queue is used.

3. In simulation modelling, to manage the discrete events the priority queue is


used.

Types of Priority Queue

The elements in the priority queue have specific ordering. There are two types of
priority queues -

1. Ascending priority queue: An ascending order priority queue gives the highest
priority to the lower number in that queue.
2. Descending priority queue: A descending order priority queue gives the
highest priority to the highest number in that queue.

In priority queue, the elements are arranged in any order and out of which only the
smallest or largest element allowed to delete each time.

The implementation of priority queue can be done using arrays or linked list. The
data structure heap is used to implement the priority queue effectively.

ADT for Priority Queue

Various operations that can be performed on priority queue are

1. Insertion

2. Deletion

3. Display

Hence the ADT for priority queue is given as below -

Instances:

P_que[MAX] is a finite collection of elements associated with some priority.


Precondition :

The front and rear should be within the maximum size MAX.

Before insertion operation, whether the queue is full or not is checked.

Before any deletion operation, whether the queue is empty or not is checked.

Operations :

1. create() - The queue is created by declaring the data structure for it.

2. insert() The element can be inserted in the queue.

3. delet() - If the priority queue is ascending priority queue then only smallest
element is deleted each time. And if the priority queue is descending priority queue
then only largest element is deleted each time.

4. display() The elements of queue are displayed from front to rear.

The implementation of priority queue using arrays is as given below -

1. Insertion operation

While implementing the priority queue we will apply a simple logic. That is while
inserting the element we will insert the element in the array at the proper position.
For example, if the elements are placed in the queue as

And now if an element 8 is to be inserted in the queue then it will be at 0 th location


as -
If the next element comes as 11 then the queue will be -

The C function for this operation is as given below -

int insert(int que[SIZE],int rear,int front)

int item,j;

printf("\nEnter the element: ");

scanf("%d", &item);

if(front ==-1)

front++;

j=rear;

while(j>=0 && item<que[j])

quelj+1]=que[j];

j- -;

que[j+1]=item;

rear=rear+1;

return rear;
}

2. Deletion operation

In the deletion operation we are simply removing the element at the front.

For example, if queue is created like this -

Then the element at que[0] will be deleted first.

and then new front will be que[1].

The deletion operation in C is as given below -

int delet(int que[SIZE],int front)

int item;

item=que[front];

printf(“\n The item deleted is %d”,item);

front++;

return front;

The complete implementation of priority queue is as given below -


Ex. 4.11.1: Implementation of Priority Queue

Sol. :

/
******************************************************************
Program for implementing the ascending priority Queue

**************************************************************/

/*Header Files*/

#include<stdio.h>

#include<conio.h>

#define SIZE 5

void main(void)

int rear,front,que[SIZE], choice;

int Qfull(int rear), Qempty(int rear,int front);

int insert(int que[SIZE], int rear,int front);

int delet(int que [SIZE], int front);

void display(int que[SIZE], int rear,int front);

char ans;

clrscr();

front=0;

rear=-1;
do

clrscr();

printf("\n\t\t Priority Queue\n");

printf("\n Main Menu");

printf("\n1.Insert\n2.Delete\n3.Display");

printf("\n Enter Your Choice: ");

scanf("%d", &choice);

switch(choice)

case 1:if(Qfull(rear))

printf("\n Queue IS full");

else

rear=insert(que,rear, front);

break;

case 2:if(Qempty(rear, front))

printf("\n Cannot delete element");

else

front=delet(que, front);

break;

case 3:if(Qempty(rear, front))

printf("\n Queue is empty");


else

display(que,rear, front);

break;

default:printf("\n Wrong choice");

break;

printf("\n Do You Want To continue?");

ans =getche();

} while(ans == 'Y' || ans =='y');

getch();

int insert(int que [SIZE], int rear,int front)

int item,j;

printf("\nEnter the element: ");

scanf("%d", &item);

if(front = = -1)

front++;

j=rear;

while(j>=0 && item<que[j])

que[j+1]=que[j];
j- -;

que[j+1]=item;

rear=rear+1;

return rear;

int Qfull(int rear)

if(rear==SIZE-1)

return 1;

else

return 0;

int delet(int que[SIZE], int front)

int item;

item=que[front];

printf("\n The item deleted is %d",item);

front++;

return front;

Qempty(int rear,int front)


{

if((front==-1) | | (front>rear))

return 1;

else

return 0;

void display(int que[SIZE], int rear,int front)

int i;

printf("\n The queue is:");

for(i=front;i<=rear;i++)

printf("%d",que[i]);

Output

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Output

Enter Your Choice: 1


Enter the element: 30

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice: 1

Enter the element: 10

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display
Enter Your Choice: 1

Enter the element: 20

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice: 1

Enter the element: 50

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice: 1


Enter the element: 40

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice: 3

The queue is: 10 20 30 40 50

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice: 2


The item deleted is 10

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice: 2

The item deleted is 20

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display
Enter Your Choice: 2

The item deleted is 30

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice: 2

The item deleted is 40

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display
Enter Your Choice: 2

The item deleted is 50

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice: 2

Cannot delete element

Do You Want TO continue?

Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice: 3

Queue is empty

Do You Want TO continue?n

Ex. 4.11.2: Write program for implementing the linked priority queue.

Sol. :
#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

/*Declaration of Linked Queue data structure*/

typedef struct node

int data;

struct node *next;

}Q;

Q *front, *rear;

/*

The main Function

*/

void main(void)

char ans;

int choice;

void insert();

Q *delet();

void display(Q *);

front= NULL;

rear= NULL;
do

printf("\n\tProgram For Linked priority Queue\n");

printf("\n Main Menu");

printf("\n1.Insert\n2.Delete \n3.Display");

printf("\n Enter Your Choice");

scanf("%d", &choice);

switch(choice)

case 1 : insert();

break;

case 2:front = delet();

break;

case 3 :display(front);

break;

default:printf("\nYou have entered Wrong Choice\n");

break;

printf("\nDo you want to continue?\n");

flushall();

ans = getch();

} while(ans=='y' || ans == 'Y');


getch();

clrscr();

/*

The get_node function

*/

Q *get_node(Q *temp)

temp =(Q*)malloc(sizeof(Q));

temp->next = NULL;

return temp;

/*

The insert Function

*/

void insert()

char ch;

Q *temp, *current, *prev; clrscr();

temp =get_node(temp); /* allocates memory for temp node*/

printf("\n\n\n\tInsert the element in the Queue\n");

scanf("%d",&temp->data);
/*The new node which is to be inserted is temp */

if(front == NULL)/* creating first node*/

front= temp;

rear=temp;

else/*first node is created and next node is to be attached*/

current=front;

/*current node is to be compared with every node from beginnning*/

prev=current;

/*if temp node is attached as a first node to remaining list*/

if(current->data>temp->data)

temp->next=current;

front=temp;/*update front*/

/*if temp node is to be inserted in between*/

else

while((current->data <temp->data)&&(current!= NULL))

{
/*prev is previous to current node */

prev=current;

current=current->next;

}/*end of while*/

/*if temp->data>current->data and current node!= NULL*/

if(current)

prev->next=temp;

temp->next = current;

/*attaching temp as a last node when temp has greaest among all the nodes in the
list and we have reached at the end of the list*/

else

prev->next=temp;

rear=temp;/*as temp is appended, rear is changed,temp becomes rear*/

}/*closing the outermost else*/

/*

The delet Function


*/

Q *delet()

Q *temp;

int Qempty(Q *front);

temp=front;

if(Qempty(front))

printf("\n\n\t\tSorry!The Queue Is Empty\n");

printf("\n Can not delete the element");

else

printf("\n\tThe deleted Element Is %d ",temp->data);

front=front->next;/*deleting the front node*/

temp->next = NULL;

free(temp);

return front;

/*

The QEmpty Function


*/

int Qempty(Q *front)

if(front== NULL)

return 1;

else

return 0;

/*

The display Function

Input: front pointer

Called By:main

Calls:QEmpty

*/

void display(Q *front)

if(Qempty(front))

printf("\n The Queue Is Empty\n");

else

printf("\n\t The Display Of Queue Is \n");

/*queue is displayed from front to rear*/


for(;front!=rear->next;front=front->next)

printf("\t%d ",front->data);

getch();

Output

Program For Linked Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice 1

Insert the element in the Queue

Do you want to continue?

Program For Linked Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice 1

Insert the element in the Queue


11

Do you want to continue?

Program For Linked Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice 1

Insert the element in the Queue

15

Do you want to continue?

Program For Linked Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice 1

Insert the element in the Queue

Do you want to continue?

Program For Linked Priority Queue

Main Menu
1.Insert

2.Delete

3.Display

Enter Your Choice 1

Insert the element in the Queue

12

Do you want to continue?

Program For Linked Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice 3

The Display Of Queue Is

7 9 11 12 15

Do you want to continue?

Program For Linked Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice 2


The deleted Element Is 7

Do you want to continue?

Program For Linked Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice 2

The deleted Element Is 9

Do you want to continue?

Program For Linked Priority Queue

Main Menu

1.Insert

2.Delete

3.Display

Enter Your Choice

The Display Of Queue Is

11 12 15

Do you want to continue?

Logic Explanation of Linked Priority Queue

Refer above program while understanding this section.

1. Insertion of a node
Initially queue will be empty and if we want to insert the first node. Then first
memory will get allocated for temp node as :

If we want to insert 9 then

temp = get_node();

As it is our first node in queue

if (front== NULL)

front = temp;

rear = temp;

Now, if want to insert next item say 11 then we will create temp node as

Then we will start scanning the queue from beginning because we want to insert
node with '11' at proper place.
While((current → data < temp → data)&&(current != NULL))

prev = current;

current = current →next;

current = NULL;

else

prev →next = temp;

rear = temp;
}

Now if we want to insert temp node with value '7' in the linked queue then we will
find the position for temp node in linked queue.

if (current → data > temp → data)

temp → next = current;

front = temp;

Continuing in this fashion we create a linked list in an ascending order.

2. Deletion of a node

The deletion operation is simple. We always delete a node which is at front.


Consider that the priority queue is

temp=front;

printf("\n\t The deleted element is%d", temp → data);

front =front → next;

temp → next =NULL;

Review Question

1. Implement a priority queue using linked list. AU: Dec.-19, Marks 15

Applications of Queue
AU: Dec.-19, Marks 15

There are various applications of queues such as,

1. Job Scheduling

• In the operating system various programs are getting executed.


• We will call these programs as jobs. In this process, some programs are in
executing state.

• The state of these programs is called as 'running' state.

• Some programs which are not executing but they are in a position to get executed
at any time such programs are in the 'ready' state.

• And there are certain programs which are neither in running state nor in ready
state. Such programs are in a state called as 'blocked' state.

• The operating system maintains a queue of all such running state, ready state,
blocked state programs. Thus use of queues help the operating system to schedule
the jobs.

• The jobs which are in running state are removed after complete execution of each
job, then the jobs which are in ready state change their state from ready to running
and get entered in the queue for running state.

• Similarly the jobs which are in blocked state can change their state from blocked
to ready state.

• These jobs then can be entered in the queue for ready state jobs.

• Thus every job changes its state and finally get executed. Refer Fig. 4.12.1.

• Thus queues are effectively used in the operating system for scheduling the jobs.
Categorizing Data
• The queue can be used to categorize the data.

• The typical example for categorizing the data is our college library.

• The college can have several departments such as Computer Engineering,


Information Technology, Mechanical Engineering, Electronics Engineering and so
on. The library has various sections in which the books from each stream are
arranged.

• These sections are like multiple queues in which appropriate data (books) are
stored. Thus categorization of data can be possible using multiple queues.

Ex. 4.12.1: There are 'N' numbers of balls in the box. The colors of the balls are
red and blue. You are requested to stack the balls in the bottom sealed basket
one by one. The order of placing the balls is two consecutive red balls followed
by two consecutive blue balls. Later create two empty queues Q1 and Q2.
Remove the last inserted balls from the basket and place it in Q1. Similarly
remove the next inserted balls from the basket and insert it in Q2. Develop a
program to repeat this process until the basket is empty and also print the color
of the balls in both queues. AU: Dec.-19, Marks 15

Sol. :

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#define size 25

/* stack structure*/

struct stack

char s[size];
int top;

}st;

struct queue

char que[size];

int front,rear;

}Q1, Q2;

int stfull()

if(st.top>=size - 1)

return 1;

else

return 0;

void push()

for(int i=0;i<2;i++)

st.top++;

st.s[st.top]='r';

for(int i=0;i<2;i++)
{

st.top++;

st.s[st.top]='b'; tex

printf("\n Balls are Pushed !!!");

int stempty()

if(st.top== -1)

return 1;

else

return 0;

char pop()

char item;

item=st.s[st.top];

st.top--;

printf("\n Ball is popped");

return(item);

void insert_Queue1 (char item)


{

printf("\n Inserting ball in Q1");

if(Q1.front == -1)

Q1.front++;

Q1.que[++Q1.rear] = item;

void insert_Queue2(char item)

printf("\n Inserting ball in Q2");

if(Q2.front == -1)

Q2.front++;

Q2.que[++Q2.rear] = item;

void display_queue(struct queue Q)

int i;

for(i=Q.front;i<=Q.rear;i++)

printf("%c",Q.que[i]);

void display_stack()

int i;
if(stempty())

printf("\n Stack Is Empty!");

else

for(i=st.top;i>=0;i - -)

printf("\n%c", st.s[i]);

int main(void)

int choice;

char ans,item;

st.top = -1;

Q1.front= -1;

Q1.rear= -1;

Q2.front= -1;

Q2.rear =1;

do

printf("\n Main Menu");

printf("\n1.Push the balls\n2.Pop\n3.exit");

printf("\n Enter Your Choice: ");


scanf("%d", &choice);

switch(choice)

case 1:if(stfull())

printf("\n Stack is Full!");

void display_queue(struct queue Q)

int i;

for(i=Q.front;i<=Q.rear;i++)

printf("%c",Q.que[i]);

void display_stack()

int i;

if(stempty())

printf("\n Stack Is Empty!");

else

for(i=st.top;i>=0;i — −)

printf("\n%c", st.s[i]);

}
int main(void)

int choice;

char ans,item;

st.top = -1;

Q1.front = -1;

Q1.rear = -1;

Q2.front = -1;

Q2.rear = -1;

do

printf("\n Main Menu");

printf("\n1.Push the balls\n2.Pop\n3.exit");

printf("\n Enter Your Choice: ");

scanf("%d", &choice);

switch(choice)

case 1:if(stfull())

printf("\n Stack is Full!");

else {

push();

display_stack();
}

break;

case 2:if(stempty())

printf("\n Empty stack!Underflow !!");

else

while(!stempty())

item=pop();

insert_Queue1(item);

item=pop();

insert_Queue2(item);

printf("\n Displaying Queue1...\n");

display_queue(Q1);

printf("\n Displaying Queue2...\n");

display_queue(Q2);

printf("\n----------------------\n");

display_stack();

break;

case 3:exit(0);
}

printf("\n Do You want To Continue? ");

ans=getche();

} while(ans == 'Y' || ans =='y');

getch();

return 0;

Output

Main Menu

1.Push the balls

2.Pop

3.exit

Enter Your Choice: 1

Balls are Pushed !!!!

Do You want To Continue? y

Main Menu

1.Push the balls

2.Pop

3.exit
Enter Your Choice: 2

Ball is popped

Inserting ball in Q1

Ball is popped og r

Inserting ball in Q2

Displaying Queue1...

Displaying Queue2...

------------------------

Ball is popped

Inserting ball in Q1

Ball is popped

Inserting ball in Q2

Displaying Queue1...

br

Displaying Queue2...

br

--------------------------

Stack Is Empty!

Two Marks Questions with Answers


Q. 1Give an example that shows how a stack is used by a computer system.

Ans. : In computer system the memory model consists of stack memory stores
types of variables that have a fixed lifetime based on how C programs run. It is a
section of RAM that grows and shrinks as the program runs. When you call a
function, its parameters and any variables you have defined in that function (which
are not static) are stored on the stack.

Q. 2 What do you understand by polish notation? Explain.

Ans. : This is also called as prefix notation. In this type of notation the operator
followed by two operands. For example if (a+b)*c is a given expression then its
polish notation will be *+ abc.

Q. 3 What is a top pointer of a stack?

Ans. : The top denotes the only one end of the stack from which the element can
be inserted or deleted. When we push the element onto the stack, the top is
incremented. When we pop the element from the stack the top is decremented.

Q. 4 Write the postfix notation for following expression. (A+B)*C-(D-E)^F

Ans.: Following steps can be followed for computing the postfix expression -

Step 1: (AB+)*C-(D-E)^F

Step 2: (AB+C*)-(D-E)^F

Step 3: (AB+C*)-(DE-)^F

Step 4: (AB+C*)-(DE-F^)

Step 5: AB+C*DE-F^-
Q. 5 Write any two applications of stack. AU: Dec.-14, 18, 19

Ans. : The stack can be used for

1. Conversion of expression from one form to another. Various forms of


expression are infix, prefix and postfix.

2. Evaluation of postfix expression.

3. Evaluation of recursive functions.

4. Reversing the string.

5. For checking the well formedness of parenthesis.

Q. 6 List the characteristics of stacks.

Ans. :

1. Insertion and deletion can be made by one end only. Hence the element inserted
last will be first one to come out. Hence sometimes it is called LIFO.

2. Stacks are useful for evaluating an expression.

3. Stacks can store the functions calls.

Q. 7 Write the role of stack in function call.

Ans. : The stack is an useful data structure for handling the recursive function
calls. When a recursive call is encountered, the status of call is pushed onto the
stack. And at the return of the call the stack is popped off. Thus execution of
recursive statements is done with the help of stack.
Q. 8 What is Last-In-First-Out strategy? Which data structure follows this
strategy?

Ans. : In the Last In First Out strategy we insert the element in the data structure
lastly and while removing the elements from this data structure, the element which
is inserted lastly will get removed first.

The stack data structure makes use of Last In First Out(LIFO) data structure.

Q. 9 Write the steps to reverse the contents of the list with the help of stack data
structure.

Ans. :

Step 1: Read each element from the list and push it onto the stack.

Step 2: Pop the element from the stack and store the popped element in a separate

Step 3: Read the array completely from left to write. This will be the reversed list
of the elements.

Q. 10 Which data structure is used in handling the recursive function?

Ans. : The stack is used to handle the recursive function call.

Q. 11 Given the prefix for an expression write its postfix. AU: May-15

-*-+abc/ef-g/hi

Ans. :

-*-+abc/ef-g/hi

- * - T1 cef-g/hi T1 = ab+

-T2/ef-g/hi T2 = T1c-
- T2 T3 g/hi T3=ef /

- T4g-/hi T4 = T2T3*

- T4 g T5 T5 = hi/

-T4 T6 T6=g T5-

T7 T7= T4 T6

By backward substitution,

T7

T4 T6-

T2 T3 T6 -

T1 c T3 * T6 -

ab + c - T3 * T6 -

ab + c –ef/*t6-

ab + c -ef/* g T5--

ab + c - ef /* ghi/ -- is postfix expression

Q. 12 Give the infix for an expression, write its prefix a* b/c+d?

Ans. : The prefix expression is /* ab + cd.

Q. 13 Convert the following infix expression to postfix expression using stack.

AU: May - 19

Ans. :
The required postfix expression is abc*def++g/+.

Q. 14 State the rules to be followed during infix to postfix conversion. AU: Dec.-
19

Ans. : Refer section 4.6.

Q. 15 What do the terms LIFO and FIFO means? Explain.

Ans. : The LIFO stands for Last In First Out. This property belongs to stack. That
means the element inserted lastly will be the element to be popped off first from
the stack.

The FIFO stands for First In First Out. This property belongs to queue. That means
the element inserted first in the queue will be the first to get deleted.

Q. 16 What are the front and rear pointers of queue.

Ans. : The front end of the queue from which the element gets deleted is called
front and the end from which the element is inserted in the queue is called rear. is
called rear.roA For example: Refer Fig. 4..10.1.

Q. 17 Write any four applications of queues. AU: May-14

Ans. :

1. In operating system for scheduling jobs, priority queues are used.

2. In Local Area Network (LAN) multiple computers share few printers. Then
these printers accumulate jobs in a queue. Thus printers can process multiple print
commands with the help of queues.

3. For categorizing data, queues are used.


4. In simulation and modeling queues are used.

5. In computer networks, while broadcasting message, the message packets are


accumulated in queue. And then these packets are forwarded.

Q. 18 What is a dequeue? AU: May-14,16 Dec.-14

Ans. : The dequeue is a data structure in which the element can be inserted from
both the ends i.e. front and rear. Similarly, the element can be deleted from both
the front and rear end.

Q. 19 How do you test for an empty queue?

Ans. : Following is a C code which is used to test an empty queue -

if((Q.front==-1) | | (Q.front>Q.rear))

printf("\n The Queue is Empty!!");

else

printf("\n The Queue is not Empty!!");

Q. 20 What is the use of queue in operating system ?

Ans. :

The queue is used for scheduling the jobs in operating system.

Q. 21 What is stack and queue ?

AU: Dec.-15

Ans. :
Stack is linear data structure in which insertion and deletion of element is from one
end called top.

Queue is a linear data structure in which insertion of element is from one end
called rear and deletion of element is from other end called front.

Q. 22 What are priority queues? What are the ways to implement priority
queue?

AU: Dec.-18

Ans. :

• Definition: The priority queue is a data structure having a collection of elements


which are associated with specific ordering.

• Ways to implement priority queue:

There are two ways to implement priority queue.

1. Ascending priority queue - It is a collection of items in which the items can be


inserted arbitarily but only smallest element can be removed.

2. Descending priority queue - It is a collection of items in which insertion of


items can be in any order but only largest element can be removed.
Non-Linear Data Structures - Trees

Unit IV
Chapter 5
a. Non-Linear Data Structures – Trees

Syllabus
Trees - Binary Trees - Tree Traversals - Expression Trees - Binary Search Tree.

Contents
5.1 Trees

5.2 Binary Trees

5.3 Representation of Binary Tree

5.4 Tree Traversal ……. Dec.-19, ……. Marks 13

5.5 Expression Trees …….. Dec.-18, ………. Marks 15

5.6 Binary Search Tree ……. Dec.-18,19, ……. Marks 13

5.7 Two Marks Questions with Answers

Trees
A tree is a finite set of one or more nodes such that -

i) There is a specially designated node called root.

ii) The remaining nodes are partitioned into n> = 0 disjoint sets T1, T2,T3...Tn where
T1, T2,T3...Tn are called the sub-trees of the root.

The concept of tree is represented by following Fig. 5.1.1.


Various operations that can be performed on the tree data structure are

1. Creation of a tree

2. Insertion of a node in the tree as a child of desired node.

3. Deletion of any node(except root node) from the tree.

4. Modification of the node value of the tree.

5. Searching particular node from the tree.

1. Basic Terminologies
Let us get introduced with some of the definitions or terms which are normally
used.
From Fig. 5.1.2,

1. Root

Root is a unique node in the tree to which further subtrees are attached. For
above given tree, node 10 is a root node.

2. Parent node

The node having further sub-branches is called parent node. In Fig. 5.1.3 the 20 is
parent node of 40, 50 and 60.

3. Child nodes

The child nodes in above given tree are marked as shown below -
4. Leaves

These are the terminal nodes of the tree.

For example -

5. Degree of the node

The total number of subtrees attached to that node is called the degree of a node.

For example.
6. Degree of tree

The maximum degree in the tree is degree of tree.

7. Level of the tree

The root node is always considered at level zero.

The adjacent nodes to root are supposed to be at level 1 and so on.


8. Height of the tree

The maximum level is the height of the tree. In Fig. 5.1.8 the height of tree is 3.
Sometimes height of the tree is also called depth of tree.

9. Predecessor

While displaying the tree, if some particular node occurs previous to some other
node then that node is called predecessor of the other node.

For example: While displaying the tree in Fig. 5.1.8 if we read node 20 first and
then if we read node 40, then 20 is a predecessor of 40.

10. Successor

Successor is a node which occurs next to some node.

For example: While displaying tree in Fig. 5.1.8 if we read node 60 after reading
node 20 then 60 is called successor of 20.

11. Internal and external nodes

Leaf node means a node having no child node. As leaf nodes are not having
further links, we call leaf nodes External nodes and non leaf nodes are
called internal nodes.
12. Sibling

The nodes with common parent are called siblings or brothers.

For example

In this chapter we will deal with special type of trees called binary trees. Let us
understand it.

Binary Trees
• Definition of a binary tree: A binary tree is a finite set of nodes which is either
empty or consists of a root and two disjoint binary trees called the left subtree and
right subtree.
• The binary tree can be as shown below -

Abstract DataType BinT (node * root)

Instances : Binary tree is a nonlinear data structure which contains every node
except the leaf nodes at most two child nodes.

Operations:
1. Insertion :

This operation is used to insert the nodes in the binary tree. By inserting desired
number of nodes, the binary tree gets created.

2. Deletion :

This operation is used to remove any node from the tree. root node is removed
the tree becomes empty.

1. Types of Binary Tree


Full Binary Tree

• A full binary tree is a tree in which every node has zero or two children.

• In other words, the full binary tree is a binary tree in which all the nodes have
two children except the leaf node. (Refer Fig. 5.2.3)

Complete Binary Tree

• The complete binary tree is a binary in which all the levels are completely filled
except the last level which is filled from left.
• There are two points to be remembered

1) The leftmost side of the leaf node must always be filled first.

2) It is not necessary for the last leaf node to have right sibling.

• Note that in above representation, Treel is a complete binary tree in which all
the levels are completely filled, whereas Tree2 is also a complete binary tree in
which the last level is filled from left to right but it is incompletely filled.

Difference between complete binary tree and full binary tree

Left and Right Skewed Trees


The tree in which each node is attached as a left child of parent node then it is left
skewed tree. The tree in which each node is attached as a right child of parent
node then it is called right skewed tree.

Representation of Binary Tree


There are two ways of representing the binary tree.

1. Sequential representation

2. Linked representation.

Let us see these representations one by one.

1. Sequential representation of binary trees or array

representation :
Each node is sequentially arranged from top to bottom and from left to right. Let
us understand this matter by numbering each node. The numbering will start
from root node and then remaining nodes will give ever increasing numbers in
level wise direction. The nodes on the same level will be numbered from left to
right. The numbering will be as shown below.

Now, observe Fig. 5.3.1 carefully. You will get a point that a binary tree of depth n
having 2n-1 number of nodes. In Fig. 5.3.1 the tree is having the depth 4 and total
number of nodes are 15. Thus remember that in a binary tree of depth n there
will be maximum 2n-1 nodes. And so if we know the maximum depth of the tree
then we can represent binary tree using arrays data structure. Because we can
then predict the maximum size of an array that can accommodate the tree.

Thus array size can be > = n. The root will be at index 0. Its left child will be at
index 1, its right child will be at index 2 and so on. Another way of placing the
elements in the array is by applying the formula as shown below -

• When n = 0 the root node will placed at 0th location

• Parent(n) = floor(n-1)/2

• Left(n) = (2n+1)

• Right(n) = (2n+2).
Advantages of sequential representation

The only advantage with this type of representation is that the direct access to
any node can be possible and finding the parent, left or right children of any
particular node is fast because of the random access.

Disadvantages of sequential representation

1. The major disadvantage with this type of representation is wastage of memory.

For example In the skewed tree half of the array is unutilized. You can easily
understand this point simply by seeing Fig. 5.3.3.
2. In this type of representation the maximum depth of the tree has to be fixed
because we have already decided the array size. If we choose the array size quite
larger than the depth of the tree, then it will be wastage o of the memory. And if
we choose array size lesser than the depth of the tree then we will be unable to
represent some part of the tree.

3. The insertions and deletion of any node in the tree will be costlier as other
nodes have to be adjusted at appropriate positions so that the meaning of binary
tree can be preserved.

As these drawbacks are there with this sequential type of representation, we will
search for more flexible representation. So instead of array we will make use of
linked list to represent the tree.

2. Linked representation or node representation of binary

trees
In binary tree each node will have left child, right child and data field.

Left child Data Right child

The left child is nothing but the left link which points to some address of left
subtree whereas right child is also a right link which points to some address of
right subtree. And the data field gives the information about the node. Let us see
the 'C' structure of the node in a binary tree.

typedef struct node

int data;

struct node *left;

struct node *right;

}bin;

The tree with Linked representation is as shown below-

Advantages of linked representation

1. This representation is superior to our array representation as there is no


wastage of memory. And so there is no need to have prior knowledge of depth of
the tree. Using dynamic memory concept one can create as many memory
(nodes) as required. By chance if some nodes are unutilized one can delete the
nodes by making the address free.

2. Insertions and deletions which are the most common operations can be done
without moving the other nodes.
Disadvantages of linked representation

1. This representation does not provide direct access to a node and special
algorithms are required.

2. This representation needs additional space in each node for storing the left and
right sub-trees.

Ex. 5.3.1: For the given data draw a binary tree and show the array
representation of the same: 100 80 45 55 110 20 70 65

Sol. The binary tree will be

Formula used for placing the node values in array are

1. Root will be at 0th location

2. Parent(n) - floor (n - 1)/2

3. Left (n) = (2n+1)

4. Right (n) = (2n + 2)

where n > 0.
Ex. 5.3.2: What is binary tree? Show the array representation and linked
representation for the following binary tree.
Sol. Binary Tree : Binary Tree is a finite set of nodes which is either empty or
consists of a root and two disjoint binary trees called left subtree and right
subtree.

Array Representation
Linked Representation

Tree Traversal
AU: Dec.-19, Marks 13 grej)rabroni

• Definition : Tree traversal means visiting each node exactly once.

• Basically there are six ways to traverse a tree. For these traversals we will use
following notations :

L for moving to left child

R for moving to right child

D for parent node

• Thus with L, R, D we will have six combinations such as LDR, LRD, DLR,
DRL, RLD, RDL.

• From computation point of view, we will consider only three combinations as


LDR, DLR and LRD i.e. inorder, preorder and postorder respectively.

1) Inorder Traversal :

In this type of traversal, the left node is visited, then parent node and then right
node is visited.

For example

Algorithm :

1. If tree is not empty then


a. traverse the left subtree in inorder

b. visit the root node

c. traverse the right subtree in inorder

The recursive routine for inorder traversal is as given below

void inorder(node *temp)

if(temp!= NULL)

inorder(temp->left); ← Moving to leftmost node

printf("%d", temp->data);

inorder(temp->right);" ← Moving to rightmost node

2) Preorder Traversal :

In this type of traversal, the parent node or root node is visited first; then left node
and finally right node will be visited.

For example
Algorithm:

1. If tree is not empty then

a. visit the root node

b. traverse the left subtree in preorder

c. traverse the right subtree in preorder

The recursive routine for preorder traversal is as given below.

void preorder(node *temp)

if(temp!= NULL)

printf("%d",temp->data); ← Moving to leftmost node

preorder(temp->left);

preorder(temp->right); ← Moving to rightmost node

3) Postorder Traversal :
In this type of traversal, the left node is visited first, then right node and finally
parent node is visited.

For example

Algorithm:

1. If tree is not empty then

a. traverse the left subtree in postorder

b. traverse the right subtree in postorder

c. visit the root node

The recursive routine for postorder traversal is as given below.

void postorder(node *temp)

if(temp!= NULL)

postorder(temp->left);

postorder(temp->right);

printf("%d",temp->data);
}

Ex. 5.4.1: Write inorder, preorder and postorder traversal for the following tree:

Sol. :

Inorder 8 10 11 30 20 25 40 42 45 60 50 55

Preorder 40 30 10 8 11 25 20 50 45 42 60 55

Postorder 8 11 10 20 25 30 42 60 45 55 50 40.

Ex. 5.4.2: Implementation of binary tree

Sol.:

/******************************************

Program for creation of a binary tree and display the tree using recursive inorder,
preorder and post order traversals
********************************************/

#include <stdio.h>

#include <alloc.h>

#include<conio.h>

typedef struct bin

int data;

struct bin *left;

struct bin *right;

}node;/*Binary tree structure*/

void insert(node *, node *);

void inorder(node *);

void preorder(node *);

void postorder(node *);

node *get_node();

void main()

int choice;

char ans='n';

node *New,*root;
root=NULL;

clrscr();

do

printf("\n Program For Implementing Simple Binary Tree");

printf("\n 1.Create");

printf("\n 2.Inorder");

printf("\n 3.Preorder ");

printf("\n 4.Postorder");

printf("\n 5.Exit");

printf("\n\t Enter Your Choice: ");

scanf("%d", &choice);

switch(choice)

case 1:root = NULL;

do

New=get_node();

printf("\n Enter The Element: ");

scanf("%d", &New->data);

if(root == NULL)

root=New;
else

insert(root,New);

printf("\n Do You want To Enter More elements?(y/n):");

ans=getche();

while(ans=='y' || ans == 'Y');

clrscr();

break;

case 2:if(root == NULL)

printf("Tree Is not Created!");

else

inorder(root);

break;

case 3:if(root == NULL)

printf("Tree Is Not Created!");

else

preorder(root);

break;

case 4:if(root == NULL)

printf("Tree Is Not Created!");

else

postorder(root);
break;

} while (choice!=5);

node *get_node()

node *temp;

temp = (node *)malloc(sizeof(node));

temp->left = NULL;

temp->right = NULL;

return temp;

void insert(node *root,node *New)

char ch;

printf("\n Where to insert left/right of %d: ", root->data);

ch=getche();

if ((ch=='r') || (ch=='R'))

if(root->right == NULL)

{
root->right=New;

else

insert(root->right,New);

else

if (root->left== NULL)

root->left=New;

else

insert(root->left, New);

void inorder(node *temp)

if(temp!= NULL)

inorder(temp->left);

printf("%d",temp->data);

inorder(temp->right);
}

void preorder(node *temp)

if(temp!= NULL)

printf("%d",temp->data);

preorder(temp->left);

preorder(temp->right);

void postorder(node *temp)

if(temp!= NULL)

postorder(temp->left);

postorder(temp->right);

printf("%d",temp->data);

Output

Program For Implementing Simple Binary Tree


1. Create

2. Inorder

3. Preorder

4. Postorder

5. Exit

Enter Your Choice: 1

Enter The Element: 10

Do You Want To Enter More Elements?(y/n): y

Enter The Element: 12

Where to insert left/right of 10: 1

Do You Want To Enter More Elements?(y/n): y

Enter The Element: 17

Where to insert left/right of 10: r

Do You Want To Enter More Elements?(y/n): y

Enter The Element: 8

Where to insert left/right of 10: 1

Where to insert left/right of 12: r

Do You Want To Enter More Elements?(y/n):

Program For Implementing Simple Binary Tree

1.Create

2.Inorder

3.Preorder
4.Postorder

5.Exit

Enter Your Choice: 2

12 8 10 17

Program For Implementing Simple Binary Tree

1.Create

2.Inorder

3.Preorder

4.Postorder

5.Exit

Enter Your Choice: 3

10 12 8 17

Program For Implementing Simple Binary Tree

1. Create

2. Inorder

3. Preorder

4. Postorder

5. Exit

Enter Your Choice: 4

8 12 17 10

Program For Implementing Simple Binary Tree

1. Create
2. Inorder

3. Preorder

4. Postorder

5. Exit

Enter Your Choice: 5

Review Question

1. Explain the tree traversal techniques with an example.

AU: Dec.-19, Marks 13

Expression Trees
AU: Dec.-18, Marks 15

Definition: An expression tree is a binary tree in which the operands are attached
as leaf nodes and operators become the internal nodes.

For example -

From expression tree :

Inorder traversal: A+B*C(Left-Data-Right)

Preorder traversal: +A*BC(Data-Left-Right)


Postorder traversal: ABC*+ (Left-Right-Data)

If we traverse the above tree in inorder, preorder or postorder then we get infix,
prefix or postfix expressions respectively.

Key Point: Inorder traversal of expression tree fives infix expression. The preorder
traversal of expression tree gives prefix expression and post order traversal of
expression tree gives postfix expression.

1. Creation of an Expression Tree


Consider a postfix expression, stored in array exp

Now we will read each symbol from left to right one character at a time. If we
read an operand then we will make a node of it and push it onto the stack. If we
read operator then pop two nodes from stack, the first popped node will be
attached as right child to operator node and second popped node will be attached
as a left child to operator node. For the above given expression let us build a tree.
Now as we read '+' pop two operands and attach them as follows -

Now push the node '+' onto the stack.

Next we read c and d. Hence stack will be -


Now we read '-'. So pop two nodes

Next we read '*'. Hence pop two nodes from the stack and attach them to * node.
As now we read '\0', pop the content of stack. The node which we will get is the
root node of an expression tree.

Let us implement it
Ex. 5.5.1: Program for creating an expression tree and printing it using an
inorder traversal.

Sol. :

#include <stdio.h>

#include <conio.h>

#include <alloc.h>

#include <ctype.h>

#define size 20

typedef struct node

char data;

struct node *left;

struct node *right;

}btree;

/* stack stores the operand nodes of the tree*/

btree *stack[size];

int top;

void main()
{

btree *root;

char exp[80]; /* exp stores postfix expression */

btree *create(char exp[80]);

void display(btree *root);

clrscr();

printf("Enter the postfix expression\n");

scanf("%s",exp);

top = -1; /* Initialise the stack */

root create(exp);

printf("\n The Tree is created...\n");

printf("\n The inorder traversal of it is \n");

display(root);

getch();

btree* create(char exp[])

btree *temp;

int pos;

char ch;

void push(btree *);

btree *pop();
pos = 0;

ch = exp[pos];

while (ch!= '\0')

/* Create a new node */

temp -> left = temp -> right = NULL;

temp -> data = ch;

if (isalpha(ch)) /* is it a operand */

push (temp); /* push operand */

else if (ch=='+' || ch==''||ch=="*' || ch=='/')

/* it is operator, so pop two nodes from stack

set first node as right child and

set second as left child and push the

operator node on to the stack

*/

temp->right = pop();

temp ->left = pop();

push(temp);

else

printf("Invalid character in expression\n");


pos ++;

ch exp[pos]; /* Read next character */

temp = pop();

return(temp);

void push(btree *Node)

if (top+1 >= size)

printf("Error: Stack is Full\n");

top++;

stack[top] = Node;

btree* pop()

btree *Node;

if (top = = -1)

printf("Error: Stack is Empty\n");

Node = stack[top];

top--;

return(Node);

}
void display(btree *root)

btree *temp;

temp = root;

if (temp!= NULL)

display(temp->left);

printf("%c", temp->data);

display(temp->right);

Output

Enter the postfix expression

ab+cd-*

The Tree is created...

The inorder traversal of it is

a+b * c - d

Ex. 5.5.2: Show the binary tree with arithmetic expression A/B * C * D + E. Give
the algorithm for inorder, preorder, postorder traversals and show the result of
these traversals.

Sol. :
Algorithm for inorder, preorder and postorder Traversal - Refer section 5.4.

Inorder Traversal A/B*C*D+E

Preorder Traversal + * * / ABCDE

Postorder Traversal AB/C*D*E+

Review Question

1. What are expression trees. Write the procedure for constructing an expression
tree.

AU: Dec.-18, Marks 15


Binary Search Tree
AU: Dec.-18,19, Marks 13

Binary search tree is a binary tree in which the nodes are arranged in specific
order. That means the values at left subtree are less than the root node value.
Similarly the values at the right subtree are greater than the root node. Fig. 5.6.1
represents the binary search tree.

The binary search tree is based on binary search algorithm.

1. Operations on Binary Search Tree


1. Insertion of a node in a binary tree

Algorithm:

1. Read the value for the node which is to be created and store it in a node
called New.

2. Initially if (root!=NULL) then root-New.

3. Again read the next value of node created in New.

4. If (New->value < root->value) then attach New node as a left child of root
otherwise attach New node as a right child of root.
5. Repeat steps 3 aand 4 for constructing required binary search tree completely.

void insert(node *root,node *New)

if(New->data <root->data)

if(root->left== NULL) ← Attaching left node to the current node.

root->left=New;

else

insert(root->left,New);

if(New->data>root->data)

if(root->right == NULL)

root->right=New; ← If the root node has already some left child, then move onto
left subtree.

else

insert(root->right,New);

srit aupaib au fo

While inserting any node in binary search tree, first of all we have to look for its
appropriate position in the binary search tree. We start comparing this new node
with each node of the tree. If the value of the node which is to be inserted is greater
than the otolob totes a value of current node we move onto the right subbranch
otherwise we move onto the left subbranch. As soon as the appropriate position is
found we attach this new node as left or right child appropriately.

In the Fig. 5.6.2 if we want to insert 23. Then we will start comparing 23 with
value of root node i.e. 6. As 23 is greater than 10, will will move on right subtree.
Now we will compare 23 with 20 and move right, compare 23 with 22 and move
right. Now compare 23 with 24 but it is less than 24. We will move on left branch
of 24. But as there is NULL node as left child of 24, we can attach 23 as left child
of 24.
2. Deletion of an element from the binary tree

For deletion of any node from binary search tree there are three cases which are
possible.

i. Deletion of leaf node.

ii. Deletion of a node having one child.

iii. Deletion of a node having two children.

Let us discuss the above cases one by one.

i. Deletion of leaf node

This is the simplest deletion, in which we set the left or right pointer of parent node
as NULL.
From the above tree, we want to delete the node having value 6 then we will set
left pointer of its parent node as NULL. That is left pointer of node having value 8
is set to NULL.

ii. Deletion of a node having one child

To explain this kind of deletion, consider a tree as shown in the Fig. 5.6.6.
If we want to delete the node 15, then we will simply copy node 18 at place of 15
and then set the node free. The inorder successor is always copied at the position of
a node being deleted.
iii. The node having two children

Again, let us take some example for discussing this kind of deletion.

Let us consider that we want to delete node having value 7. We will then find out
the inorder successor of node 7. The inorder successor will be simply copied at
location of node 7. Thats it!

That means copy 8 at the position where value of node is 7. Set left pointer of 9 as
NULL. This completes the deletion procedure.
void del(node *root,int key)

node *temp, *parent,*temp_succ

temp=search(root,key,&parent);

/*deleting a node with two children*/

if(temp->left!= NULL&&temp->right!= NULL)

parent=temp;

temp_succ=temp->right; ← temp is node which is to be deleted. Parent is a node


which keeps track of parent of node temp and temp_succ is for keeping track of
success of temp.

while(temp_succ->left!= NULL)

parent=temp_succ;
temp_succ=temp_succ->left; ← Moving to leftmost subtree

temp->data=temp_succ->data; ← Copying the successor node's data to temp node.


Thus content of temp node gets deleted.

if(temp_succ == parent->left)

parent->left = NULL;

else

parent->right = NULL;

printf(" Now Deleted it!");

return;

/* deleting a node having only one child*/

/*The node to be deleted has left child*/

if(temp->left!= NULL &&temp->right == NULL)

if(parent->left==temp)

parent->left=temp->left; ← Finding parent of temp

else

parent->right-temp->left;

temp=NULL;

free(temp);

printf(" Now Deleted it!");


return;

/*The node to be deleted has right child*/

if(temp->left==NULL &&temp->right!= NULL)

if(parent->left == temp)

parent->left-temp->right;

else

parent->right-temp->right;

temp=NULL;

free(temp);

printf(" Now Deleted it!");

return;

/*deleting a node which is having no child*/

if(temp->left==NULL &&temp->right == NULL)

3. Searching a node from binary search tree

In searching, the node which we want to search is called a key node. The key node
will be compared with each node starting from root node if value of key node is
greater than current node then we search for it on right subbranch otherwise on left
subbranch. If we reach to leaf node and still we do not get the value of key node
then we declare "node is not present in the tree".
In the above tree, if we want to search for value 9. Then we will compare 9 with
root node 10. As 9 is less than 10 we will search on left subbranch. Now compare 9
with 5, but 9 is greater than 5. So we will move on right subbranch. Now compare
9 with 8 but as 9 is greater than 8 we will move on right subbranch. Now we read
the node value as 9. Thus the desired node can be searched. Let us see the 'C'
implementation of it.

The routine is as given below -

Non-recursive search routine

node *search(node *root,int key,node **parent)

node *temp;

temp=root;

while(temp!= NULL)

if(temp->data==key)
{

printf("\n The %d Element is Present",temp->data);

return temp;

*parent=temp; ← via to mexport/a/, Mang

if(temp->data>key) ← if current node is greater than key

temp-temp->left; ← Search for the left subtree.

else

temp-temp->right;

return NULL;

We can display a tree in inorder fashion. Hence the complete implementation is


given below along with appropriate output.

/*****************************************

Program for Implementation of Binary Search Tree and

perform insertion deletion, searching, display of tree.

*****************************************/

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>

typedef struct bst


{

int data;

struct bst *left, *right;

}node;

void insert(node *,node *);

void inorder(node *);

node *search(node *,int,node **);

void del(node *,int);

void main()

int choice;

char ans='N';

int key;

node *New,*root, *tmp, *parent;

node *get_node();

root = NULL;

clrscr();

printf("\n\t Program For Binary Search Tree ");

do

{
printf("\n1.Create\n2.Search\n3.Delete\n4.Display");

printf("\n\n Enter your choice :");

scanf("%d", &choice);

switch(choice)

case 1:do

New get_node();

printf("\n Enter The Element ");

scanf("%d", &New->data);

if(root == NULL) /* Tree is not Created */

root=New;

else

insert(root,New);

printf("\n Do u Want To enter More Elements?(y/n)");

ans=getch();;

}while(ans= ='y');

break;

case 2:printf("\n Enter The Element Which You Want To Search");

scanf("%d", &key);

tmp=search(root,key,&parent);

printf("\n Parent of node %d is %d",


tmp->data,parent->data);

break;

case 3:printf("\n Enter The Element U wish to Delete");

scanf("%d", &key);

del(root,key);

break;

case 4:if(root == NULL)

printf("Tree Is Not Created");

else

printf("\n The Tree is: ");

inorder(root);

break;

}while(choice!=5);

node *get_node()

node *temp;

temp (node *)malloc(sizeof(node));

temp->left=NULL;
temp->right=NULL;

return temp;

/*This function is for creating a binary search tree */

void insert(node *root,node *New)

if(New->data <root->data)

if(root->left== NULL)

root->left=New;

else

insert(root->left,New);

if(New->data>root->data)

if(root->right == NULL)

root->right=New;

else

insert(root->right,New);

/*
This function is for searching the node from binary Search Tree

*/

node *search(node *root,int key,node **parent)

node *temp;

temp=root;

while(temp!= NULL)

if(temp->data= =key)

printf("\n The %d Element is Present",temp->data);

return temp;

*parent=temp;

if(temp->data>key)

temp-temp->left;

else

temp-temp->right;

return NULL;

/*
This function is for deleting a node from binary search tree. There exists three
possible cases for deletion of a node

*/

void del(node *root,int key)

node *temp, *parent,*temp_succ;

temp=search(root,key,&parent);

/*deleting a node with two children*/

if(temp->left!= NULL&&temp->right!= NULL)

parent=temp;

temp_succ-temp->right;

while(temp_succ->left!= NULL)

parent=temp_succ;

temp_succ=temp_succ->left; ← Finding successor node of temp node

temp->data=temp_succ->data;. ← Copy the data of successor node to temp node

if(temp_succ = = parent->left)

parent->left = NULL;

else

parent->right = NULL;
printf(" Now Deleted it!");

return;

/*deleting a node having only one child*/

/*The node to be deleted has left child*/

if(temp->left!= NULL &&temp->right= = NULL)

if(parent->left == temp)

parent->left=temp->left;

else

parent->right-temp->left;

temp=NULL;

free(temp);

printf(" Now Deleted it!");

return;

/*The node to be deleted has right child*/

if(temp->left== NULL &&temp->right!= NULL)

if(parent->left == temp)

parent->left-temp->right; ← Parent's left child is deleted.

else
parent->right-temp->right;

temp=NULL;

free(temp);

printf(" Now Deleted it!");

return;

/*deleting a node which is having no child*/

if(temp->left==NULL &&temp->right == NULL)

:{

if(parent->left= =temp)

parent->left= NULL;

else

parent->right=NULL; ← Simply make parent's left pointer NULL, so that left


child of parent is deleted.

printf(" Now Deleted it!");

return;

/*

This function displays the tree in inorder fashion

*/

void inorder(node *temp)


{

if(temp!= NULL)

inorder(temp->left);

printf("%d",temp->data);

inorder(temp->right);

Output

Program For Binary Search Tree

1. Create

2. Search

3. Delete

4. Display

Enter your choice :1

Enter The Element 10

Do u Want To enter More Elements?(y/n)

Enter The Element 8

Do u Want To enter More Elements?(y/n)

Enter The Element 9

Do u Want To enter More Elements?(y/n)

Enter The Element 7


Do u Want To enter More Elements?(y/n)

Enter The Element 15

Do u Want To enter More Elements?(y/n)

Enter The Element 13

Do u Want To enter More Elements?(y/n)

Enter The Element 14

Do u Want To enter More Elements? (y/n)

Enter The Element 12

Do u Want To enter More Elements? (y/n)

Enter The Element 16

Do u Want To enter More Elements? (y/n)

1. Create

2. Search

3. Delete

4. Display

Enter your choice :4

The Tree is: 7 8 9 10 12 13 14 15 16

1. Create

2. Search

3. Delete
4. Display

Enter your choice :2

Enter The Element Which You Want To Search16

The 16 Element is Present

Parent of node 16 is 15

1. Create

2. Search

3. Delete

4. Display

Ex. 5.6.1 Define binary search tree. Draw the binary search tree for the
following input. 14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5

Sol. Binary Search Tree (Refer section 5.6)


Ex. 5.6.2 Define a binary search tree and construct a binary search tree. With
elements {22, 28, 20, 25, 22, 15, 18, 10, 14). Give recursive search algorithm to
search an element in that tree.

Sol. Binary Search Tree (Refer section 5.6)

Example
Recursive Algorithm for search - Refer example 5.6.4.

Ex. 5.6.3: What is binary search tree? Draw the binary search tree for the
following input. 14, 5, 6, 2, 18, 20, 16, 18, -1, 21.

Sol. Binary Search Tree : Refer section 5.6.

Example
Ex. 5.6.4: What is binary search tree? Write a recursive search routine for
binary search tree.

Sol. Binary Search Tree: Refer section 5.6.

Recursive Search Routine

node *search(node temp, int key)

if (temp == NULL || key == temp.data)

return temp;

else

if (key<temp.data)

return search(temp->left, key);

else

return search(temp->right,key);

Ex. 5.6.5 Write the following routines to implement the basic binary search tree
operations

AU: Dec.-18, Marks 13

(i) Perform search operation in binary search tree signs

(ii) Find_min and Find_max

Sol.: (i) Search operation - Refer section 5.6.1.


(ii) Find_min and Find_max

Consider following binary search tree

For finding the minimum value from the binary search tree, we need to traverse to
the left most node. Hence the left most node in above Fig. 5.6.11 is with value 7
which is the minimum value. Note that for the leftmost node the left pointer is
NULL.

The routine for finding the minimum value from the binary search tree is,

Find_min(node *root)

struct node* current=root;

while(current->left != NULL)

current=current->left;

printf("%d", current->data);

For finding the maximum value from the binary search tree, we need to traverse to
the right most node. Hence the right most node in above Fig. 5.6.11 is with value
13 which is the maximum value. Note that for the rightmost node the right pointer
is NULL. The routine for finding the maximum value from the binary search tree is
Find_max(node *root)

{
struct node* current=root;

while(current->right != NULL)

current-current->right;

printf("%d", current->data);

Review Questions

1. Write a iterative search routine for a binary search tree.

2. Describe the binary search tree with an example. Write a iterative function to
search for the key value in binary search tree. esmito giarollo sit stiW 2.8.2

3. How to insert and delete an element into binary search tree and write down the
code for the insertion routine with an example. dose grandi moitos

AU: Dec.-19, Marks 13

Programming Examples
Ex. 5.6.6 Program for counting total number of nodes.

Sol. :

/********************************************

Program For Counting Total number of nodes Of The

Binary Search Tree.

*********************************************/

#include<stdio.h>

#include <alloc.h>

#include<conio.h>

typedef struct bst1


{

int data;

struct bst1 *left,*right;

}bs;

bs *New,*root;

/*---------------------------------------------------

The main Function with a menu of operations

--------------------------------------------------------*/

void main()

char ans='N';

void insert(bs *,bs *);

void inorder(bs *);

int count(bs *,int);

int cnt;

bs *get_node();

clrscr();

root = NULL;

printf("\n\t Program For The Binary Search Tree");

do

New=get_node();

if(root = = NULL)
root=New;

else

insert(root,New);

printf("\n Do u Want To enter More Elements?(y/n)");

ans=getch();

}while(ans= ='y');

printf("\n The Tree Is: ");

inorder(root);

cnt=0;

cnt count(root,cnt);

printf("\n The Total Number Of Nodes in Tree are: %d",cnt);

bs *get_node()

bs *temp;

temp=(bs*)malloc(sizeof(bs));

printf("\n Enter The Element");

scanf("%d", &temp->data);

temp->left=NULL;

temp->right = NULL;

return temp;

void insert(bs *root,bs *New)


{

if(New->data <root->data)

if(root->left== NULL)

root->left=New;

else

insert(root->left,New);

if(New->data>root->data)

if(root->right== NULL)

root->right=New;

else

insert(root->right, New);

int count(bs* temp,int cnt)

static int i=0;

if(temp!= NULL)

i++;

count(temp->left,i);
count(temp->right,i);

return i;

void inorder(bs *temp)

if(temp!= NULL)

inorder(temp->left);

printf("%d", temp->data);

inorder(temp->right);

Ex. 5.6.7 Program for finding height of BST.

Sol.:

/***************************************

Program For finding height of Binary Search Tree.

****************************************/

#include<stdio.h>

#include <alloc.h>

#include <conio.h>
typedef struct bst1

int data;

struct bst1 *left,*right;

}bs;

bs *New,*root;

/**************************************

The main Function with a menu of operations

***************************************/

void main()

char ans='N';

void insert(bs *,bs *);

void inorder(bs *);

int height(bs *);

int count;

bs *get_node();

clrscr();

root=NULL;

printf("\n\t Program For The Binary Search Tree");

do

New=get_node();
if(root == NULL)

root=New;

else

insert(root,New);

printf("\n Do u Want To enter More Elements? (y/n)");

ans=getch();

} while(ans= ='y');

printf("\n The Tree Is: ");

inorder(root);

count=0;

count height(root);

printf("\n The height of Tree is: %d",count);

bs *get_node()

bs *temp;

temp=(bs*)malloc(sizeof(bs));

printf("\n Enter The Element ");

scanf("%d", &temp->data);

temp->left=NULL;

temp->right= NULL;

return temp;

}
void insert(bs *root,bs *New)

if(New->data <root->data)

if(root->left== NULL)

root->left=New;

else

insert(root->left,New);

if(New->data>root->data)

if(root->right == NULL)

root->right=New;

else

insert(root->right,New);

int height(bs * temp)

int max(int,int);

if (temp== NULL)

return 0;

else
return (1+max(height(temp->left),height(temp->right)));

if(x>y)

return x;

return y;

void inorder(bs *temp)

if(temp!= NULL)

inorder(temp->left);

printf("%d", temp->data);

inorder(temp->right);

Program For The Binary Search Tree

Enter The Element 10

Do u Want To enter More Elements?(y/n)

Enter The Element 9

Do u Want To enter More Elements?(y/n)

Enter The Element 15


Do u Want To enter More Elements? (y/n)

Enter The Element 7

Do u Want To enter More Elements?(y/n)

Enter The Element 12

Do u Want To enter More Elements?(y/n)

Enter The Element 18

Do u Want To enter More Elements?(y/n)

Enter The Element 14

Do u Want To enter More Elements?(y/n)

Enter The Element 13

Do u Want To enter More Elements?(y/n)

The Tree Is: 7 9 10 12 13 14 15 18

The height of Tree is : 5

Ex. 5.6.8 Program to display the tree in levelwise manner.

Sol.:

/**********************************
Program to create a binary tree and print the data level wise or in a breadth first
search order. The data in each level will be

displayed on seperate lines.

**********************************/

#include<stdio.h>

#include <alloc.h>

#include <conio.h>

#define size 50

typedef struct node

int data;

struct node *left;

struct node *right;

}btree;

btree *root, *New;

void insert(node *,node *);

void enque(btree *Node);

btree *deque ();

int front, rear;

void insert(node *root,node *New)

if(New->data <root->data)
{

eals

if(root->left= = NULL)

root->left=New;

else

insert(root->left, New);

if(New->data>root->data)

if(root->right== NULL)

root->right=New;

else

insert(root->right,New);

void display()

btree *temp, *dummy;

dummy = (btree*)malloc(sizeof(btree));

if (dummy = = NULL)

printf("Insufficient Memory\n");

dummy->left = root;

dummy->right = NULL;
dummy->data = '';

temp = dummy ->left;

enque(temp);

enque(dummy);

temp = deque();

while(front != rear)

if (temp!= dummy)

printf("%d",temp->data);

if (temp->left != NULL)

enque(temp -> left);

if (temp->right != NULL)

enque(temp -> right);

else

enque(temp);

printf("\n");

temp = deque();

}
void enque(btree *Node)

if (rear = = size-1)

printf("Queue is full\n");

rear = rear + 1;

que[rear] = Node;

btree *deque ()

btree *Node;

if (front = = rear)

printf("Queue is empty\n");

front++;

Node = que[front];

return(Node);

void main()

char ans='y';

root=NULL;

front-rear =-1;

do

{
clrscr();

New (btree *)malloc(sizeof(btree));

New->left=NULL;

New->right = NULL;

printf("\n Enter The Element ");

if(root == NULL)/* Tree is not Created */

root=New;

else

insert(root,New);

printf("\n Do u Want To enter More Elements?(y/n)\n");

ans=getch();

while(ans= ='y');

display();

getch();

Output

Enter The Element 10

Do u Want To enter More Elements?(y/n)

Enter The Element 8

Do u Want To enter More Elements?(y/n)

Enter The Element 7

Do u Want To enter More Elements? (y/n)

Enter The Element 9


Do u Want To enter More Elements?(y/n)

Enter The Element 12

Do u Want To enter More Elements?(y/n)

Enter The Element 11

Do u Want To enter More Elements?(y/n)

Enter The Element 13

Do u Want To enter More Elements?(y/n)

10

8 12

7 9 11 13

Ex. 5.6.9 Program for copying Binary Search Tree.

Sol. :

/***************************************

Program For Copying The Binary Search Tree.

***************************************/

#include<stdio.h>

#include <alloc.h>

#include <conio.h>

typedef struct bst1

int data;

struct bst1 *left, *right;


}bs;

bs *New,*second,*root;

/**************************************

The main Function with operations

***************************************/

void main()

char ans='N';

void insert(bs *,bs *);

void inorder(bs *);

bs *copy(bs *);

bs *get_node();

clrscr();

root= NULL;

printf("\n\t Program For Copying The Binary Search Tree");

do

New get_node();

if(root== NULL)

root=New;

else

insert(root, New);

printf("\n Do u Want To enter More Elements?(y/n)");


ans=getch();

} while(ans= ='y');

printf("\n The Tree Is: ");

inorder(root);

printf("\n The Copied Tree Is :");

second copy(root);

inorder(second);

bs *get_node()

bs *temp;

temp=(bs*)malloc(sizeof(bs));

printf("\n Enter The Element ");

scanf("%d", &temp->data);

temp->left=NULL;

temp->right=NULL;

return temp;

void insert(bs *root,bs *New)

if(New->data <root->data)

if(root->left== NULL)
root->left=New;

else

insert(root->left,New);

if(New->data>root->data)

if(root->right == NULL)

root->right=New;

else

insert(root->right,New);

bs *copy(bs * first)

bs *New;

if (first!= NULL)

New = (bs *)malloc(sizeof(bs));

if (New == NULL)

printf("\nMemory Is Not Allocated\n");

New->left copy(first -> left);

New->right copy(first -> right);

New->data = first -> data;


return (New);

else

return NULL;

void inorder(bs *temp)

if(temp!= NULL)

inorder(temp->left);

printf("%d",temp->data);

inorder(temp->right);

Output

Program For Copying The Binary Search Tree

Enter The Element 10

Do u Want To enter More Elements?(y/n)

Enter The Element 8

Do u Want To enter More Elements?(y/n)

Enter The Element 9


Do u Want To enter More Elements?(y/n)

Enter The Element 7

Do u Want To enter More Elements?(y/n)

Enter The Element 15

Do u Want To enter More Elements?(y/n)

The Tree Is: 7 8 9 10 15

The Copied Tree Is: 7 8 9 10 15

Ex. 5.6.10 Program for comparing two BSTs.

Sol. :

/*******************************************

Program For Comparision Of Two Binary Search Trees.

*******************************************/

#include<stdio.h>

#include <conio.h>

#define TRUE 1

#define FALSE 0

typedef struct bst1

int data;
struct bst1 *left, *right;

}bs;

bs *s;

void insert(bs *,bs *);

void inorder(bs *);

int equal(bs *,bs *);

bs *get_node();

/******************************************

This Function is for allocation of memory for the node

*******************************************/

bs *get_node()

bs *temp;

temp=new bs;

printf("\n Enter The Element ");

scanf("%d", &temp->data);

temp->left= NULL;

temp->right = NULL;

return temp;

/**************************************

This function is for creating a binary search tree

**************************************/
void insert(bs *root,bs *New)

if(New->data <root->data)

if(root->left== NULL)

root->left=New;

else

insert(root->left, New);

if(New->data>root->data)

if(root->right == NULL)

root->right=New;

else

insert(root->right,New);

/**************************************

This function displays the tree in inorder fashion

***************************************/

void inorder(bs *temp).

if(temp!= NULL)

inorder(temp->left);
printf("%d", temp->data);

inorder(temp->right);

/**************************************

Function For Comparing Two Trees

**************************************/

int equal(bs *t1,bs *t2)

int flag;

flag = FALSE;

if (t1 = = NULL && t2 = = NULL)

flag = TRUE;

else

if (t1 != NULL && t2 != NULL)

if (t1->data == t2 -> data)

if (equal(t1 -> left, t2 -> left))

equal(t1 -> right, t2->right);

/**************************************

The main Function

***************************************/

void main()
{

int choice,flag;

bs *root1,*root2;

char ans='N';

clrscr();

root1=NULL;

root2= NULL;

printf("\n\t Program For Comparing The Two Binary Search Trees");

printf("\nCreate First Tree");

do

s=get_node();

if(root1== NULL)

root1=s;

else

insert(root1,s);

printf("\n Do u Want To enter More Elements?(y/n)");

ans=getch();

}while(ans= ='y');

printf("\nCreate Second Tree");

do

s=get_node();
if(root2== NULL)

root2=s;

else

insert(root2,s);

printf("\n Do u Want To enter More Elements?(y/n)");

ans=getch();

} while(ans= ='y');

printf("\n First Tree");

inorder(root1);

printf("\nSecond Tree");

inorder(root2);

flag=equal(root1,root2);

if (flag==TRUE)

printf("\nThe two trees are identical \n");

else

printf("\nThe two trees are not identical \n");

getch();

Output

Program For Comparing The Two Binary Search Trees

Create First Tree

Enter The Element 10


Do u Want To enter More Elements? (y/n)

Enter The Element 8

Do u Want To enter More Elements?(y/n)

Enter The Element 7

Do u Want To enter More Elements?(y/n)

Enter The Element 9

Do u Want To enter More Elements?(y/n)

Enter The Element 12

Do u Want To enter More Elements?(y/n)

Create Second Tree

Enter The Element 10

Do u Want To enter More Elements?(y/n)

Enter The Element 8

Do u Want To enter More Elements? (y/n)

Enter The Element 5

Do u Want To enter More Elements? (y/n)

Enter The Element 9


Do u Want To enter More Elements?(y/n)

Enter The Element 12

Do u Want To enter More Elements?(y/n)

First Tree 7 8 9 10 12

Second Tree 5 8 9 10 12

The two trees are not identical

Two Marks Questions with Answers

Q.1 What is the difference between linear and non-linear data structures?

Ans. :

Q.2 Define: Binary tree.


Ans. :

A binary tree is a finite set of nodes which is either empty or consists of root and
two disjoint binary trees called the left subtree and right subtree. Refer Fig.

Q.3 Give various implementation of tree.

Ans. : The tree can be implemented by two ways

1. Sequential implementation: The tree is implemented using arrays in this type of


implementation.

2. Linked implementation : The tree is implemented or represented using linked


list.

Q.4 Which tree representation is mostly preferred by the developers linked?


Justify.

Ans. :

There are two ways of representing the binary tree - sequential representation and
linked representation. The linked representation is normally preferred by
developers because in the linked representation the binary tree is represented using
linked list. Hence the tree with any number of nodes can be created. Secondly there
is no wastage or shortage of the memory in this representation.

Q.5 List the applications of trees.

Ans. :

1. In computer networking such as Local Area Network (LAN), Wide Area


Networking (WAN), internetworking.

2. In telephone cabling graph theory is effectively used.


3. In job scheduling algorithms the graphs are used.

Q.6 In tree construction which is the suitable efficient data structure ?

Ans. :

The linked list is the efficient data structure for constructing the trees. Because
using linked list there is no wastage of memory or shortage of memory. The nodes
can be allocated or de-allocated as per the requirements.

Q.7 What is meant by equivalent binary tree?

Ans. :

The two binary trees are said to be equivalent if the sequence of their traversal is
same.

Q.8 Define complete binary tree.

Ans. :

A complete binary tree is a tree in which every node except the root node should
have exactly two children not necessarily on the same level. Refer Fig. 5.7.1
Q.9 What is level of a tree?

AU: Dec.-19

Ans. :

The root node is always considered at level zero. The adjacent nodes to root are
supposed to be at level 1 and so on.

Q.10 What are internal and external nodes in a tree ?

Ans. :

Leaf node means a node having no child node. As leaf nodes are not having further
links, we call leaf nodes external nodes and non-leaf nodes are called internal
nodes.

Q.11 What is sibling node in a tree?

Ans. : The nodes with common parent are called siblings or brothers.

Q.12 What is forest ?

Ans. Forest is a collection of disjoint trees. From a given tree if we remove its root
then we get a forest. Refer Fig. 5.7.2.
Q.13 What is full binary tree?

Ans. : A full binary tree is a tree in which every node has zero or two children.
Refer Fig. 5.7.3.

Q.14 List out the traversal techniques used in tree.

Ans. :

1. Preorder 2. Postorder 3. Inorder traversal

Q.15 Which traversal results in elements in sorted order?

Ans. : The inorder traversal results in elements in sorted order.

Q. 16 How is binary tree represented using an array ? Give an example.

AU: Dec.-05

Ans. : In an array root node will be at position 1. Its left child will be at position 2
and right child will be at position 3. Hence the nodes of tree are placed in array
using following formula -

Parent (n) = floor ((n-1)/2)

left (n) = (2n+1)


right (n) = (2n + 2)

Consider tree as given below.

It will be placed in an array as given below.

Q.17 Construct an expression tree for the expression A+ (BC) * D* (E + F).

AU: May-06

Ans. :
Q.18 Define binary search tree.

AU: May-07, ECE, May-08, Dec.-09, 19

Ans.: Binary search tree is a binary tree in which each node is systematically
arranged i.e. the left child has less value than its parent node and right child has
greater value than its parent node. The searching of any node in such a tree
becomes efficient in this type of tree.

For example -

Q.19 List the operations defined on binary trees data type with a suitable
example.

Ans. :

Various operations that can be performed on binary trees are - 1. Insertion 2.


Deletion 3. Traversal

The insertion operation is performed to insert a node at any desired position.

For example -
We can delete any desired node from the binary tree except root node.

For example -

Traversal means a walkover a binary tree. It can be preorder, postorder and inorder
traversal.

Q.20 Write an algorithm to declare nodes of a tree structure.

Ans. Algorithm :

1. Declare a C structure for the node of a binary tree

typedef struct node

int data;

struct node *left;


struct node *right;

}bin;

2. Create a node by allocating memory by using the dynamic memory allocation.

New (bin*)malloc(sizeof(bin));

3. Initialize the Left and Right child pointers to NULL.

New->left=NULL;

New->right=NULL;

Thus a single node gets created. This is the first node of the tree, hence it is called
as the root node.

root=New;

4. Attach the next subsequent nodes to either as a left child or a right child to the
corresponding parent nodes depending on the user's choice.

Q.21 Why it is said that the searching a node in a binary search tree is efficient
than that of a simple binary tree?

Ans. : In the binary search tree the nodes are arranged in such a way that the left
node is having less data value than root node value. And the right nodes are having
larger value than that of root. Because of this while searching any node the value
of target node will be compared with the parent node and accordingly either left
sub branch or right sub branch will be searched. This procedure will be repeated if
required. So one has to compare only particular branches. Thus searching becomes
efficient.

Q.22 If a binary tree with n nodes is represented sequentially, then for any node
with index i (a) 1 ≤ i ≤n, then left child (i) is at 2i, if 2i ≤n. (b) If 2i>n, then I has
no left child. Name the type of binary tree which satisfies both (a) and (b).
AU: May-11

Ans. : The complete binary tree.

Q.23 What is meant by equivalent binary tree?

AU : May-11

Ans. : The two binary trees are said to be equivalent if the sequence of there
traversal is same for example -

The sequence is 8, 8, 9, 10, 11, 12, 13.

Q.24 List the applications of trees. AU: Dec.-11

Ans.

Binary tree is used in various applications such as -

1. Binary search tree

2. Game tree

3. Expression tree

4. Threaded Binary tree.


Q.25 Define binary tree and give binary tree node structure.

AU: Dec.-12

Ans. : A binary tree is a finite set of nodes which is either empty or consists of root
or two disjoint binary trees called the left subtree and right subtree.

Each node in the binary tree contains three fields left child pointer, data field and
right child pointer.

Left child Data Right child

struct BST

BST *leftchild;

int data;

BST *rightchild;

};

Q. 26 How many trees are possible with 3 nodes ?

Ans. :

For 3 nodes there are 2 3 - 3 trees possible. That means 5 such trees can be drawn.
For example - If there are 3 nodes with the value 10, 20, 30 then
Q. 27 Show the result of inorder traversal of the binary search tree given in
Fig. 5.7.4.

Ans. : Inorder Traversal: 1, 2, 3, 4, 5, 6, 7, 9

Q.28 For the tree in Fig. 5.7.5. AU: Dec.-18

a) List the siblings for node E.

b) Compute the height.


Ans. : i) Siblings
are those nodes that share common parents. Hence sibling of E is D.

ii) The maximum level of tree is called height. The maximum level is AB-E-J-M.
Thus height of tree of tree is 4.

Q. 29 The depth of complete binary tree is 8 and compute the number of nodes
in leaf.

AU: May-19

Ans : The relationship between depth of a tree and maximum number of nodes in
leaf is,

2d -1 = n

28 -1 = n

n = 255

Q. 30 How to resolve null links in a binary tree?

AU: May-19
Ans. : The left null link can point to predecessor node and the right null link can
point to successor node. This way the null links can be utilized so that tranversing
of the tree becomes efficient.
Hashing

Unit IV
Chapter 6
b. Hashing

Syllabus
Hashing - Hash Functions - Separate Chaining - Open Addressing - Linear
Probing- Quadratic Probing - Double Hashing - Rehashing.

Contents
6.1 Basic Concept … May-19, …. Marks 6

6.2 Hash Functions

6.3 Properties of Good Hash Function

6.4 Collision Handling .. Dec.-15,18, May-16,17,19, Marks 16

6.5 Applications of Hashing

6.6 Two Marks Questions with Answers

Basic Concept
Hashing is an effective way to reduce the number of comparisons. Actually
hashing deals with the idea of proving the direct address of the record where the
record is likely to store. To understand the idea clearly let us take an example -

Suppose the manufacturing company has an inventory file that consists of less
than 1000 parts. Each part is having unique 7 digit number. The number is called
'key' and the particular keyed record consists of that part name. If there are less
than 1000 parts then a 1000 element array can be used to store the complete file.
Such an array will be indexed from 0 to 999. Since the key number is 7 digit it is
converted to 3 digits by taking only last three digits of a key. This is shown in the
Fig. 6.1.1.
Observe in Fig. 6.1.1 that the first key 496700 and it is stored at oth position. The
second key is 8421002. The last three digits indicate the position 2nd in the array.
Let us search the element 4957397. Naturally it will be obtained at position 397.
This method of searching is called hashing. The function that converts the key (7
digit) into array position is called hash function. Here hash function is

h(Key) = key 1000

Where key % 1000 will be the hash function and the key obtained by
hash function is called hash key.

1. Basic Concepts in Hashing


1) Hash Table : Hash table is a data structure used for storing and retrieving data
quickly. Every entry in the hash table is made using Hash function.

2) Hash Function:

• Hash function is a function used to place data in hash table.

• Similarly hash function is used to retrieve data from hash table.

• Thus the use of hash function is to implement hash table.

For example : Consider hash function as key mod 5. The hash table of size 5.

3) Bucket: The hash function H(key) is used to map several dictionary entries in
the hash table. Each position of the hash table is called bucket.
4) Collision: Collision is situation in which hash function returns the same address
for more than one record.

For example

5) Probe: Each calculation of an address and test for success is known as a probe.

6) Synonym: The set of keys that has to the same location are called synonyms.
For example - In above given hash table computation 25 and 55 are synonyms.

7) Overflow : When hash table becomes full and new record needs to be inserted
then it is called overflow.

For example -
Ex. 6.1.1: Indicate whether you use an Array, Linked List or Hash Table to store
data in each of the following cases. Justify your answer.

1) A list of employee records needs to be stored in a manner that it is easy to


find max or min in the list.

2) A library needs to maintain books by their ISBN number. Only thing important
is finding them as soon as possible.

3) A data set needs to be maintained in order to find the median of the set
quickly.

AU: May-19, Marks 6

Sol. : 1) The list of employees can be stored in an array. The min or max value can
be searched easily from the array.

2) As the book is searched using ISBN, hash table can be used to store the book
records.

3) The data set can be stored in an array, so that the median of array can be easily
obtained.

Hash Functions
There are various types of hash functions or hash methods which are used to
place the elements in hash table.
1. Division Method
The hash function depends upon the remainder of division.

Typically the divisor is table length. For example :-

If the record 54, 72, 89, 37 is to be placed in the hash table and if the table size is
10 then

2. Multiplicative Hash Function


The multiplicative hash function works in following steps

1) Multiply the key 'k' by a constant A where A is in the range 0 < A < 1. Then
extract the fractional part of kA.
2) Multiply this fractional part by m and take the floor.

The above steps can be formulated as

Donald Knuth suggested to use A = 0.61803398987

Example :

Let key k = 107, assume m = 50.

A = 0.61803398987

That means 107 will be placed at index 6 in hash table.

Advantage: The choice of m is not critical

3. Extraction
In this method some digits are extracted from the key to form the address
location in hash table.
For example: Suppose first, third and fourth digit from left is selected for hash
key.

4. Mid Square
This method works in following steps

1) Square the key

2) Extract middle part of the result. This will indicate the location of the key
element in the hash table.

Note that if the key element is a string then it has to be preprocessed to produce
a number.

Let key = 3111

For the hash table of size of 1000

H(3111) = 783

Review Question

1. What is hashing function? Explain any four types of hashing functions.


Collision Handling
AU: Dec.-15, 18, May - 16, 17, 19, Marks 16

Definition: If collisions occur then it should be handled by applying some


techniques, such techniques are called collision handling techniques.

1. Chaining
1. Chaining without replacement

In collision handling method chaining is a concept which introduces an additional


field with data i.e. chain. A separate chain table is maintained for colliding data.
When collision occurs we store the second colliding data by linear probing
method. The address of this colliding data can be stored with the first colliding
element in the chain table, without replacement.

For example consider elements,

131, 3, 4, 21, 61, 6, 71, 8, 9

From the example, you can see that the chain is maintained the number who
demands for location 1. First number 131 comes we will place at index 1. Next
comes 21 but collision occurs so by linear probing we will place 21 at index 2, and
chain is maintained by writing 2 in chain table at index 1 similarly next comes 61
by linear probing we can place 61 at index 5 and chain will be maintained at index
2. Thus any element which gives hash key as 1 will be stored by linear probing at
empty location but a chain is maintained so that traversing the hash table will be
efficient.

The drawback of this method is in finding the next empty location. We are least
bothered about the fact that when the element which actually belonging to that
empty location cannot obtain its location. This means logic of hash function gets
disturbed.

2. Chaining with replacement

The method of chaining without replacement has a drawback of loosing the


meaning of the hash function, to overcome this drawback the method known as
chaining with replacement is introduced. Let us discuss the example to
understand the method. Suppose we have to store following elements:

131, 21, 31, 4, 5


Now next element is 2. As hash function will indicate hash key as 2 but already at
index 2. We have stored element 21. But we also know that 21 is not of that
position at which currently it is placed.

Hence we will replace 21 by 2 and accordingly chain table will be updated. See the
table:
The value -1 in the hash table and chain table indicate the empty location. The
advantage of this method is that the meaning of hash function is preserved. But
each time some logic is needed to test the element, whether it is at its proper
position.

2. Open Addressing
Open addressing is a collision handling technique in which the entire hash table is
searched in systematic way for empty cell to insert new item if collision occurs.

Various techniques used in open addressing are

1. Linear probing

2. Quadratic probing

3. Double hashing

1. Linear probing
When collision occurs i.e. when two records demand for the same location in the
hash table, then the collision can be solved by placing second record linearly
down wherever the empty location is found.

For example

In the hash table given in Fig. 6.4.3 the hash function used is number % 10. If the
first number which is to be placed is 131 then 131 % 10 = 1 i.e. remainder is 1 so
hash key = 1. That means we are supposed to place the record at index 1. Next
number is 21 which gives hash key 1 as 21 % 10 = 1. But already 131 is placed at
index 1. That means collision is occurred. We will now apply linear probing. In this
method, we will search the place for number 21 from location of 131. In this case
we can place 21 at index 2. Then 31 at index 3. Similarly 61 can be stored at 6
because number 4 and 5 are stored before 61. Because of this technique, the
searching becomes efficient, as we have to search only limited list to obtain the
desired number.
Ex. 6.4.1: Implement the hash table and perform collision handling by linear
probing

Sol. :

#include <stdio.h>

#include<conio.h>

void display(int a[ ], int n)

// Displaying complete hash table

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

printf("\n %d %d",i,a[i]);

void Linear_prob(int table[ ], int tsize,int num)

int key = num % tsize;//Computing the hash key using hash function

while (table[key]!= -1)//if empty slot is not found

key (key+1)%tsize;//then move linearly dow in search of empty slot

table[key]=num ;//if empty slot gets then insert the element


display(table, tsize);

int main()

int SIZE = 10;// Size of the hash table

int num;

int hash_table[SIZE];

char ans;

// Initializing the hash table

for (int i = 0; i < SIZE; i++)

hash_table[i] = -1;//-1 indicates empty slot

do

printf("\nEnter The Number: ");

scanf("%d", &num);//This element is to be inserted in hash table

Linear_prob(hash_table,SIZE,num);

printf("\n Do U Wish To Continue? (y/n)");

ans = getch();

}while(ans=='y');

return 0;
}

Output

Enter The Number: 131

0 -1

1 131

2 -1

3 -1

4 -1

5 -1

6 -1

7 -1

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 21

0 -1

1 131

2 21

3 -1

4 -1

5 -1

6 -1
7 -1

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 3

1- 0

1 131

2 21

3 3

4 -1

5 -1

6 -1

7 -1

8 -1

9 -1

Do U Wish To Continue? (y/n)

Enter The Number: 4

0 -1

1 131

2 21

3 3

44
5 -1

6 -1

7 -1

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 5

0 -1

1 131

2 21

33

44

LO

6 -1

7 -1

8 -1

9 -1

Do U Wish To Continue? (y/n)

Enter The Number: 8

0 -1
1

131

2 21

33

44

55

6 -1

7 -1

8 8

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 9

0 -1

1 131

2 21

3 3

4 4

55

6 -1

7 -1

8 8

9 9
Do U Wish To Continue?(y/n)

Enter The Number: 18

0 18

1 131

2 21

3 3

4 4

5 5

6 -1

7 -1

8 8

9 9

Do U Wish To Continue?(y/n)

Enter The Number: 33

0 18

1 131

2 21

3 3

4 4

5 5

6 33

7 -1
8 8

9 9

Do U Wish To Continue?(y/n)

Problem with linear probing

One major problem with linear probing is primary clustering. Primary clustering is
a process in which a block of data is formed in the hash table when collision is
resolved.

For example:

This clustering problem can be solved by quadratic probing.

2. Quadratic probing

Quadratic probing operates by taking the original hash value and adding
successive values of an arbitrary quadratic polynomial to the starting value. This
method uses following formula -
Hi(key) = (Hash(key)+i2)%m

where m can be a table size or any prime number.

For example: If we have to insert following elements in the hash table with table
size 10: 37, 90, 55, 22, 11, 17, 49, 87.

We will fill the hash table step by step

Now if we want to place 17 a collision will occur as 17%10-7 and bucket 7 has
already an element 37. Hence we will apply quadratic probing to insert this record
in the hash table.

Hi(key) = (Hash(key)+i2)%m

we will choose value i = 0, 1, 2, whichever is applicable.

Consider i = 0 then

(17+02) %10 = 7

(17+12) %10 = 8, when i = 1

The bucket 8 is empty hence we will place the element at index 8.


Then comes 49 which will be placed at index 9.

49%10 = 9

Now to place 87 we will use quadratic probing.

(87+0)%10 = 7

(87 + 1)%10 = 8 ... but already occupied

(87 +22)%10 = 1 ... already occupied

(87+32)%10 = 6... this slot is free

We place 87 at 6th index.


It is observed that if we want to place all the necessary elements in the hash table
the size of divisor (m) should be twice as large as total number of elements.

Ex. 6.4.2 Write a C program to implement quadratic probing.

Sol. :

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

void display(int a[], int n)

// Displaying complete hash table

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

printf("\n %d %d",i,a[i]);

void Quadratic_prob(int table[], int tsize,int num)

int key = num % t using size;//computing the hash key mod function

// Insert in the table if there is empty slot

if (table[key] == -1)

table[key] = num;

else.

for (int i = 0; i < tsize; i++)//using formula for quadratic probing

int index = (key + i* i) % tsize;

if (table[index] == -1)//if empty slot is found

{
table[index] break; = num;//then insert element at that index

break;

display(table, tsize);

int main()

int SIZE = 10;// Size of the hash table

int num;

int hash_table[SIZE];

char ans;

// Initializing the hash table

for (int i = 0; i < SIZE; i++)

hash_table[i] = -1;//-1 indicates empty slot

do

printf("\nEnter The Number: ");

scanf("%d", &num);//Number to be inserted in the hash table


Quadratic prob(hash_table,SIZE,num);

printf("\n Do U Wish To Continue?(y/n)");

ans = getch();

while(ans= ='y');

return 0;

Output

Enter The Number: 37

0 -1

1 -1

2 -1

3 -1

4 -1

5 -1

6 -1

7 37

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 90

0 90

1 -1
2 -1

3 -1

4 -1

5 -1

6 -1

7 37

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 55

0 90

1 -1

2 -1

3 -1

4 -1

5 55

6 -1

7 37

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 22


0 90

1 -1

2 22

3 -1

4 -1

5 55

6 -1

7 37

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 11

0 90

1 11

2 22

3 -1

4 -1

5 55

6 -1

7 37

8 -1

9 -1
Do U Wish To Continue?(y/n)

Enter The Number: 17

0 90

1 11

2 22

3 -1

4 -1

5 55

6 -1

7 37

8 17

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 49

0 90

1 11

2 22

3 -1

4 -1

5 55

6 -1

7 37
8 17

9 49

Do U Wish To Continue?(y/n)

Enter The Number: 87

0 90

1 11

2 22

3 -1

4 -1

5 55

6 87

7 37

8 17

9 49

Do U Wish To Continue?(y/n)

3. Double hashing

Double hashing is technique in which a second hash function is applied to the key
when a collision occurs. By applying the second hash function we will get the
number of positions from the point of collision to insert.

There are two important rules to be followed for the second function :

• It must never evaluate to zero.

• Must make sure that all cells can be probed.


The formula to be used for double hashing is

H1(key) = key mod tablesize

H2(key) = M (key mod M)

where M is a prime number smaller than the size of the table.

Consider the following elements to be placed in the hash table of size 10

37, 90, 45, 22, 17, 49, 55

Initially insert the elements using the formula for H1(key).

Insert 37, 90, 45, 22.


Now if 17 is to be inserted then

H1(17) = 17%10 = 7

H2(key) = M - (key%M)

Here M is a prime number smaller than the size of the table. Prime number
smaller than table size 10 is 7.

Hence M = 7

H2(17) = 7 (17%7) = 7 – 3 = 4

That means we have to insert the element 17 at 4 places from 37. In short we
have to take 4 jumps. Therefore the 17 will be placed at index 1.

Now to insert number 55.

H1 (55) 55%10 = 5... collision

H2(55) = 7-(55%7) = 7 - 6 = 1

That means we have to take one jump from index 5 to place 55. Finally the hash
table will be -
Comparison of quadratic probing and double hashing

The double hashing requires another hash function whose probing efficiency is
same as some another hash function required when handling random collision.

The double hashing is more complex to implement than quadratic probing. The
quadratic probing is fast technique than double hashing.

Ex. 6.4.3 Give the input {4371, 1323, 6173, 4199, 4344, 9679, 1989} and hash
function X(mod 10), show the results for the following:

i) Open addressing hash table using linear probing

ii) Open addressing hash table using quadratic probing

iii) Open addressing hash table with second hash function h2 (X) = 7 - (X mod 7).

AU: Dec.-18, Marks 15

Sol. i) Open addressing hash table using linear probing :

We assume mod function as mod 10.


4371 mod 10 = 1

1323 mod 10 = 3

6173 mod 10 = 3 collision occurs

Hence by linear probing we will place 6173 at next empty location. That is, at
location 4.

4199 mod 10 = 9

4344 mod 10 = 4 but location 4 is not empty.

Hence we will place 4344 at next empty location i.e. 5,

9679 mod 10 = 9 collision occurs so place at next location at 0. The hash table is of
size 10. Hence we find the next empty location by rolling the table in forward
direction.

1989 mod 10 = 9 collision occurs, so we find the next empty location at index 2.

The hash table will then be


ii) Open addressing hash table using quadratic probing

In quadratic probing we consider the original hash key and then add an arbitrary
polynomial. This sum is then considered for hash function. The hash function will
be

H(Key) = (Key +i2) % me-

where m can be a table size

If we assume m = 10, then the numbers can be inserted as follows -


iii) Open addressing hash table with second hash function

Step 1:

Step 2:
Step 3:
Step 4:
Ex. 6.4.4 What do you understand by collision in hashing? Represent the
following keys in memory using linear probing with or without replacement.
Use modulo (10) as your hashing function: (24, 13, 16, 15, 19, 20, 22, 14, 17, 26,
84, 96)

Sol. Collision in hashing - Refer section 6.4.

i) Linear probing with replacement

We will consider the hash function as modulo (10) for the hash table size 12, that
is from 0 to 11. In linear probing with replacement, we first find the probable
position of the key element using hash function. If the location which we obtain
from hash function is empty then place the corresponding key element at that
location. If the location is not empty and the key element which is present at that
location belongs to that location only then, move down in search of empty slot.
Place the record at the empty slot.
If the location contains a record which does not belong to that location then
replace that record by the current key element. Place the replaced record at some
empty slot, which can be obtained by moving linearly down.

We get the empty location at index 7. Hence 14 is placed at index 7.


Ex. 6.4.5: Consider a hash table with 9 slots. The hash function is h(k) = k mod 9.
The following keys are inserted in the order 5, 28, 19, 15, 20, 33, 12, 17, 10.
Draw the contents of the hash table when the collisions are resolved by

(i) Chaining (ii) Linear probing (iii) Double hashing.

The second hash function h2(x) = 7-(x mod 7).

AU: May-19 Marks 13

Sol.: i) Chaining
Similarly remaining elements can be placed. When collision occurs, double
hashing is applied.

3. Rehashing
Rehashing is a technique in which the table is resized, i.e., the size of table is
doubled by creating a new table. It is preferable if the total size of table is a prime
number. There are situations in which the rehashing is required –

• When table is completely full.

• With quadratic probing when the table is filled half.

• When insertions fail due to overflow.

In such situations, we have to transfer entries from old table to the new table by
recomputing their positions using suitable hash functions.
Consider we have to insert the elements 37, 90, 55, 22, 17, 49 and 87. The table
size is 10 and I will use hash function,
Now this table is almost full and if we try to insert more elements collisions will
occur and eventually further insertions will fail. Hence we will rehash by doubling
the table size. The old table size is 10 then we should double this size for new
table, that becomes 20. But 20 is not a prime number, we will prefer to make the
table size as 23. And new hash function will be
Now the hash table is sufficiently large to accommodate new insertions.

Advantages

1. This technique provides the programmer a flexibility to enlarge the table size if
required.

2. Only the space gets doubled with simple hash function which avoids occurrence
of collisions.

Review Questions

1. Explain the following collision resolution strategies with example.

i) Separate chaining ii) Linear probing iii) Quadratic probing

AU: Dec.-15, Marks 16

2. Explain the following: Rehashing.

AU: May-16, Marks 8

3. Illustrate with example the open addressing and chaining methods of collision
resolution techniques in hashing. AU: May-17, Marks 16

4. Explain open addressing in detail. AU: Dec.-18, Marks 6

5. When do you perform rehashing? Illustrate with example.

AU: May-19, Marks 8

Properties of Good Hash Function


Rules for choosing good hash function

1. The hash function should be simple to compute.

2. Number of collisions should be less while placing the record in the hash table.
Ideally no collision should occur. Such a function is called perfect hash function.
3. Hash function should produce such keys which will get distributed uniformly
over an array.

4. The hash function should depend on every bit of the key. Thus the hash function
that simply extracts the portion of a key is not suitable.

Review Question

1. What are the characteristics of good hashing function?

Collision Handling
AU: Dec.-15, 18, May - 16, 17, 19, Marks 16

Definition: If collisions occur then it should be handled by applying some


techniques, such techniques are called collision handling techniques.

1. Chaining
1. Chaining without replacement

In collision handling method chaining is a concept which introduces an additional


field with data i.e. chain. A separate chain table is maintained for colliding data.
When collision occurs we store the second colliding data by linear probing
method. The address of this colliding data can be stored with the first colliding
element in the chain table, without replacement.

For example consider elements,

131, 3, 4, 21, 61, 6, 71, 8, 9

From the example, you can see that the chain is maintained the number who
demands for location 1. First number 131 comes we will place at index 1. Next
comes 21 but collision occurs so by linear probing we will place 21 at index 2, and
chain is maintained by writing 2 in chain table at index 1 similarly next comes 61
by linear probing we can place 61 at index 5 and chain will be maintained at index
2. Thus any element which gives hash key as 1 will be stored by linear probing at
empty location but a chain is maintained so that traversing the hash table will be
efficient.

The drawback of this method is in finding the next empty location. We are least
bothered about the fact that when the element which actually belonging to that
empty location cannot obtain its location. This means logic of hash function gets
disturbed.
2. Chaining with replacement

The method of chaining without replacement has a drawback of loosing the


meaning of the hash function, to overcome this drawback the method known as
chaining with replacement is introduced. Let us discuss the example to
understand the method. Suppose we have to store following elements:

131, 21, 31, 4, 5

Now next element is 2. As hash function will indicate hash key as 2 but already at
index 2. We have stored element 21. But we also know that 21 is not of that
position at which currently it is placed.

Hence we will replace 21 by 2 and accordingly chain table will be updated. See the
table:
The value -1 in the hash table and chain table indicate the empty location. The
advantage of this method is that the meaning of hash function is preserved. But
each time some logic is needed to test the element, whether it is at its proper
position.

2. Open Addressing
Open addressing is a collision handling technique in which the entire hash table is
searched in systematic way for empty cell to insert new item if collision occurs.

Various techniques used in open addressing are

1. Linear probing

2. Quadratic probing

3. Double hashing

1. Linear probing
When collision occurs i.e. when two records demand for the same location in the
hash table, then the collision can be solved by placing second record linearly
down wherever the empty location is found.

For example

In the hash table given in Fig. 6.4.3 the hash function used is number % 10. If the
first number which is to be placed is 131 then 131 % 10 = 1 i.e. remainder is 1 so
hash key = 1. That means we are supposed to place the record at index 1. Next
number is 21 which gives hash key 1 as 21 % 10 = 1. But already 131 is placed at
index 1. That means collision is occurred. We will now apply linear probing. In this
method, we will search the place for number 21 from location of 131. In this case
we can place 21 at index 2. Then 31 at index 3. Similarly 61 can be stored at 6
because number 4 and 5 are stored before 61. Because of this technique, the
searching becomes efficient, as we have to search only limited list to obtain the
desired number.
Ex. 6.4.1: Implement the hash table and perform collision handling by linear
probing

Sol. :

#include <stdio.h>

#include<conio.h>

void display(int a[ ], int n)

// Displaying complete hash table

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

printf("\n %d %d",i,a[i]);

void Linear_prob(int table[ ], int tsize,int num)

int key = num % tsize;//Computing the hash key using hash function

while (table[key]!= -1)//if empty slot is not found

key (key+1)%tsize;//then move linearly dow in search of empty slot

table[key]=num ;//if empty slot gets then insert the element


display(table, tsize);

int main()

int SIZE = 10;// Size of the hash table

int num;

int hash_table[SIZE];

char ans;

// Initializing the hash table

for (int i = 0; i < SIZE; i++)

hash_table[i] = -1;//-1 indicates empty slot

do

printf("\nEnter The Number: ");

scanf("%d", &num);//This element is to be inserted in hash table

Linear_prob(hash_table,SIZE,num);

printf("\n Do U Wish To Continue? (y/n)");

ans = getch();

}while(ans=='y');

return 0;
}

Output

Enter The Number: 131

0 -1

1 131

2 -1

3 -1

4 -1

5 -1

6 -1

7 -1

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 21

0 -1

1 131

2 21

3 -1

4 -1

5 -1

6 -1
7 -1

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 3

1- 0

1 131

2 21

3 3

4 -1

5 -1

6 -1

7 -1

8 -1

9 -1

Do U Wish To Continue? (y/n)

Enter The Number: 4

0 -1

1 131

2 21

3 3

44
5 -1

6 -1

7 -1

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 5

0 -1

1 131

2 21

33

44

LO

6 -1

7 -1

8 -1

9 -1

Do U Wish To Continue? (y/n)

Enter The Number: 8

0 -1
1

131

2 21

33

44

55

6 -1

7 -1

8 8

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 9

0 -1

1 131

2 21

3 3

4 4

55

6 -1

7 -1

8 8

9 9
Do U Wish To Continue?(y/n)

Enter The Number: 18

0 18

1 131

2 21

3 3

4 4

5 5

6 -1

7 -1

8 8

9 9

Do U Wish To Continue?(y/n)

Enter The Number: 33

0 18

1 131

2 21

3 3

4 4

5 5

6 33

7 -1
8 8

9 9

Do U Wish To Continue?(y/n)

Problem with linear probing

One major problem with linear probing is primary clustering. Primary clustering is
a process in which a block of data is formed in the hash table when collision is
resolved.

For example:

This clustering problem can be solved by quadratic probing.

2. Quadratic probing

Quadratic probing operates by taking the original hash value and adding
successive values of an arbitrary quadratic polynomial to the starting value. This
method uses following formula -
Hi(key) = (Hash(key)+i2)%m

where m can be a table size or any prime number.

For example: If we have to insert following elements in the hash table with table
size 10: 37, 90, 55, 22, 11, 17, 49, 87.

We will fill the hash table step by step

Now if we want to place 17 a collision will occur as 17%10-7 and bucket 7 has
already an element 37. Hence we will apply quadratic probing to insert this record
in the hash table.

Hi(key) = (Hash(key)+i2)%m

we will choose value i = 0, 1, 2, whichever is applicable.

Consider i = 0 then

(17+02) %10 = 7

(17+12) %10 = 8, when i = 1

The bucket 8 is empty hence we will place the element at index 8.


Then comes 49 which will be placed at index 9.

49%10 = 9

Now to place 87 we will use quadratic probing.

(87+0)%10 = 7

(87 + 1)%10 = 8 ... but already occupied

(87 +22)%10 = 1 ... already occupied

(87+32)%10 = 6... this slot is free

We place 87 at 6th index.


It is observed that if we want to place all the necessary elements in the hash table
the size of divisor (m) should be twice as large as total number of elements.

Ex. 6.4.2 Write a C program to implement quadratic probing.

Sol. :

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

void display(int a[], int n)

// Displaying complete hash table

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

printf("\n %d %d",i,a[i]);

void Quadratic_prob(int table[], int tsize,int num)

int key = num % t using size;//computing the hash key mod function

// Insert in the table if there is empty slot

if (table[key] == -1)

table[key] = num;

else.

for (int i = 0; i < tsize; i++)//using formula for quadratic probing

int index = (key + i* i) % tsize;

if (table[index] == -1)//if empty slot is found

{
table[index] break; = num;//then insert element at that index

break;

display(table, tsize);

int main()

int SIZE = 10;// Size of the hash table

int num;

int hash_table[SIZE];

char ans;

// Initializing the hash table

for (int i = 0; i < SIZE; i++)

hash_table[i] = -1;//-1 indicates empty slot

do

printf("\nEnter The Number: ");

scanf("%d", &num);//Number to be inserted in the hash table


Quadratic prob(hash_table,SIZE,num);

printf("\n Do U Wish To Continue?(y/n)");

ans = getch();

while(ans= ='y');

return 0;

Output

Enter The Number: 37

0 -1

1 -1

2 -1

3 -1

4 -1

5 -1

6 -1

7 37

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 90

0 90

1 -1
2 -1

3 -1

4 -1

5 -1

6 -1

7 37

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 55

0 90

1 -1

2 -1

3 -1

4 -1

5 55

6 -1

7 37

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 22


0 90

1 -1

2 22

3 -1

4 -1

5 55

6 -1

7 37

8 -1

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 11

0 90

1 11

2 22

3 -1

4 -1

5 55

6 -1

7 37

8 -1

9 -1
Do U Wish To Continue?(y/n)

Enter The Number: 17

0 90

1 11

2 22

3 -1

4 -1

5 55

6 -1

7 37

8 17

9 -1

Do U Wish To Continue?(y/n)

Enter The Number: 49

0 90

1 11

2 22

3 -1

4 -1

5 55

6 -1

7 37
8 17

9 49

Do U Wish To Continue?(y/n)

Enter The Number: 87

0 90

1 11

2 22

3 -1

4 -1

5 55

6 87

7 37

8 17

9 49

Do U Wish To Continue?(y/n)

3. Double hashing

Double hashing is technique in which a second hash function is applied to the key
when a collision occurs. By applying the second hash function we will get the
number of positions from the point of collision to insert.

There are two important rules to be followed for the second function :

• It must never evaluate to zero.

• Must make sure that all cells can be probed.


The formula to be used for double hashing is

H1(key) = key mod tablesize

H2(key) = M (key mod M)

where M is a prime number smaller than the size of the table.

Consider the following elements to be placed in the hash table of size 10

37, 90, 45, 22, 17, 49, 55

Initially insert the elements using the formula for H1(key).

Insert 37, 90, 45, 22.


Now if 17 is to be inserted then

H1(17) = 17%10 = 7

H2(key) = M - (key%M)

Here M is a prime number smaller than the size of the table. Prime number
smaller than table size 10 is 7.

Hence M = 7

H2(17) = 7 (17%7) = 7 – 3 = 4

That means we have to insert the element 17 at 4 places from 37. In short we
have to take 4 jumps. Therefore the 17 will be placed at index 1.

Now to insert number 55.

H1 (55) 55%10 = 5... collision

H2(55) = 7-(55%7) = 7 - 6 = 1

That means we have to take one jump from index 5 to place 55. Finally the hash
table will be -
Comparison of quadratic probing and double hashing

The double hashing requires another hash function whose probing efficiency is
same as some another hash function required when handling random collision.

The double hashing is more complex to implement than quadratic probing. The
quadratic probing is fast technique than double hashing.

Ex. 6.4.3 Give the input {4371, 1323, 6173, 4199, 4344, 9679, 1989} and hash
function X(mod 10), show the results for the following:

i) Open addressing hash table using linear probing

ii) Open addressing hash table using quadratic probing

iii) Open addressing hash table with second hash function h2 (X) = 7 - (X mod 7).

AU: Dec.-18, Marks 15

Sol. i) Open addressing hash table using linear probing :

We assume mod function as mod 10.


4371 mod 10 = 1

1323 mod 10 = 3

6173 mod 10 = 3 collision occurs

Hence by linear probing we will place 6173 at next empty location. That is, at
location 4.

4199 mod 10 = 9

4344 mod 10 = 4 but location 4 is not empty.

Hence we will place 4344 at next empty location i.e. 5,

9679 mod 10 = 9 collision occurs so place at next location at 0. The hash table is of
size 10. Hence we find the next empty location by rolling the table in forward
direction.

1989 mod 10 = 9 collision occurs, so we find the next empty location at index 2.

The hash table will then be


ii) Open addressing hash table using quadratic probing

In quadratic probing we consider the original hash key and then add an arbitrary
polynomial. This sum is then considered for hash function. The hash function will
be

H(Key) = (Key +i2) % me-

where m can be a table size

If we assume m = 10, then the numbers can be inserted as follows -


iii) Open addressing hash table with second hash function

Step 1:

Step 2:
Step 3:
Step 4:
Ex. 6.4.4 What do you understand by collision in hashing? Represent the
following keys in memory using linear probing with or without replacement.
Use modulo (10) as your hashing function: (24, 13, 16, 15, 19, 20, 22, 14, 17, 26,
84, 96)

Sol. Collision in hashing - Refer section 6.4.

i) Linear probing with replacement

We will consider the hash function as modulo (10) for the hash table size 12, that
is from 0 to 11. In linear probing with replacement, we first find the probable
position of the key element using hash function. If the location which we obtain
from hash function is empty then place the corresponding key element at that
location. If the location is not empty and the key element which is present at that
location belongs to that location only then, move down in search of empty slot.
Place the record at the empty slot.
If the location contains a record which does not belong to that location then
replace that record by the current key element. Place the replaced record at some
empty slot, which can be obtained by moving linearly down.

We get the empty location at index 7. Hence 14 is placed at index 7.


Ex. 6.4.5: Consider a hash table with 9 slots. The hash function is h(k) = k mod 9.
The following keys are inserted in the order 5, 28, 19, 15, 20, 33, 12, 17, 10.
Draw the contents of the hash table when the collisions are resolved by

(i) Chaining (ii) Linear probing (iii) Double hashing.

The second hash function h2(x) = 7-(x mod 7).

AU: May-19 Marks 13

Sol.: i) Chaining
Similarly remaining elements can be placed. When collision occurs, double
hashing is applied.

3. Rehashing
Rehashing is a technique in which the table is resized, i.e., the size of table is
doubled by creating a new table. It is preferable if the total size of table is a prime
number. There are situations in which the rehashing is required –

• When table is completely full.

• With quadratic probing when the table is filled half.

• When insertions fail due to overflow.

In such situations, we have to transfer entries from old table to the new table by
recomputing their positions using suitable hash functions.
Consider we have to insert the elements 37, 90, 55, 22, 17, 49 and 87. The table
size is 10 and I will use hash function,
Now this table is almost full and if we try to insert more elements collisions will
occur and eventually further insertions will fail. Hence we will rehash by doubling
the table size. The old table size is 10 then we should double this size for new
table, that becomes 20. But 20 is not a prime number, we will prefer to make the
table size as 23. And new hash function will be
Now the hash table is sufficiently large to accommodate new insertions.

Advantages

1. This technique provides the programmer a flexibility to enlarge the table size if
required.

2. Only the space gets doubled with simple hash function which avoids occurrence
of collisions.

Review Questions

1. Explain the following collision resolution strategies with example.

i) Separate chaining ii) Linear probing iii) Quadratic probing

AU: Dec.-15, Marks 16

2. Explain the following: Rehashing.

AU: May-16, Marks 8

3. Illustrate with example the open addressing and chaining methods of collision
resolution techniques in hashing. AU: May-17, Marks 16

4. Explain open addressing in detail. AU: Dec.-18, Marks 6

5. When do you perform rehashing? Illustrate with example.

AU: May-19, Marks 8

Applications of Hashing
1. In compilers to keep track of declared variables.

2. For online spelling checking the hashing functions are used.rw ni song piller 3.
Hashing helps in Game playing programs to store the moves made.

4. For browser program while caching the web pages, hashing is used.
Two Marks Questions with Answers

Q.1 What is hashing?

AU: May-16

Ans. :

Hashing is a technique of storing the elements directly at the specific location in


the hash table. The hashing makes use of hash function to place the record at its
position. Using the same hash function the data can be retrieved directly from the
hash table.

Q.2 List out the various techniques of hashing.

Ans. :

Various techniques of hashing are -

1. Division method 2. Mid square method 3. Multiplicative hash function

4. Digit folding 5. Digit analysis.

Q.3 What is uniform hash function ?

Ans. : An uniform hash function is one that equally distributes data items over the
whole hash table data structure.

Q.4 What is rehashing ?

AU: Dec.-15

Ans. :
Rehashing is a technique in which the table is resized. That means the size of the
table is doubled by creating a new table. The total size of the table is usually a
prime number. Following are the situations in which the rehashing is required -

1. When table is completely full.

2. With quadratic probing the table is filled half.

3. When insertions fail due to overflow.

Q.5 What is collision in hashing ?

Ans. : The situation in which the hash function returns the same hash key for more
than one record is called collision.

Q.6 What is overflow in hashing?

Ans. : The situation in which there is no room for a new pair in the hash table is
called overflow.

Q.7 What are the characteristics of good hashing function?

Ans. : Refer section 6.3

Q.8 What is the major problem in linear probing ?

Ans. : One major problem in linear probing is primary clustering. Primary


clustering is the process in which a block of data is formed in the hash table when
collision is resolved.

Q.9 What are the advantages of rehashing ?


Ans. : Following are the advantages -

1. This technique provides the programmer a flexibility to enlarge the table size if
required.

2. Only the space gets doubled with simple hash function which avoids occurrence
of collisions.

Q.10 What is the advantage of chained hash table over open addressing
scheme ?

Ans. : The deletion of particular record from the hash function becomes easier.

Q.11 State some major drawback of chaining.

Ans. : Requirement of additional data structure is the major drawback of chaining.

Q.12 Specify the hashing technique in which the table size can be changed.

Ans. : The rehashing is a hashing technique in which the table size can be changed.

Q.13 What will be the position of the number 3111 in a hash table, when the mid
square method is applied ? (The table size is 1000)

Ans. : The position will be 783 because (3111)2 = 9678321.

Q.14 Which hash function maintains the record in order of hash field values ?

Ans. : The folding method maintains the record in order of hash field values.
Q.15 Enlist the conditions in which the rehashing is required.

Ans. : The rehashing is required in following conditions -

1. Table is completely full.

2. Insertion fails due to overflowing.

3. When there is a need to transfer the contents from old hash table to new hash
table.

Q.16 What do you understand by collision resolution by chaining ?

Ans. : When collision happens we create a new memory location outside the
existing table and use a chain to link to the new memory location.

Q.17 Use of pointer is in ----- hashing technique.

Ans. : chaining.

Q.18 What are the advantages and disadvantages of separate chaining and
linear probing?

Ans. : 1) Separate chaining:

Advantages:

i) It is simple to implement.

ii) Hash table never fills and we can add elements in the linked list fashion.

iii) The meaning of hash function can be preserved.

Disadvantages:

i) It requires extra space to maintain links.


ii) If the chain becomes too long then it takes more time to search an element.

iii) There may be wastage of space as some parts of hash table are never used.

2) Linear probing:

Advantage:

1) It is faster due to locality of references.

Disadvantage:

1) It forms primary clustering. Hence only some part of hash table remain occupied
bim and other part remains vaccant.
Sorting and Searching Techniques

Unit V
Chapter 7
Sorting and Searching Techniques

Syllabus
Insertion Sort - Quick Sort - Heap Sort - Merge Sort - Linear Search - Binary
Search.

Contents
7.1 Sorting

7.2 Insertion Sort ……… May-19, ……. Marks 7

7.3 Quick Sort

7.4 Heap Sort …….. Dec.-07,08,09,10,11,12,2 ……… May-10,11,12, … Marks


16

7.5 Merge Sort …… Dec.-15,18, May-19, Marks 13

7.6 Searching May-16,17, Dec.-18,19, …. Marks 13

7.7 Two Marks Questions with Answers

Sorting
• Definition: Sorting is a technique for arranging data in particular order.

• Order of Sorting : Order means the arrangement of data. The sorting order can
be ascending or descending. The ascending order means arranging the data in
increasing order whereas descending order means arranging the data in
decreasing order.

• Internal Sorting: This is a type of sorting technique in which data resides on


main memory of computer.

• External Sorting: This is a sorting technique in which there is a huge amount of


data and it resides on secondary devices (For example Hard disk, Magnetic tape
and so on) while sorting.

• Various techniques of internal sorting are -

1. Insertion sort

2. Selection sort

3. Shell sort

4. Bubble sort

5. Quick sort

6. Merge sort

7. Radix sort Stor

• Passes: While sorting the elements in some specific order, there is lot of
arrangement of elements. The phases in which the elements are moving to acquire
their proper position is called passes.

Applications of Sorting

1. The sorting is useful in database applications for arranging the data in desired
order.

2. In the dictionary like applications the data is arranged in sorted order.

3. For searching the element from the list of elements, the sorting is required.

4. For checking the uniqueness of the element the sorting is required.


5. For finding the closest pair from the list of elements the sorting is required.

Insertion Sort
AU May-19, Marks 7

In this method the elements are inserted at their appropriate place. Hence is the
name insertion sort. Let us understand this method with the help of some example

3. More efficient than most other simple O (n2) algorithms such as selection sort or
bubble sort.

4. This is a stable (does not change the relative order of equal elements).

5. It is called in-place sorting algorithm (only requires a constant amount O(1) of


extra memory space). The in-place sorting algorithm is an algorithm in which the
input is overwritten by output and to execute the sorting method it does not require
any more additional space.

Let us now see the implementation of this method using C.

Ex. 7.2.1: C program sorting elements using insertion sort.

Sol. :

/************************************

Implementation of insertion sort

************************************/

#include<stdio.h>

#include<conio.h>

void main()

{
int A[10],n,i;

void Insert_sort(int A[10], int n);

clrscr();

printf("\n\t\t Insertion Sort");

printf("\n How many elements are there?");

scanf("%d",&n);

printf("\n Enter the elements\n");

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

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

Insert_sort(A,n);

getch();

void Insert_sort(int A[10], int n)

int i,j,temp;

for(i=1;i<=n-1;i++)

temp=A[i];

j=i-1;

while((j>=0)&&(A[j]>temp))

Alj+1]=A[j];
j=j-1; smel

}.

A[j+1]=temp;

printf("\n The sorted list of elements is...\n");

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

printf("\n%d",A[i]);

Output

'Insertion Sort

How many elements are there?5

Enter the elements

30

20

10

40

50

The sorted list of elements is...

10

20

30

40
50

Logic Explanation

For understanding the logic of above C program consider a list of unsorted


elements as,

Then the control moves to while loop. As j >= 0 and A[j] > temp is True, the while
loop will be executed.

Now since j >= 0 is false, control comes out of while loop.

Then list becomes,


Thus we have scanned the entire list and inserted the elements at corresponding
locations. Thus we get the sorted list by insertion sort.

Ex. 7.2.2: Write a routine for insertion sort. Sort the following sequence using
insertion sort. 3, 10, 4, 2, 8, 6, 5, 1.

AU May-19, Marks 7

Sol. : We will store the elements in an array.

The process will start from the first element.


Quick Sort
• Quick sort is a technique in which the array is divided into two sub arrays based
on the element called pivot.

• The left subarray is having the elements less than pivot and right subarray is
having the elements greater than pivot.

• Thus array is partitioned repeatedly and the elements in subarray are sorted.

• Finally these subarrays are combined to get a final sorted list.


• In merge sort the division of array is based on the positions of array elements, but
in quick sort this division is based on actual value of the element. Consider an
array A[i] where i is ranging from 0 to n-1 then we can formulize the division of
array elements as

Let us understand this algorithm with the help of some example.

Example

Step 1:
Algorithm

The quick sort algorithm is performed using following two important functions –
Quick and partition. Let us see them -

Algorithm Quick(A[0...n-1],low,high)

//Problem Description: This algorithm performs sorting of

//the elements given in Array A[0...n-1]

//Input: An array A[0...n-1] in which unsorted elements are

//given. The low indicates the leftmost element in the list

//and high indicates the rightmost element in the list

//Output: Creates a sub array which is sorted in ascending

//order

if(low<high)then

//split the array into two sub arrays

m ← partition(Allow...high])// m is mid of the array

Quick(Allow...m-1])

Quick (A[mid+1...high])

In above algorithm call to partition algorithm is given. The partition performs


arrangement of the elements in ascending order. The recursive quick routine is for
dividing the list in two sub lists. The pseudo code for Partition is as given below -

Algorithm Partition (Allow...high])

//Problem Description: This algorithm partitions the

//subarray using the first element as pivot element

//Input: A subarray A with low as left most index of the

//array and high as the rightmost index of the array.


//Output: The partitioning of array A is done and pivot

//occupies its proper position. And the rightmost index of

//the list is returned

pivot ← A[low]

i ← low

j ← high+1

while(i<=j) do

while(A[i] <= pivot) do

i ← i+1

while(A[j] >= pivot) do

j ← j-1;

if(i<=j) then

swap(A[i],A[j])//swaps A[i] and A[j]

swap(A[low],A[j])//when i crosses j swap A[low] and A[j]

return j//rightmost index of the list

The partition function is called to arrange the elements such that all the elements
that are less than pivot are at the left side of pivot and all the elements that are
greater than pivot are all at the right of pivot. In other words pivot is occupying its
proper position and the partitioned list is obtained in an ordered manner.

C Program

/**************************************************
Program to sort the elements in ascending order using Quick Sort.

**************************************************/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#define SIZE 10

void Quick(int A[SIZE], int, int);

int partition(int A[SIZE], int, int);

void swap(int A[SIZE], int *,int *);

int n;

int main()

int i;

int A[SIZE];

clrscr();

printf("\n\t\t Quick Sort Method \n");

printf("\n Enter Total numbers to sort: ");

scanf("%d", &n);

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

printf("\nEnter %dth number: ",i+1);

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

Quick (A,0,n-1);

printf("\n\n\t Sorted Array Is: \n");

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

printf("\t%d ",A[i]);

getch();

return 0;

/*

This function is to sort the elements in a sublist

*/

void Quick(int A[SIZE], int low,int high)

int m,i;

if(low<high)

m=Partition (A,low,high);//setting pivot element

Quick(A,low,m-1);//splitting of list

Quick (A,m+1,high);//splitting of list

/*
This function is to partition a list and decide the pivot

element

*/

int Partition(int A[SIZE], int low,int high)

int pivot =A[low],i=low,j=high;

while(i<=j)

while(A[i] <= pivot)

i++;

while(Alj]>pivot)

j--;

if(i<j)

swap(A,&i,&j);

swap(A,&low,&j);

return j;

void swap(int A[SIZE], int *i,int *j)

int temp;

temp=A[*i];
A[*i]=A[*j];

inom A[*j]=temp;

Output

Quick Sort Method

Enter Total numbers to sort : 8

Enter 1th number: 50

Enter 2th number: 30

Enter 3th number: 10

Enter 4th number: 90

Enter 5th number: 80

Enter 6th number: 20

Enter 7th number: 40

Enter 8th number: 70

Sorted Array Is:

10 20 30 40 50 70 80 90

Ex. 7.3.1 Consider following numbers, sort them using quick sort. Show all
passes to sort the values in ascending order

25, 57, 48, 37, 12, 92, 86, 33

Sol. : Consider the first element as a pivot element.


Now, if A[i] < Pivot element then increment i. And if A[j] > Pivot element then
decrement j. When we get these above conditions to be false, Swap A[i] and A[j]

After pass 1:
Ex. 7.3.2 Sort the following data to ascending order using quick sort. Show all
passes with Pivot: 17, 8, -9, 2, 0, -5, 7, 20, 11, 15

Sol. : Consider the first element as pivot.

17 8 -9 2 0 -5 7 20 11 15

Pivot i j

If A [i] < A [pivot] increment i. Similarly if A [j] > A [pivot] decrement j.

When we get these above conditions to be false, Swap A [i] and and A [j].

17 8 -9 2 0 -5 7 15 11 20

Swap A [Pivot] and A[j]


Heap Sort
AU: Dec.-07,08,09,10,11,12, May-10,11,12, Marks 16

In this section we will learn "What is heap?" and "How to construct heap?" and
heap sort.

Definition: Heap is a complete binary tree or a almost complete binary tree in


which every parent node be either greater or lesser than its child nodes.

Heap can be min heap or max heap.

A Max heap is a tree in which value of each node is greater than or equal to the
value of its children nodes.

For example:

A Min heap is a tree in which value of each node is less than or equal to value of
its children nodes.
For example:

Parent being greater or lesser in heap is called parental property. Thus heap has
two important properties.

Heap Sort

Heap sort is a sorting method discovered by J. W. J. Williams. It works in two


stages.

1. Heap construction: First construct a heap for given numbers.

2. Deletion of maximum key: Delete root key always for (n - 1) times to


remaining heap. Hence we will get the elements in decreasing order. For an array
implementation of heap, delete the element from heap and put the deleted element
in the last position in array. Thus after deleting all the elements one by one, if we
collect sin buitenoo lliw W these deleted elements in an array starting from last
index of array. We get a list of elements in a ascending order.

ADT for heap sort

Instances: Heap is a tree data structure denoted by either a maxheap or minheap.

Operations :

1. Create_heap(): This is the first task to be performed for sorting the elements
using heap sort. The parent node must be either maximum of its children or
minimum than its children. That means a maxheap or minheap should be
constructed..

2. Swap(): The root node must be swapped with the node at the last position in
tree.

3. Delete_node(): The node at the last position in the heap tree must be deleted.

4. Insert_Q(): The deleted element from the heap must be inserted in the priority
queue.

5. Delete_Q(): The element can be deleted from the priority queue by the front
end, so that a sorted list can be obtained.

Ex. 7.4.1: State algorithm to sort elements of a given array in ascending order
using heap sort. Sort the following numbers using heap sort: 48, 0, -1, 82, 108,
72, 54.

Sol. Algorithm :

Step 1: Construct the max heap from given set of elements.


Step 2: Swap the root key with the last node key of the heap.

Step 3: Delete the last node and store its key at the end of the array.

Step 4: Heapify the remaining heap structure.

Step 5: Repeat step 2 to 4 until the last remaining node.

Step 6: Delete the last node and store it at the end of the array.

Step 7: Print all the elements of the array. This will display the elements in sorted
order.

Consider, 48, 0, 1, 82, 108, 72, 54.

Stage I : Construct heap

We will construct max heap as follows –

Step 1: Insert 48 Step 2: Insert 0 Step 3: Insert - 10 tail s 199 9W


Note that in this heap structure, every parent node has greater value than its child
nodes.

Stage II: Delete root node and heapify repeatedly

Step 1 a: Delete root


Ex. 7.4.2: State algorithm to sort elements of a given array in ascending order
using heapsort. Sort the following numbers using heapsort in descending order:

38, 10, 11, 72, 98, 62, 44.

Sol. :

Step I: Construction of heap

We will construct a min heap


Step II: Deletion of root node and heapify repeatedly

Step 1 a Delete root


Review Question

1. Explain heap sort with example.

Merge Sort
AU: Dec.-15,18, May-19, Marks 13

Merge sort is a sorting algorithm in which array is divided repeatedly. The sub
arrays are sorted independently and then these subarrays are combined together to
form a final sorted list.

Merge sort on an input array with n elements consists of three steps:

Divide : Partition array into two sub lists s1 and s2 with n/2 elements each. ano?

Conquer : Then sort sub list s1 and sub list $2.

Combine : merge s1 and s2 into a unique sorted group.

Ex. 7.5.1: Consider the following elements for sorting using merge sort

70, 20, 30, 40, 10, 50, 60

Sol.: Now we will split this list into two sublists.


Algorithm

Algorithm MergeSort(int A[0...n-1],low,high)

//Problem Description: This algorithm is for

//sorting the elements using merge sort

//Input: Array A of unsorted elements, low as //beginning

//pointer of array A and high as end pointer of array A

//Output: Sorted array A[0...n-1]

if(low < high)then

{
mid-low+high)/2 //split the list at mid

MergeSort (A,low,mid) //first sublist

MergeSort (A,mid+1,high) //second sublist

Combine(A,low,mid,high) //merging of two sublists

Algorithm Combine(A[0...n-1],low, mid, high)

k ← low; //k as index for array temp

i ← low;//i as index for left sublist of array A

j ← mid+1 //j as index for right sublist of array A

while(i<= mid and j <= high)do

if(A[i]<=A[j])then

//if smaller element is present in left sublist

//copy that smaller element to temp array

temp[k] A[i]

i ← i+1

k ← k+1

else //smaller element is present in right sublist


{

//copy that smaller element to temp array

temp[k] ← A[j]

j ← j+1

k ← k+1

//copy remaining elements of left sublist to temp

while(i<=mid)do

temp[k] A[i]

i ← i+1

k ← k+1

//copy remaining elements of right sublist to temp

while(j<=high)do

temp[k] A[j]

j ← j+1

k ← k+1

Logic Explanation
To understand above algorithm consider a list of elements as

Then we will first make two sublists as

Let us see the combine operation more closely with the help of some example.
Consider that at some instance we have got two sublits 20, 30, 40, 70 and 10, 50,
60, then
Finally we will copy all the elements of array temp to array A. Thus array A
contains sorted list.

C Function

void MergeSort(int A[10], int low, int high)

int mid;

void Combine(int A[10]; int low, int mid, int high);

if(low high)

Mid = (low+high)/2; //split the list at mid

MergeSort(A,low,mid); //first sublist

MergeSort(a,mid+1,high); //second sublist

Combine(A,low,mid,high); //merging of two sublists

void Combine(int A[10], int low, int mid, int high)

int i,j,k;

int temp[10];
k=low;

i=low;

j=mid+1;

while(i<= mid && j <= high)

if(A[i]<=A[j])

temp[k]=A[i];

i++;

k++;

else

temp[k] =A[j];

j++;

k++;

while(i<=mid)

temp[k]=A[i];

i++;
k++;

while(j<=high)

temp[k] =A[j];

j++;

k++;

//copy the elements from temp array to A

(apid > woul

for(k=low;k<=high;k++)

A[k]=temp[k];

C Program

/**********************************

This program is for performing Merge Sort.

**********************************/

#include<conio.h>

#include<stdio.h>

#include<stdlib.h>

int n;

void main()
{

int i,low,high;

int A[10];

void MergeSort(int A[10], int low,int high);

void Display(int A[10]);

clrscr();

printf("\n\t\t Merge Sort \n");

printf("\n Enter the length of list :");

scanf("%d",&n);

printf("\n Enter list elements :");

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

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

low=0;

high=n-1;

MergeSort(A,low,high);

Display(A);

getch();

/*

This function is to split the list into sublists

*/

void MergeSort(int A[10], int low,int high)


{

int mid;

void Combine(int A[10], int low,int mid,int high);

if(low high)

mid (low+high)/2;//split the list at mid

MergeSort(A,low,mid);//first sublist

MergeSort (A,mid+1,high);//second sublist

Combine(A,low,mid,high);//merging of two sublists

/* This function is for merging the two sublists

*/

void Combine(int A[10], int low,int mid,int high)

int i,j,k;

int temp[10];

k=low;

i=low;

j=mid+1;

while(i<= mid && j <= high)

{
if(A[i]<=A[j]) ← We compare elements from left sublist and right sublist. If
element in the left sublist is lesser than the element in the right sublist then copy
that smaller element of left sublist to temp array

temp[k]=A[i];

i++;

k++; ← We compare elements from left sublist and right sublist. If element in the
right sublist is lesser than the element in the left sublist then copy that smaller
element of right sublist to temp array

else

temp[k]=A[j];

j++;

k++;

while(i<=mid) ← Reached at the end of right sublist and elements of left sublist
are remaining, then copy the remaining elements of left sublist to temp

temp[k]=A[i];

i++;

k++;

}
while(j<=high) ← Reached at the end of left sublist and elements of right sublist
are remaining, then copy the remaining elements of right sublist to temp

temp[k]=A[j];

j++;

k++;

//copy the elements from temp array to A

for(k=low;k<=high;k++)

A[k]=temp[k];

/* function to display sorted array */

void Display(int A[10])

int i;

printf("\n\n The Sorted Array Is ...\n");

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

printf("%d\t",A[i]);

Output

Merge Sort

Enter the length of list :7


Enter list elements:

70

20

30

40

10

50

60

The Sorted Array Is... 10

20 30 40 50 60 70

Ex. 7.5.2 Sort the following numbers using merge sort algorithm 11, 8, 55, 22,
33, 27, 62, 35, 71. Obtain the worst case and average case time complexity.

AU: Dec.-15, 18, Marks 13

Sol. :
Review Question

1. Write a function to perform merge sort. Give example.

AU May-19, Marks 6

Searching
AU: May-16,17, Dec.-18,19, Marks 13

• insure art sota of banist . When we want to find out particular record efficiently
from the given list of elements then there are various methods of searching that
element. These methods are called searching methods. Various algorithms based
on these searching methods are known as searching algorithms.
• The basic characteristic of any searching algorithm is -

i. It should be efficient

ii. Less number of computations must be involved in it.

iii. The space occupied by searching algorithms must be less.

• The most commonly used searching algorithms are -

i. Sequential or linear search

ii. Indexed sequential search

iii. Binary search

• The element to be searched from the given list is called the key element. Let us
discuss various searching algorithms.

1. Linear Search
• Linear search or sequential search is technique in which the given list of
elements is scanned from the beginning. The key element is compared with every
element of the list. If the match is found the searching is stopped otherwise it will
be continued to the end of the list.

• Although this is a simple method, there are some unnecessary comparisons


involved in this method. Detse

• The time complexity of this algorithm is O(n). The time complexity will increase
linearly with the value of n.

• For higher value of n sequential search is not satisfactory solution.

• Example
From the above Fig. 7.6.1 the array is maintained to store the students record.
The record is not sorted at all. If we want to search the student's record whose
roll number is 12 then with the key-roll number we will see the every record
whether it is of roll number We can obtain such a record at Array [4] location.

Let us implement the sequential search using C program

'C' Program:

/******************************************

Program to perform the linear search operation on some number of elements.

********************************************/

#include<stdio.h>

#include<conio.h>

#define MAX 10

int a[MAX],n,i; .

/*
The create Function

Input :none

Output:none

Called By: main

Calls:none

*/

void create()

printf("\n How Many Elements");

scanf("%d", &n);

printf("\n Enter The Elements");

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

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

/*

The display Function

Input:none

Output:none

Called By:main

Calls:none

*/
void display()

printf("\n The Elements Are");

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

printf("\n%d",a[i]);

/*

The search function

Input:key element- which is to be searched

Output:the status

Called By:main

Calls:none

*/

search(int k)

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

if(a[i]==k)

return 1;

return 0;

}
void main()

int status,key;

clrscr();

create();

display();

printf("\n Enter the Element Which You wish to Search ");

scanf("%d",&key);

status=search(key);

if (status = =1)

printf("\n The Element is Present");

else

printf("\n The Element Is Not Found");

getch();

/************End Of Program**********************/

How Many Elements 5

Enter The Elements 10

100

1000

10000
The Elements Are

10

100

1000

10000

Enter the Element Which You wish to Search 99

The Element Is Not Found

How Many Elements 5

Enter The Elements 10

100

1000

10000

The Elements Are

10

100

1000

10000

Enter the Element Which You wish to Search 100

The Element is Present


Advantages of Linear searching

1. It is simple to implement.

2. It does not require specific ordering before applying the method.

Disadvantage of Linear searching

1. It is less efficient.

2. Binary Search
Definition: Binary search is a searching technique in which the elements are
arranged in a sorted order and each time mid element is compared with the key
element recursively.

Example: The necessity of this method is that all the elements should be sorted.
So let us take an array of sorted elements.

Step 1: Now the key element which is to be searched is = 99 .. key = 99.

Step 2: Find the middle element of the array. Compare it with the key

if middle? Key
i.e. if 42 ? 99

if 42 < 99 search the sublist 2

Now handle only sublist 2. Again divide it, find mid of sublist 2

if middle? key

i.e. if 99? 99

So match is found at 7th position of array i.e. at array [6]

Thus by binary search method we can find the element 99 present in the given list
at array [6]th location.

Non Recursive Binary Search Program

/*************************************

Implementation of non recursive Binary Search algorithm bir

****************************************/

beb #include<stdio.h>

hluode atremals adj


#include<conio.h>

#define SIZE 10

int n;

void main()

int A[SIZE],KEY,i,flag;

int BinSearch(int A[SIZE], int KEY);

clrscr();

YSTIA

printf("\n How Many elements in an array?");

scanf("%d", &n);

printf("\n Enter The Elements");

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

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

printf("\n Enter the element which is to be searched");

scanf("%d", &KEY);

flag=BinSearch(A,KEY);

if(flag= =-1)

printf("\n The Element is not present");

else

printf("\n The element is at A[%d] location",flag);

getch();
}

int BinSearch(int A[SIZE], int KEY)

int low,high,m;

low=0;

high-n-1;

while(low<=high)

m=(low+high)/2; //mid of the array is obtained

if(KEY= =A[m])

return m;

else if(KEY <A[m])

high-m-1; //search the left sub list

else

low=m+1; //search the right sub list

return-1; //if element is not present in the list

Output (Run 1)

How Many elements in an array? 6

Enter The Elements

10
20

30

40

50

60

Enter the element which is to be searched 50

The element is at A[4] location

(Run 2)

How many elements in an array?

Enter The Elements

10

20

30

40

50

Enter The Elements which is to be searched 80

The Element is not present

Algorithm For Binary Search Using Recursive definition :

1. if(low>high)

2. return

3. mid =(low+high)/2;

4. if(x==a[mid])
5. return (mid);

6. if(x<a[mid])

7. search for x in a[low] to a[mid-1];

8. else

9. search for x in a[mid+1] to a[high];

Recursive Binary Search Program

/*******************************

Program for searching the number by Binary Search. The list of numbers should
be in ascending order. The program also shows the location at which the number
is present(if at all)

**********************************/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

#define size 10

/*

The binsearch Function

Input:array of elements,key element,

starting and ending element of the list

i.e.a,x,low and high.

Output:location at which the number can be present

Called By:main
Calls:itself

*/

int binsearch(int a[], int x,int low,int high)

int mid;

if(low>high)

return(-1);

mid = (low+high)/2;

if(x ==a[mid])

return(mid);

else if(x<a[mid])

binsearch(a,x,low,mid-1);

else

binsearch(a,x,mid+1,high);

/*

The main Function

Input:none

Output:none

Called By:O.S.

Calls:binsearch

*/
void main(void)

int n,i,low,high,a[size],key,ans;

clrscr();

printf("\n\t\t\t Binary Search Method ");

printf("\n Enter the total number of elements");

scanf("%d", &n);

printf("\nEnter the list of elements");

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

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

low = 0;

high = n-1;

printf("\n Enter the element which you want to search");

scanf("%d", &key);

ans binsearch(a,key,low,high);

if(ans!= -1)

printf("\n The number %d is present in the list at

location %d", key, ans+1);

else

printf("\n The number is not present in the list");

getch();

}
/************** End Of Program******************/

Output

Binary Search Method

Enter the total number of elements 5

Enter the list of elements

10

20

30

40

50

Enter the element which you want to search 40

The number 40 is present in the list at location 4

Searching method

Linear search

Binary search

Time complexity

O(n)

O(nlogn)
3. Linear Search Vs. Binary Search

Review Questions

1. Explain binary searching.

AU: May-16, Marks 8 but not bool

2. Write the difference between binary search and linear search.

3. Write a C function to find the element using linear search.

4. Write a C program to search a number with the given set of numbers using
binary search.

AU: May-17, Marks 8

5. Distinguish between linear search and binary search. State and explain the
algorithms for both the search with example.

6. Write an algorithm for binary search with suitable example.


Two Marks Questions with Answers

Q.1 What is the importance of sorting and searching techniques ?

Ans.: Sorting is useful for arranging the data in desired order. After sorting the
required element can be located easily.

Searching technique is essential for locating the position of the required element
from the heap of data.

Q.2 Give any two applications of sorting.

Ans. :

1. The sorting is useful in database applications for arranging the data in desired
order.

2. In the dictionary like applications the data is arranged in sorted order.

3. For searching the element from the list of elements, the sorting is required.

Q.3 What do you understand by the term sorting?

Ans. : Sorting is a mechanism of arranging the data in particular order.

Q. 4 What is the need for sorting?

Ans. : The sorting is useful for –

1. Searching the desired data efficiently. 2. Responding to the queries.


Q. 5 What is the meaning of sort key?

Ans. : Sort key is a field in the record based on which the sorting is conducted.

Q.6 Name the slowest and fastest sorting technique.

Ans. : Bubble sort is a slowest sorting technique and quick sort is the fastest
sorting technique.

Q.7 Differentiate between internal and external sorting.

AU: Dec.-14, 19

Ans. : Internal sorting: This is a type of sorting technique in which data resides on
main memory of computer.

External sorting: This is a sorting technique in which there is huge amount of data
and it resides on secondary storage devices while sorting.

Q.8 Explain the meaning of the term passes in context with sorting.

Ans. : While sorting the elements in some specific order, there is lot of
arrangement of elements. The phases in which the elements are moving to acquire
their proper position is called passes.

Q.9 What is ascending and descending order?

Ans.

Ascending order is the sorting order in which the elements are arranged from low
value to high value. In other words it is called increasing order. For example: 10,
20, 30, 40.
Descending order is the sorting order in which the elements are arranged from high
value to low value. In other words it is called decreasing order. For example: 40,
30, 20, 10.

Q.10 What is the basic principle behind the quick sort ?

Ans. :

Sorting and Searching Techniques The division of the list into two sublists(which
is called partition) and then sorting each sublist independently. This is the basic
principle used in quick sort. Based on the value of pivot element, the list is
subdivided.

Q.11 Enlist four internal sorting techniques.

Ans. : Following are some internal sorting techniques –

1. Insertion sort

2. Selection sort

3. Shell sort

4. Bubble sort

Q.12 What do you mean by heap?

Ans. : Ans. Heap is a complete binary tree or almost complete binary tree in which
every parent node be either greater or lesser than the parent node.

Q.13 What are the two stages in which heap sort is conducted ?
Ans. : Following are the two stages in which the heap sort is conducted - W Heap
construction: The heap structure is build for given list of elements

Deletion of maximum key: In this phase the root key is deleted for n 1 times.

Q.14 The way a card game player arranges his cards as he picks them one by
one, is an example of ----------

Ans. : insertion sort

Q.15 A sort which iteratively passes through a list to exchange the first element
with any element less than it and then repeats with a new first element is
called……..

Ans. : selection sort

Q.16 Explain why binary search can not be performed using linked list ?

Ans. : In binary search algorithm, the mid element needs to be searched. If binary
search is implemented using arrays then by simply saying a[mid] we can access the
middle element of an array in constant time. But for finding the mid element of a
linked list we have to execute separate algorithm and it can not be done in constant
time. Thus implementing binary search using linked list is very inefficient way.
Hence it is not preferred to implement a binary search using linked list.

Q.17 What do you understand by the term searching?

Ans. Searching means locating the position of the desired record or key element
from the given database.

Q.18 What are the advantages of binary search over the linear search?
Ans. : Binary search is an efficient searching method than the linear search. Using
this method, the list is subdivided each time and only sublist is scanned for locating
the key value.

Q.19 List the sorting algorithms which uses logarithmic time complexity

Ans. : The sorting algorithms which use the logarithmic time complexity are -
Quick sort and merge sort.

Q.20 Compare linear search and binary search.

Ans. :

AU: Dec.-15, May-19

You might also like