0% found this document useful (0 votes)
125 views84 pages

Cpds r20 Material

The document provides information about the author H. Ateeq Ahmed and his qualifications. It includes an acknowledgement section thanking various people. It then outlines the topics and page numbers that will be covered in the R20 I B.Tech syllabus, including introduction to C language, data structures, linked lists, trees, graphs, and searching and sorting algorithms.

Uploaded by

Kvsrit Aicte
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
125 views84 pages

Cpds r20 Material

The document provides information about the author H. Ateeq Ahmed and his qualifications. It includes an acknowledgement section thanking various people. It then outlines the topics and page numbers that will be covered in the R20 I B.Tech syllabus, including introduction to C language, data structures, linked lists, trees, graphs, and searching and sorting algorithms.

Uploaded by

Kvsrit Aicte
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

As per JNTUA

Specially Prepared for Engineering Students

R20 I B.Tech
Syllabus

By
H. Ateeq Ahmed, M.Tech, (Ph.D)
Asst. Professor of CSE,
Kurnool.

Common to CSE, ECE, EEE, CE, ME NOT FOR


SALE
ABOUT AUTHOR

H. ATEEQ AHMED is currently Pursuing Ph.D in CSE at


JNTUA, Anantapur. Completed M.Tech from Samskruti College of
Engineering & Technology, JNTUH, Hyderabad. B.Tech from Safa College
of Engineering & Technology, JNTUA, Anantapur, Currently he is working
as an Asst. Professor in the Department of CSE at Dr. KVSR Institute of
Technology, Kurnool, A.P. He has more than 12 years of teaching
experience. He has vast subject knowledge in the field of Computer networks
& organization, Network security, Software design & testing, Operating
Systems, Programming in C, Java & Python as well as Data mining.

His dynamic and illustrative approach towards the subjects helps the
students to enrich their skills in their academics which can help them to
achieve success in job career.

He always believes in real time approach to solve various problems


and expect the same with his students which can help them to understand
their subject in an easy and efficient manner.

He has prepared many materials of different subjects for engineering


students which can help them to prepare for exams in an easy method.

Finally, we expect our students to acquire as much knowledge as


possible and convert his dynamic teaching into their individual success.
ACKNOWLEDGEMENT

First I thank Almighty God for giving me the knowledge to learn and teach
various students.

It’s my privilege to thanks my parents as without their right guidance and


support, this book will be a dream for me.

Finally, I thank my colleagues and friends for helping me during tough


period of time.

“Interest & Focus are two KEYWORDS of a perfect programmer”

“The goal of this Course is to find the next C Programmer in YOU

in a magical way…”

H. Ateeq Ahmed, M.Tech, (Ph.D),

Mobile no: 994 8 37 8 994,

E-mail ID: [email protected]

Website: engineeringdrive.blogspot.com

My YouTube Channel: Engineering Drive


SYLLABUS & CONTENTS

Topics Page No.


UNIT-I
Introduction to C Language –
C language elements,
variable declarations and data types, 1 - 19
operators and expressions,
decision statements - If and switch statements,
loop control statements - while, for, do-while statements,
arrays.
UNIT-II
Functions,
types of functions,
Recursion and argument passing,
pointers,
storage allocation,
pointers to functions, 20 - 43
expressions involving pointers,
Storage classes – auto, register, static, extern,
Structures,
Unions,
Strings,
string handling functions,
and Command line arguments.
UNIT-III
Data Structures,
Overview of data structures,
stacks and queues,
representation of a stack,
stack related terms,
operations on a stack,
implementation of a stack,
evaluation of arithmetic expressions, 44 – 53
infix, prefix, and postfix notations,
evaluation of postfix expression,
conversion of expression from
infix to postfix,
recursion,
queues - various positions of queue,
representation of queue,
insertion, deletion, searching operations.
UNIT-IV
Linked Lists –
Singly linked list,
dynamically linked stacks and queues, 54 – 60
polynomials using singly linked lists, using circularly linked lists,
insertion, deletion and searching operations,
doubly linked lists and its operations,
circular linked lists and its operations.
UNIT-V
Trees –
Tree terminology,
representation,
Binary trees, representation,
binary tree traversals.
Binary tree operations,
Graphs –
graph terminology,
graph representation,
elementary graph operations, 61 – 79
Breadth First Search (BFS) and Depth First Search (DFS),
connected components,
spanning trees.
Searching and Sorting –
sequential search, binary search,
exchange (bubble) sort,
selection sort,
insertion sort.
Department of CSE 1

UNIT-I
INTRODUCTION TO C LANGUAGE
• C is a structured programming language.
• It was developed by M. Dennis Ritchie in 1972 at Bell Laboratories.
• It is considered a high-level language because it allows the programmer to concentrate
on the problem at hand and not worry about the machine that the program will be
using.
• While many languages claim to be machine independent, C is one of the closest to
achieving that goal.
• That is another reason why it is used by software developers whose applications have
to run on many different hardware platforms.

Structure of a C Program
Before we study the basic building blocks of the C programming language, let us look at a
bare minimum C program structure so that we can take it as a reference in the upcoming
chapters.
Hello World Example
A C program basically consists of the following parts −
• Preprocessor Commands
• Functions
• Variables
• Statements & Expressions
• Comments
Let us look at a simple code that would print the words "Hello World" −
#include <stdio.h>

void main()
{
/* my first program in C */
printf("Hello, World!");

getch();
}

Let us take a look at the various parts of the above program −


• The first line of the program #include <stdio.h> is a preprocessor command, which
tells a C compiler to include stdio.h file before going to actual compilation.
• The next line void main() is the main function where the program execution begins.
• The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the program.
• The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 2

Variables
“A variable is the name given to memory location to store data value in it.”
Unlike constant, the value of a variable can be changed.
A variable name must be chosen in such a way that it improves the readability of a program.

Syntax
Data_type var_name=var_value;

Example
int x=10;
The above variable ‘x’ contains value 10 and it is of integer data type.

Data types
A data type is used to indicate the type of value stored in a variable.
A data type indicates the following
§ Type of value stored in a variable
§ Memory allocated for data value
§ Type of operations that can be performed on the variable.
Data types are classified in to the following categories.
1. Integer data types
2. Floating point data types
3. Characters

1. Integer data types


It is used to store whole numbers.
The size of the integer depends on the word length of a machine i.e. it can be either 16 or 32
bits.

Signed Integers:
Signed integers are those integers which uses 15 bits for storing the magnitude of a number
and I bit for storing its sign.
The left most bit i.e. 16th bit is used for storing the sign.
1-> Negative number
0-> Positive number

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 3

Example:
signed int x=10;
0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
Magnitude
Sign
0-> Positive number
Unsigned Integers
Unsigned integers uses all 16 bits to store the magnitude.
Data type Size (bytes) Format Specifier Range
int 2 or 4 %d -32768 to 32767 or
-21474836648 to 21474836648
unsigned int 2 %u 0 to 65535
signed int 2 %d -32768 to 32767
short int 2 %hd -32768 to 32767
unsigned short 2 %hu 0 to 65535
int
signed short int 2 %hd -32768 to 32767
long int 4 %ld -21474836648 to 21474836648
unsigned long 4 %lu 0 to 4294967295
int
signed long int 4 %ld -21474836648 to 21474836648

Example Program
Write a C program to display the value of an integer variable.
#include<stdio.h>
#include<conio.h>

void main()
{
int a=10;
clrscr();
printf("Value of a=%d",a);
getch();
}

Expected Output
Value of a=10

2. Floating point data types:


These are used to store real numbers i.e. decimal point numbers or numbers with fractional
values.
Data type Size (bytes) Format Specifier Range
float 4 %f -3.4e-38 to 3.4e+38
double 8 %lf 1.7e-308 to 1.7e+308
long double 10 %Lf 3.4e-4932 to 1.1e+4932

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 4

Example Program
Write a C program to display the value of a floating variable.
#include<stdio.h>
#include<conio.h>

void main()
{
float a=2.5;
clrscr();
printf("Value of a=%f",a);
getch();
}
Expected Output
Value of a=2.500000

3. Character data type:


This data type is used to store characters.
Each character has an equivalent ASCII value.
The format specifier used with character data type is %c.
Data type Size (bytes) Format Specifier Range
char or signed 1 %c -128 to 127
char
unsigned char 1 %c 0 to 255

Example Program
Write a C program to display a single character.
#include<stdio.h>
#include<conio.h>

void main()
{
char ch=’A’;
clrscr();
printf("Character=%c",ch);
getch();
}
Expected Output
Character=A

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 5

Operators
Operators are C tokens which can join together individual constants, variables, array elements
etc.
C operators are classified into the following categories.
§ Arithmetic operators
§ Relational operators
§ Logical operators
§ Assignment operators
§ Increment and Decrement operators
§ Conditional operators
§ Bitwise operators
§ Special operators

Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division

Relational operators
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

Logical operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Assignment operators
It is used to assign the result of an expression to a variable.
It is denoted as ‘=’.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 6

Increment and Decrement operators


Operator Meaning
a++ Post increment
++a Pre increment
a-- Post decrement
--a Pre decrement

Example Program
Write a C program to show the use of increment & decrement operators.
#include<stdio.h>
#include<conio.h>

void main()
{
int x,y;
x=5;
y=5;
clrscr();

x++;
printf("x=%d",x);

y--;
printf("\ny=%d",y);

getch();
}
Expected Output
x=6
y=4

Conditional operator
It is also known as ternary operator.
Syntax
exp1?exp2:exp3;

The value of exp1 is evaluated first, If it is true, value of exp2 is evaluated otherwise exp3 is
evaluated.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 7

Example Program
Write a C program to find the biggest of two numbers using Conditional operator.
#include<stdio.h>
#include<conio.h>

void main()
{
int a,b,big;
clrscr();
a=20;
b=10;
big=(a>b)?a:b;
printf("Big number is %d",big);
getch();
}
Expected Output
Big number is 20

Bitwise operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR(XOR)
~ One’s Complement
<< Shift left
>> Shift right
Special operators
(i) Comma operator(,)
It is used to separate the variables
Eg: int a,b,c;

(ii) sizeof operator


It return the no. of bytes the operand occupies.
Eg: sizeof(operand)


C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 8

Control Statements
Control statements are the statements that allow the programmer to specify the next statement
that must be executed depending on some conditions.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 9

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 10

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 11

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 12

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 13

Example Programs for Selection statements

(i) Simple if
#include<stdio.h>
#include<conio.h>

void main()
{
int age;
age=20;
clrscr();
if(age>=18)
{
printf("Eligible for voting.");
}
getch();
}

Expected Output
Eligible for voting.

(ii) if else
#include<stdio.h>
#include<conio.h>

void main()
{
int age;
age=15;
clrscr();
if(age>=18)
{
printf("Eligible for voting.");
}
else
{
printf("Not eligible for voting.");
}
getch();
}

Expected Output
Not eligible for voting.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 14

(iii) else if ladder


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

void main()
{
float per;
per=76;
clrscr();
if(per>=70 && per<=100)
{
printf("Distinction");
}
else if(per>=60 && per<70)
{
printf("First Class");
}
else if(per>=50 && per<60)
{
printf("Second Class");
}
else
{
printf("Failed");
}
getch();
}

Expected Output
Distinction

(iv) switch
#include<stdio.h>
#include<conio.h>
void main()
{
int day;
day=5;
clrscr();
switch(day)
{
case 0:
printf("SUNDAY");
break;

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 15

case 1:
printf("MONDAY");
break;

case 2:
printf("TUESDAY");
break;

case 3:
printf("WEDNESDAY");
break;

case 4:
printf("THURSDAY");
break;

case 5:
printf("FRIDAY");
break;

case 6:
printf("SATURDAY");
break;

default:
printf("Invalid Day number");
}

getch();
}

Expected Output
FRIDAY

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 16

ARRAYS
“An Array is collection of similar elements that are stored in sequential memory locations.”
• An ordinary variable can store only one value at a time where as an array can store
multiple values of same type.
• An array is a collection of variables of the same type that are referred to through a
common name.
• A specific element in an array is accessed by an index. In C, all arrays consist of
contiguous memory locations.
• The lowest address corresponds to the first element and the highest address to the last
element.
• Arrays can have from one to several dimensions.
• The most common array is the string, which is simply an array of characters
terminated by a null.
Array Initialization methods

One Dimensional Arrays


The general form for declaring a one-dimensional array is
type var_name[size];

Like other variables, arrays must be explicitly declared so that the compiler can
allocate space for them in memory. Here, type declares the base type of the array, which is
the type of each element in the array, and size defines how many elements the array will hold.
For example, to declare a 100- element array called balance of type float, use this statement:

float balance[100];

Example
int a[5];
a

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

65516 65518 65520 65522 65524

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 17

• Here, int specifies the type of the variable, just as it does with ordinary variables and
‘a’ specifies the name of the variable.
• The [5] however is new. The number 5 tells how many elements of the type int will
be in our array. This number is often called the ‘dimension’ of the array.
• The bracket ( [ ] ) tells the compiler that we are dealing with an array.
• a[0] refers to the first element in the array whereas the whole number 65516 is its
address in memory.

Array Initialization
• So far we have used arrays that did not have any values in them to begin with.
• We managed to store values in them during program execution.
• Let us now see how to initialize an array while declaring it.
Example
int a[5] ={2,4,6,8,10};
or
int a[]={2,4,6,8,10};
a
a[0] a[1] a[2] a[3] a[4]
2 4 6 8 10
65516 65518 65520 65522 65524

Array elements are referred to using subscript; the lowest subscript is always 0 and
the highest subscript is (size –1). If you refer to an array element by using an out-of-range
subscript, you will get an error. You can refer to any element as a[0], a[1], a[2], etc

Thus, an array is a collection of similar elements. These similar elements could be all
ints, or all floats, or all chars, etc. Usually, the array of characters is called a ‘string’,
whereas an array of ints or floats is called simply an array. Remember that all elements of
any given array must be of the same type. i.e. we cannot have an array of 10 numbers, of
which 5 are ints and 5 are floats.

Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={2,4,6,8,10};
clrscr();
printf("\nFirst element=%d",a[0]);
printf("\nFifth element=%d",a[4]);
getch();
}
Expected Output
First element=2
Fifth element=10

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 18

Two dimensional arrays


Two dimensional arrays are often expressed and analyzed as
matrix of rows and columns.

Declaration & Initialization:


Syntax:
Data-type array-name[row-size][column-size]={ {row1 elements},{row2 elements},…};

Number of elements in array= (row-size * column size)


Example
int a[3][2]={{2,4}, {6,8}, {10,12}};
Column Index

Row Index

• First element of the array is referred as a[0][0]


• Sixth element is referred as a[2][1].
• Total number of elements in the above array is 6 i.e. (3*2=6).
• The array arrangement shown in matrix form is only conceptually true.
• This is because memory doesn’t contain rows and columns.
• In memory whether it is a one-dimensional or a two-dimensional array the array
elements are stored in one continuous chain.

The arrangement of array elements of a two-dimensional array in memory is shown below:

Memory Representation:
a[0][0] a[0][1] a[1][0] a[1][1] a[2][0] a[0][1]
2 4 6 8 10 12
65516 65518 65520 65522 65524 65526
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][2]={{2,4},{6,8},{10,12}},i,j;
clrscr();
printf("The array elements are");

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 19

for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
{
printf("\n%d",a[i][j]);
}
}
getch();
}
Expected Output
The array elements are
2
4
6
8
10
12

*******

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 20

UNIT-II
Functions
Definition:
A function is a self-contained block of statements that perform some specific task for the
program.

§ Functions are used to provide modularity to the software. By using functions, you can
divide complex tasks into small manageable tasks.
§ The use of functions can also help avoid duplication of work. For example, if you
have written the function for calculating the square root, you can use that function in
multiple programs

Functions are classified into two categories.


(1) Built in functions or Standard library functions
(2) User defined functions.

Built in Functions:
§ As the name suggests, library functions are nothing but commonly required functions
grouped together and stored in a Library.
§ This library of functions is present on the disk and is written for us by people who
write compilers for us.
§ Almost always a compiler comes with a library of standard functions.

Examples:
printf(), scanf() etc.

User defined functions:


User defined functions are those functions that are used by the user according to the
requirement of the program.

Syntax:
return-type function-name(parameter-list)
{
local variables;
statements;
}

Advantages of functions:

§ A function provides modularity and readability to the software.


§ To define the function, you have to define the function name, the return data type and
the formal parameters.
§ It is recommended to declare a function prototype before using a function.
§ If the function does not return any value, then you have to set the return data type as
void.
§ A call to a function should be compatible with the function definition.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 21

Example Program
//Using userdefined function

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

void message(); // function prototype

void main()
{
clrscr();
printf("How r u?");
message();
getch();
}

void message() // function definition


{
printf("\nI am fine!");
}

Expected Output
How r u?
I am fine!

Explanation

§ Here, main( ) itself is a function and through it we are calling the function message(
). What do we mean when we say that main( ) ‘calls’ the function message( )? We
mean that the control passes to the function message( ).
§ The activity of main( ) is temporarily suspended; it falls asleep while the message( )
function wakes up and goes to work.
§ When the message( ) function completes the execution of statements, the control
returns to main( ), which comes to life again and begins executing its code at the
exact point where it left off.
§ Thus, main( ) becomes the ‘calling’ function, whereas message( ) becomes the
‘called’ function.
Types of Functions:
Depending up on the arguments and return values,
functions are classified in to the following four types.
(a) Functions with no arguments and no return values
(b) Functions with arguments and no return values
(c) Function with no arguments and return values
(d) Function with arguments and return values.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 22

(a) Functions with no arguments and no return values

void sum(); //function prototype

void sum() // function definition


{
int a,b,c;
a=10;
b=20;
c=a+b;
printf("Sum=%d",c);
}

void main()
{
clrscr();
sum();
getch();
}
Expected Output
Sum=30

(b) Functions with arguments and no return values


void sum(int a,int b); //function prototype

void sum(int a,int b) // function definition


{
int c;
c=a+b;
printf("Sum=%d",c);
}

void main()
{
int a,b;
clrscr();
a=10;
b=20;
sum(a,b);
getch();
}
Expected Output
Sum=30

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 23

(c) Function with no arguments and return values


int sum(); //function prototype

int sum() // function definition


{
int a,b,c;
a=10;
b=20;
c=a+b;
return(c);
}

void main()
{
int res;
clrscr();
res=sum();
printf("Sum=%d",res);
getch();
}
Expected Output
Sum=30

(d) Function with arguments and return values


int sum(int a,int b); //function prototype

int sum(int a,int b) // function definition


{
int c;
c=a+b;
return(c);
}

void main()
{
int x,y,res;
clrscr();
x=10;
y=20;
res=sum(x,y);
printf("Sum=%d",res);
getch();
}
Expected Output
Sum=30

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 24

Passing Arguments to Functions


There are two ways in which we can pass the parameters
to the function.
(1) Call by value
(2) Call by reference
Let us discuss each of them briefly.
(a) Call by value:
“The technique of passing the value of the variable as parameter to the
function is known as “Call by value”.
By now we are well familiar with how to call functions. But, if you observe carefully,
whenever we called a function and passed something to it we have always passed the ‘values’
of variables to the called function. Such function calls are called ‘calls by value’. By this
what we mean is, on calling a function we are passing values of variables to it.

Example Program
//call by value

void swap(int x,int y);

void swap(int x,int y) //x & y are formal parameters


{
int z;
z=x;
x=y;
y=z;
printf("\nSwapped values are %d %d",x,y);
}

void main()
{
int a=10,b=20;
clrscr();
printf("\nValues before swap are %d %d",a,b);

swap(a,b); //a & b are actual parameters

printf("\nValues after swap are %d %d",a,b);


getch();
}

Expected Output
Values before swap are 10 20
Swapped values are 20 10
Values after swap are 10 20

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 25

(2) Call by reference:


The technique of passing the address of the variable as a parameter to
the function is known as a “Call by reference”.
We have also learnt that variables are stored somewhere in memory.
So instead of passing the value of a variable, we pass its location (also called address) of the
variable to a function. Hence this technique is Call by reference.

Example Program
//call by reference

void swap(int *x,int *y);


void swap(int *x,int *y) //x & y are formal parameters
{
int *z;
*z=*x;
*x=*y;
*y=*z;
printf("\nSwapped values are %d %d",*x,*y);
}
void main()
{
int a=10,b=20;
clrscr();
printf("\nValues before swap are %d %d",a,b);
swap(&a,&b); //a & b are actual parameters
printf("\nValues after swap are %d %d",a,b);
getch();
}

Expected Output
Values before swap are 10 20
Swapped values are 20 10
Values after swap are 20 10

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 26

Recursion
In C, it is possible for the functions to call themselves.
A function is called ‘recursive’ if a statement within the body of a function calls the same
function.
Thus recursion is the process of defining something in terms of itself.

Let us now see a simple example of recursion. Suppose we want to calculate the factorial
value of an integer. As we know, the factorial of a number is the product of all the integers
between 1 and that number. For example, 4 factorial is 4 * 3 * 2 * 1. This can also be
expressed as 4! = 4 * 3! where ‘!’ stands for factorial. Thus factorial of a number can be
expressed in the form of itself. Hence this can be programmed using recursion as follows.

Example Program

int fact(int n); // function prototype

int fact(int n)
{
int f;
if(n==0 || n==1)
return(1);

f=fact(n-1)*n; //fact() is recursive function


return(f);
}

void main()
{
int n,res;
clrscr();
n=5;
res=fact(n);
printf("\nFactorial=%d",res);
getch();
}

Expected Output
Factorial=120

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 27

Pointers
“A Pointer is a variable that can store the address of another variable”.

Syntax
Data-type *variable;

Example
int *i;
In the above declaration, ‘*’ indicates that ‘i’ is a pointer variable.

Example Program
//Program to show the use of pointer
#include<stdio.h>
#include<conio.h>

void main()
{
int a=10,*ptr;
clrscr();
ptr=&a; // address of a is stored in ptr
printf("Address of a is %u",ptr); // displaying the address of a
printf("\nValue of a is %d",*ptr); // displaying the value of a
getch();
}

Memory Representation

a ptr

10 65524

Addressà 65524 65522

The expression &a gives the address of the variable a.

This address can be collected in a variable, by saying,


ptr = &a ;

But remember that ptr is not an ordinary variable like any other integer variable.
It is a variable that contains the address of other variable (a in this case).
Since ptr is a variable the compiler must provide it space in the memory.

Expected Output
Address of a is 65524
Value of a is 10

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 28

Expressions involving Pointers


Like normal variables, pointers can also be used to perform various arithmetic operations like
addition, subtraction etc.

//Program to show the use Arithmetic operations on pointers


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,*res,*ptr1,*ptr2;
clrscr();
printf("Enter any two numbers:");
scanf("%d%d",&a,&b);
ptr1=&a;
ptr2=&b;

*res=*ptr1+*ptr2; // addition
printf("\nSum=%d",*res);

*res=*ptr1-*ptr2; // subtraction
printf("\nDifference=%d",*res);

*res=*ptr1**ptr2; // multiplication
printf("\nProduct=%d",*res);

*res=*ptr1/(*ptr2); // division
printf("\nDivision=%d",*res);

*res=*ptr1%*ptr2; // mod
printf("\nRemainder=%d",*res);
getch();
}

Expected Output
Enter any two numbers:
20
10

Sum=30
Difference=10
Product=200
Division=2
Remainder=0

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 29

Pointers to functions
“A pointer to function is a variable that can store the address of functions in c language”.
Along with storing the address of a variable, a pointer has the ability to store the address of
functions that are used in the program.

Example Programs
(1)
//Pointer to built in function
#include<stdio.h>
#include<conio.h>
void main()
{
int (*ptr)(); // declaration of a pointer to function variable
ptr=&clrscr;
(*ptr)();
printf("\nAddress of clrscr()=%u",ptr);
getch();
}

Expected Output
Address of clrscr()=2813

(2)
//Pointer to user defined function
#include<stdio.h>
#include<conio.h>
int fun();
void main()
{
int (*ptr)();
clrscr();
ptr=&fun;
(*ptr)();
printf("\nAddress of fun() is %u",ptr);
printf("\nValue of fun() is %d",(*ptr)());
getch();
}
int fun()
{
return(10);
}

Expected Output
Address of fun() is 697
Value of fun() is 10

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 30

Storage Classes
To fully define a variable one needs to mention not only its ‘type’ but also its ‘storage class’.
In other words, not only do all variables have a data type, they also have a ‘storage class’.
A variable name identifies some physical location within the computer where the string of
bits representing the variable’s value is stored. There are basically two kinds of locations in a
computer where such a value may be kept— Memory and CPU registers. It is the variable’s
storage class that determines in which of these two locations the value is stored.
A variable’s storage class tells us:

§ Where the variable would be stored.

§ What will be the initial value of the variable, if initial value is not specifically
assigned.(i.e. the default initial value).

§ What is the scope of the variable; i.e. in which functions the value of the variable
would be available.

§ What is the life of the variable; i.e. how long would the variable exist.

There are four storage classes in C:

(a) Automatic storage class

(b) Register storage class

(c) Static storage class

(d) External storage class

Let us examine these storage classes one by one.

(a) Automatic storage class


The features of a variable defined to have an automatic storage class are as under:

Storage − Memory.

Default initial value − An unpredictable value, which is often called a garbage value.

Scope − Local to the block in which the variable is defined.

Life − Till the control remains within the block in which the variable is
defined.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 31

Example Program
void main( )
{
auto int i;
clrscr();
printf("%d,i) ;
getch();
}
The above program shows how an automatic storage class variable is
declared, and the fact that if the variable is not initialized it contains a garbage value.

(b) Register storage class


The features of a variable defined to be of register storage class are as under:

Storage - CPU registers.

Default initial - Garbage value.


value
Scope - Local to the block in which the variable is defined.

Life - Till the control remains within the block in which the variable is
defined.

A value stored in a CPU register can always be accessed faster than the one that is stored in
memory. Therefore, if a variable is used at many places in a program it is better to declare its
storage class as register. A good example of frequently used variables is loop counters. We
can name their storage class as register.

Example Program
void main( )
{
register int i;
clrscr();
printf("%d",i);
getch();
}

Here, even though we have declared the storage class of i as register, we cannot say for sure
that the value of i would be stored in a CPU register. Why? Because the number of CPU
registers are limited, and they may be busy doing some other task. What happens in such an
event... the variable works as if its storage class is auto.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 32

(c) Static storage class


The features of a variable defined to have a static storage class are as under:

Storage − Memory.

Default initial value − Zero.

Scope − Local to the block in which the variable is defined.

Life − Value of the variable persists between different function calls.

Let us now compare the two programs and their output given below to understand the
difference between the automatic and static storage classes

The above programs consist of two functions main( ) and increment( ). The function
increment( ) gets called from main( ) thrice. Each time it increments the value of i and prints
it. The only difference in the two programs is that one uses an auto storage class for variable
i, whereas the other uses static storage class.
Like auto variables, static variables are also local to the block in which they are declared.
The difference between them is that static variables don’t disappear when the function is no
longer active. Their values persist. If the control comes back to the same function again the
static variables have the same values they had last time around.
C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 33

(d) External storage class


The features of a variable whose storage class has been defined as external are as follows:

Storage − Memory.

Default initial value − Zero.

Scope − Global.

Life − As long as the program’s execution doesn’t come to an end.

External variables differ from those we have already discussed in that their scope is global,
not local. External variables are declared outside all functions, yet are available to all
functions that care to use them.

Example Program

int x = 21;
void main( )
{
extern int y ;
printf ( "\n%d %d", x, y ) ;
}
int y = 31 ;

Here, x and y both are global variables. Since both of them have been defined outside all the
functions both enjoy external storage class. Note the difference between the following:

extern int y ;
int y = 31 ;

Here the first statement is a declaration, whereas the second is the definition. When we
declare a variable no space is reserved for it, whereas, when we define it space gets reserved
for it in memory. We had to declare y since it is being used in printf( ) before it’s definition
is encountered. There was no need to declare x since its definition is done before its usage.
Also remember that a variable can be declared several times but can be defined only once.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 34

Structures
• We have seen earlier how ordinary variables can hold one piece of information and
how arrays can hold a number of pieces of information of the same data type.
• These two data types can handle a great variety of situations.
• But quite often we deal with entities that are collection of dissimilar data types.

For example,
suppose you want to store data about a book.
You might want to store its name (a string), its price (a float) and number of pages in it (an
int).

If data about say 3 such books is to be stored, then we can follow two approaches:

(a) Construct individual arrays, one for storing names, another for storing prices and still
another for storing number of pages.
(b) Use a structure variable.

• In the first approach, the program becomes more difficult to handle as the number of
items relating to the book go on increasing.
• For example, we would be required to use a number of arrays, if we also decide to
store name of the publisher, date of purchase of book, etc.
• To solve this problem, C provides a special data type—the structure.

Structure
• A structure contains a number of data types grouped together.
• These data types may or may not be of the same type.
• Unlike arrays which can store elements of same data type, a structure can hold data of
different data types.

Declaring a Structure
The general form of a structure declaration statement is given below:

Syntax
struct structure name
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
......
......
};

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 35

Example
struct book
{
char name ;
float price ;
int pages ;
};

The above statement defines a new data type called struct book. Each variable of this data
type will consist of a character variable called name, a float variable called price and an
integer variable called pages.
Once the new structure data type has been defined one or more variables can be declared to
be of that type. For example the variables b1, b2, b3 can be declared to be of the type struct
book, as,

struct book b1, b2, b3 ;

This statement sets aside space in memory. It makes available space to hold all the elements
in the structure—in this case, 7 bytes—one for name, four for price and two for pages.
These bytes are always in adjacent memory locations.

If we so desire, we can combine the declaration of the structure type and the structure
variables in one statement.
For example,

struct book
{
char name ;
float price ;
int pages ;
};
struct book b1, b2, b3 ;

(or)

struct book
{
char name ;
float price ;
int pages ;
} b1, b2, b3 ;

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 36

Initialization of structures
• Like primary variables and arrays, structure variables can also be initialized where
they are declared.
• The format used is quite similar to that used to initiate arrays.
struct book
{
char name;
float price ;
int pages ;
};
struct book b1 = { ‘A’, 130.00, 550 } ;
struct book b2 = { ‘B’, 150.80, 800 } ;

Example Program
void main()
{
struct book
{
char name ;
float price ;
int pages ;
};

struct book b1 = { 'B', 130.00, 550 } ;


clrscr();

printf ( "Name= %c", b1.name ) ;


printf ( "\nPrice = %f", b1.price ) ;
printf ( "\nPages = %d", b1.pages ) ;
getch();
}

Expected Output
Name=B
Price=130.00
Pages=550

Memory Representation
Actually, the structure elements are stored in memory as shown below

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 37

Union
§ Like structure, a union can hold data belonging to different data types but it hold only
one object at a time.
§ In the structure each member has its own memory locations whereas, members of
unions have same memory locations.
§ The union requires bytes that are equal to the number of bytes required for the largest
member.
§ For example, if the union contains char, integer and float then the number of bytes
reserved in the memory is 4 bytes (i.e. the size of float).
§ Unlike structure members which can be initialized all at the same time, only one
union member should be initialized at a time.

Syntax
The syntax of union is similar to the structure which is shown below
union union-name
{
union element 1 ;
union element 2 ;
union element 3 ;
......
......
};
Let us now observe the difference between union and structure by using the
following program.

Example Program
//To show the difference between structure & union

struct student1 // structure


{
int rno;
char grade;
};

union student2 //union


{
int rno;
char grade;
};
C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 38

void main()
{
struct student1 s={25,'A'}; // initialization of structure members at a time
union student2 u;
clrscr();

printf("\nRollno=%d",s.rno);
printf("\nGrade=%c",s.grade);

u.rno=30; // initialization of union member 1


printf("\nRollno=%d",u.rno);
u.grade='B'; // initialization of union member 2
printf("\nGrade=%c",u.grade);

printf("\nSize of Structure=%d Bytes",sizeof(s)); // displaying size of structure


printf("\nSize of Union=%d Bytes",sizeof(u)); // displaying size of union
getch();
}

Example Program
Rollno=25
Grade=A
Rollno=30
Grade=B
Size of Structure=3 Bytes
Size of Union=2 Bytes

In the above, the size of structure is sum of the sizes of all its
members i.e. int & char which is (2+1)=3 bytes whereas the size of union is the size of the
member which belongs to largest data type i.e. int which is of 2 bytes.

STRINGS
A string is defined as an array of characters.
Strings are terminated by the special character ‘\0’; this is called a null character or null
terminator.

Declaration & Initialization


When you declare the string, you should ensure that you should have sufficient room for the
null character.
The null terminator has ASCII value 0.

For example,
char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '\0' } ;

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 39

• Each character in the array occupies one byte of memory and the last character is
always ‘\0’. What character is this? It looks like two characters, but it is actually only
one character, with the \ indicating that what follows it is something special. ‘\0’ is
called null character.
• Note that ‘\0’ and ‘0’ are not same. ASCII value of ‘\0’ is 0, whereas ASCII value of
‘0’ is 48.
• Note that the elements of the character array are stored in contiguous memory
locations.
• The below figure shows the way a character array is stored in memory.

A string can also be initialized in the following way

char name[ ] = "HAESLER" ;


In the above declaration ‘\0’ is not necessary. C inserts
the null character automatically.

Example Program
void main( )
{
char name[ ] = "CSE" ;
clrscr();
printf ( "%s", name ) ; // The %s used in printf( ) is a format specification for printing out a string
getch();
}

Expected Output
CSE

void main()
{
char name[25] ;
clrscr();
printf ( "Enter your name:" ) ;
scanf ( "%s", &name ) ;
printf ( "\nHello %s!", name ) ;
getch();
}

Expected Output
Enter your name:Ateeq
Hello Ateeq!

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 40

• Note that the declaration char name[25] sets aside 25 bytes under the array name[ ],
whereas the scanf( ) function fills in the characters typed at keyboard into this array
until the enter key is hit.
• Once enter is hit, scanf( ) places a ‘\0’ in the array.
• Naturally, we should pass the base address of the array to the scanf( ) function.
• scanf( ) is not capable of receiving multi-word strings.
• Therefore names such as ‘Computer Science’ would be unacceptable.
• The way to get around this limitation is by using the function gets( ).

The usage of functions gets( ) and its counterpart puts( ) is shown below.
Example Program
//puts and gets

void main()
{
char name[25] ;
clrscr();
printf ("Enter your full name: ") ;
gets (name); // accepts the string
puts (name); // displays the string
getch();
}
Expected Output
Enter your full name: H. Ateeq Ahmed
H. Ateeq Ahmed

• puts( ) can display only one string at a time (hence the use of two puts( ) in the
program above). Also, on displaying a string, unlike printf( ), puts( ) places the
cursor on the next line.
• Though gets( ) is capable of receiving only one string at a time, the plus point with
gets( ) is that it can receive a multi-word string.

String Handling Functions

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 41

• Out of the above list we shall discuss the functions strlen( ), strcpy( ), strcat( ) &
strcmp( ), since these are the most commonly used functions.
• This will also illustrate how the library functions in general handle strings.
• Let us study these functions one by one.

strlen( )
• This function counts the number of characters present in a string.
• Its usage is illustrated in the following program.

Example Program
//to calculate length of string

void main()
{
char str[]="Computer";
int l;
clrscr();
l=strlen(str);
printf("\nLength=%d",l);
getch();
}
Expected Output
Length=8

strcpy( )
• This function copies the contents of one string into another.
• The base addresses of the source and target strings should be supplied to this function.

strcat( )
• This function concatenates the source string at the end of the target string.
• For example, “Computer” and “Science” on concatenation would result into a string
“ComputerScience”.

Example Program
//strcpy & strcat
void main()
{
char *str;
char *str1="Computer",*str2=" Science";
clrscr();
strcpy(str,str1);
strcat(str,str2);
printf("\n%s",str); // or puts(str);
getch();
}
C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 42

Expected Output
Computer Science

strcmp( )
• This is a function which compares two strings to find out whether they are same or
different.
• The two strings are compared character by character until there is a mismatch or end
of one of the strings is reached, whichever occurs first.
• If the two strings are identical, strcmp( ) returns a value zero.
• If they’re not, it returns the numeric difference between the ASCII values of the first
non-matching pairs of characters.

Example Program
//strcmp
void main()
{
char *str1,*str2;
int res;
clrscr();
printf("Enter string1:");
gets(str1);
printf("\nEnter string2:");
gets(str2);
res=strcmp(str1,str2);
if(res==0)
printf("\nStrings are equal");
else
printf("\nStrings are not equal");
getch();
}

Expected Output
Enter string1:Computer
Enter string2:Computer
Strings are equal

Command Line Arguments


• In environments that support C, there is a way to pass command-line arguments or
parameters to a program when it begins executing.
• When main is called, it is called with two arguments.
• The first (conventionally called argc, for argument count) is the number of command-
line arguments the program was invoked with.
• The second (argv, for argument vector) is a pointer to an array of character strings that
contain the arguments, one per string.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 43

Example Program

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


{
int a,b,c;
clrscr();
a=atoi(arg[1]); // atoi() converts string to number
b=atoi(arg[2]);
c=a+b;
printf("\nSum=%d",c);
getch();
}

Expected Output
C:\TC>sum 10 20
Sum=30

Explanation
In the above output, the three arguments are sum, 10 and 20.
By default, the argument “sum” is stored in arg[0] whereas 10 and 20 are stored in arg[1],
arg[2] respectively.
The argument in the main i.e argc counts the number of arguments.

*******

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 44

UNIT-III
DATA STRUCTURES
• Data Structure can be defined as the group of data elements which provides an
efficient way of storing and organising data in the computer so that it can be used
efficiently.
• Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc.
• Data Structures are widely used in almost every aspect of Computer Science i.e.
Operating System, Compiler Design, Artificial intelligence, Graphics and many more.
• Data Structures are the main part of many computer science algorithms as they enable
the programmers to handle the data in an efficient way.
• It plays a vital role in enhancing the performance of a software or a program as the
main function of the software is to store and retrieve the user’s data as fast as possible

Types of Data Structures


Data Structures can be classified into the following two categories.
1. Linear Data Structures
2. Non Linear Data Structures

Linear Data Structures:


§ A data structure is called linear if all of its elements are arranged in the linear order.
§ In linear data structures, the elements are stored in non-hierarchical way where each
element has the successors and predecessors except the first and last element.
Examples
Arrays, Stacks, Queues, Linked Lists.

Non Linear Data Structures:


§ This data structure does not form a sequence i.e. each item or element is connected
with two or more other items in a non-linear arrangement.
§ The data elements are not arranged in sequential structure.
Examples
Trees, Graphs.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 45

STACKS
• Stack is an abstract data type with a bounded(predefined) capacity.
• It is a simple data structure that allows adding and removing elements in a particular
order.
• Every time an element is added, it goes on the top of the stack and the only element
that can be removed is the element that is at the top of the stack, just like a pile of
objects.

Basic features of Stack

1. Stack is an ordered list of similar data type.


2. Stack is a LIFO (Last in First out) structure or we can say FILO(First in Last out).
3. push() function is used to insert new elements into the Stack and pop() function is used to
remove an element from the stack. Both insertion and removal are allowed at only one
end of Stack called Top.
4. Stack is said to be in Overflow state when it is completely full and is said to be
in Underflow state if it is completely empty.

Implementation of Stack Data Structure


Stack can be easily implemented using an Array or a Linked List. Arrays are quick, but are
limited in size and Linked List requires overhead to allocate, link, unlink, and deallocate, but
is not limited in size.
Here we will implement Stack using array.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 46

Algorithm for PUSH operation

1. Check if the stack is full or not.


2. If the stack is full, then print error of overflow and exit the program.
3. If the stack is not full, then increment the top and add the element.

Algorithm for POP operation

1. Check if the stack is empty or not.


2. If the stack is empty, then print error of underflow and exit the program.
3. If the stack is not empty, then print the element at the top and decrement the top.

Below we have a simple C program implementing stack data structure while following the
object oriented programming concepts.

Position of Top Status of Stack

-1 Stack is Empty

0 Only one element in Stack

N-1 Stack is Full

N Overflow state of Stack

Applications of Stack
The simplest application of a stack is to reverse a word. You push a given word to stack -
letter by letter - and then pop letters from the stack.
There are other uses also like:
1. Parsing
2. Expression Conversion (Infix to Postfix, Postfix to Prefix etc)

QUEUES
Queue is also an abstract data type or a linear data structure, just like stack data structure, in
which the first element is inserted from one end called the REAR(also called tail), and the
removal of existing element takes place from the other end called as FRONT(also
called head).
This makes queue as FIFO (First in First Out) data structure, which means that element
inserted first will be removed first.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 47

Which is exactly how queue system works in real world. If you go to a ticket counter to buy
movie tickets, and are first in the queue, then you will be the first one to get the tickets.
Right? Same is the case with Queue data structure.
Data inserted first, will leave the queue first.
The process to add an element into queue is called Enqueue and the process of removal of an
element from queue is called Dequeue.

Basic features of Queue

1. Like stack, queue is also an ordered list of elements of similar data types.
2. Queue is a FIFO (First in First Out) structure.
3. Once a new element is inserted into the Queue, all the elements inserted before the new
element in the queue must be removed, to remove the new element.
4. peek( ) function is often used to return the value of first element without dequeuing it.

Implementation of Queue Data Structure


• Queue can be implemented using an Array, Stack or Linked List.
• The easiest way of implementing a queue is by using an Array.
• Initially the head (FRONT) and the tail (REAR) of the queue points at the first index
of the array (starting the index of array from 0).
• As we add elements to the queue, the tail keeps on moving ahead, always pointing to
the position where the next element will be inserted, while the head remains at the
first index.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 48

When we remove an element from Queue, we can follow two possible approaches
(mentioned [A] and [B] in above diagram). In [A] approach, we remove the element
at head position, and then one by one shift all the other elements in forward position.
In approach [B] we remove the element from head position and then move head to the next
position.
In approach [A] there is an overhead of shifting the elements one position forward every
time we remove the first element.
In approach [B] there is no such overhead, but whenever we move head one position ahead,
after removal of first element, the size on Queue is reduced by one space each time.

Algorithm for ENQUEUE operation

1. Check if the queue is full or not.


2. If the queue is full, then print overflow error and exit the program.
3. If the queue is not full, then increment the tail and add the element.

Algorithm for DEQUEUE operation

1. Check if the queue is empty or not.


2. If the queue is empty, then print underflow error and exit the program.
3. If the queue is not empty, then print the element at the head and increment the head.
C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 49

Types of Queues
There are three types of queue:
• Circular Queue
• Priority Queue
• Deque

(i) Circular Queue


A circular queue is one in which the insertion of a element is done at the very first location if
the queue if the last location of the queue is full. New element can be inserted if and only if
the those location are empty For example, if we have a queue Q of say n elements , then after
inserting an element at last location (i.e in the n-1th) location of the array the next element
will be inserted at the very first location( i.e at 0th location) of the array.
A circular queue also have a front and rear to keep the track of the elements to be deleted and
inserted and therefore to maintain the unique characteristic of the queue.
Following are the assumption made:

• Front will always be pointing to the first element


• If front=rear the queue will be empty
• Each time a new element is inserted into the queue the rear is incremented by one
rear=rear+1
• Each time a new element is deleted from the queue the value of front is incremented by
one, front=front+1

(ii) Priority Queue


Priority queue is a collection of elements such that each element has been assigned a priority
and the order in which elements are deleted and processed comes from following rules:
• An element of higher priority is processed before any elements of lower priority
• Two elements with the same priority are processed according to the order in which they
were added to the queue.
An example of priority queue in computer science occurs in timesharing system in which the
processes of higher priority is executed before any process of lower priority.

There are two types of priority queue:


• Ascending priority queue :
It is a collection of items in to which items can be inserted arbitrarily and from which only
the smallest item can be removed.

• Descending priority queue :


It is similar but allows deletion of only the largest item.

(iii) Double Ended Queue i.e Dequeue
It is also a homogeneous list of elements in which insertion and deletion operations are
performed from both the ends. That is, we can insert elements from the rear end or from the
front end. Hence, it is called Double-Ended Queue. There are two types of deques. These

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 50

two types are due to the restrictions put to perform either the insertions or deletions only at
one end.
• Input restricted deques : Input restricted deques allows insertions at only one end of the
array or list but deletions allows at both ends.
• Output restricted deques : Output restricted deques allows deletions at only one end of
the array or list but insertions allow at both ends.

Applications of Queue
Queue, as the name suggests is used whenever we need to manage any group of objects in an
order in which the first one coming in, also gets out first while the others wait for their turn,
like in the following scenarios:

1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life scenario, Call Center phone systems uses Queues to hold people calling them
in an order, until a service representative is free.

Handling of interrupts in real-time systems. The interrupts are handled in the same order as
they arrive i.e First come first served.

Evaluation of Expressions
In any programming language, if we want to perform any calculation or to frame a condition
etc., we use a set of symbols to perform the task. These set of symbols makes an expression.

An expression can be defined as follows...

An expression is a collection of operators and operands that represents a specific value.

In above definition, operator is a symbol which performs a particular task like arithmetic
operation or logical operation or conditional operation etc.
Operands are the values on which the operators can perform the task. Here operand can be a
direct value or variable or address of memory location.

Expression Types
Based on the operator position, expressions are divided into three types.

They are as follows...

1. Infix Expression
2. Postfix Expression
3. Prefix Expression

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 51

1. Infix Expression
In infix expression, operator is used in between the operands.

The general structure of an Infix expression is as follows...

Operand1 Operator Operand2

Example

2. Postfix Expression
In postfix expression, operator is used after operands.
We can say that "Operator follows the Operands".

The general structure of Postfix expression is as follows...

Operand1 Operand2 Operator

Example

3. Prefix Expression
In prefix expression, operator is used before operands.
We can say that "Operands follows the Operator".

The general structure of Prefix expression is as follows...

Operator Operand1 Operand2

Example

Every expression can be represented using all the above three different types of expressions.
And we can convert an expression from one form to another form like Infix to Postfix, Infix
to Prefix, Prefix to Postfix and vice versa.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 52

Conversion of Expressions

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 53

*******

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 54

UNIT-IV
LINKED LISTS
Definition
Linked List is a very commonly used linear data structure which consists of group
of nodes in a sequence.
Each node holds its own data and the address of the next node hence forming a chain like
structure.
Linked Lists are used to create trees and graphs.

Advantages of Linked Lists


• They are a dynamic in nature which allocates the memory when required.
• Insertion and deletion operations can be easily implemented.
• Stacks and queues can be easily executed.
• Linked List reduces the access time.

Disadvantages of Linked Lists


• The memory is wasted as pointers require extra memory for storage.
• No element can be accessed randomly; it has to access each node sequentially.
• Reverse Traversing is difficult in linked list.

Applications of Linked Lists


• Linked lists are used to implement stacks, queues, graphs, etc.
• Linked lists let you insert elements at the beginning and end of the list.
• In Linked Lists we don't need to know the size in advance.

Types of Linked Lists


There are 3 different implementations of Linked List available, they are:

1. Singly Linked List


2. Doubly Linked List
3. Circular Linked List

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 55

Let's know more about them and how they are different from each other.

Singly Linked List


Singly linked lists contain nodes which have a data part as well as an address part i.e. next,
which points to the next node in the sequence of nodes.
The operations we can perform on singly linked lists are insertion, deletion and traversal.

A linked list is a sequence of data structures, which are connected together via links.
Linked List is a sequence of links which contains items. Each link contains a connection to
another link. Linked list is the second most-used data structure after array. Following are the
important terms to understand the concept of Linked List.
• Link − Each link of a linked list can store a data called an element.
• Next − Each link of a linked list contains a link to the next link called Next.
• Linked List − A Linked List contains the connection link to the first link called First.

Linked List Representation

Linked list can be visualized as a chain of nodes, where every node points to the next node.

As per the above illustration, following are the important points to be considered.
• Linked List contains a link element called first.
• Each link carries a data field(s) and a link field called next.
• Each link is linked with its next link using its next link.
• Last link carries a link as null to mark the end of the list.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 56

Doubly Linked List


In a doubly linked list, each node contains a data part and two addresses, one for
the previous node and one for the next node.

Doubly Linked List is a variation of Linked list in which navigation is possible in both ways,
either forward and backward easily as compared to Single Linked List. Following are the
important terms to understand the concept of doubly linked list.
• Link − Each link of a linked list can store a data called an element.
• Next − Each link of a linked list contains a link to the next link called Next.
• Prev − Each link of a linked list contains a link to the previous link called Prev.
• Linked List − A Linked List contains the connection link to the first link called First
and to the last link called Last.
Representing Chains

As per the above illustration, following are the important points to be considered.
• Doubly Linked List contains a link element called first and last.
• Each link carries a data field(s) and two link fields called next and prev.
• Each link is linked with its next link using its next link.
• Each link is linked with its previous link using its previous link.
• The last link carries a link as null to mark the end of the list.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 57

Circular Linked List


Circular Linked List is a variation of Linked list in which the first element points to the last
element and the last element points to the first element.
Both Singly Linked List and Doubly Linked List can be made into a circular linked list.
In circular linked list the last node of the list holds the address of the first node hence forming
a circular chain.

Both Linked List and Array are used to store linear data of similar type, but an array
consumes contiguous memory locations allocated at compile time, i.e. at the time of
declaration of array, while for a linked list, memory is assigned as and when data is added to
it, which means at runtime.
Below we have a pictorial representation showing how consecutive memory locations
are allocated for array, while in case of linked list random memory locations are assigned to
nodes, but each node is connected to its next node using pointer.

On the left, we have Array and on the right, we have Linked List.

Applications of Linked lists


Applications of linked list in computer science –
1. Implementation of stacks and queues
2. Implementation of graphs: Adjacency list representation of graphs is most popular
which uses linked list to store adjacent vertices.
3. Dynamic memory allocation: We use linked list of free blocks.
4. Maintaining directory of names
5. Performing arithmetic operations on long integers
6. Manipulation of polynomials by storing constants in the node of linked list representing
sparse matrices.
C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 58

Applications of linked list in real world-


1. Image viewer – Previous and next images are linked, hence can be accessed by next and
previous button.
2. Previous and next page in web browser – We can access previous and next url searched
in web browser by pressing back and next button since, they are linked as linked list.
3. Music Player – Songs in music player are linked to previous and next song. you can
play songs either from starting or ending of the list.

Applications of Circular Linked Lists:


1. Useful for implementation of queue. Unlike this implementation, we don’t need to
maintain two pointers for front and rear if we use circular linked list. We can maintain a
pointer to the last inserted node and front can always be obtained as next of last.
2. Circular lists are useful in applications to repeatedly go around the list. For example,
when multiple applications are running on a PC, it is common for the operating system
to put the running applications on a list and then to cycle through them, giving each of
them a slice of time to execute, and then making them wait while the CPU is given to
another application. It is convenient for the operating system to use a circular list so that
when it reaches the end of the list it can cycle around to the front of the list.
3. Circular Doubly Linked Lists are used for implementation of advanced data structures
like Fibonacci Heap.

Basic Operations on Linked List


• Traversal: To traverse all the nodes one after another.
• Insertion: To add a node at the given position.
• Deletion: To delete a node.
• Searching: To search an element(s) by value.
• Updating: To update a node.
• Sorting: To arrange nodes in a linked list in a specific order.
• Merging: To merge two linked lists into one.

1. Linked List Traversal


The idea here is to step through the list from beginning to end. For example, we may want
to print the list or search for a specific node in the list.
The algorithm for traversing a list
• Start with the head of the list. Access the content of the head node if it is not null.
• Then go to the next node(if exists) and access the node information
• Continue until no more nodes (that is, you have reached the null node)

2. Linked List node Insertion


There can be three cases that will occur when we are inserting a node in a linked list.
• Insertion at the beginning
• Insertion at the end. (Append)
• Insertion after a given node

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 59

Insertion at the beginning


§ Since there is no need to find the end of the list.
§ If the list is empty, we make the new node as the head of the list.
§ Otherwise, we have to connect the new node to the current head of the list and make
the new node, the head of the list.

Insertion at end
§ We will traverse the list until we find the last node.
§ Then we insert the new node to the end of the list.
§ Note that we have to consider special cases such as list being empty.
§ In case of a list being empty, we will return the updated head of the linked list
because in this case, the inserted node is the first as well as the last node of the
linked list.

Insertion after a given node


We are given the reference to a node, and the new node is inserted after the given node.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 60

3. Linked List node Deletion


To delete a node from a linked list, we need to do these steps
• Find the previous node of the node to be deleted.
• Change the next pointer of the previous node
• Free the memory of the deleted node.
In the deletion, there is a special case in which the first node is deleted.
In this, we need to update the head of the linked list.

4. Linked List node Searching


To search any value in the linked list, we can traverse the linked list and compares the value
present in the node.

5. Linked List node Updation


To update the value of the node, we just need to set the data part to the new value.

*******

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 61

UNIT-V
TREES
• Tree is a hierarchical data structure which stores the information naturally in the form of
hierarchy style.
• Tree is one of the most powerful and advanced data structures.
• It is a non-linear data structure compared to arrays, linked lists, stack and queue.
• It represents the nodes connected by edges.

The above figure represents structure of a tree. Tree has 2 subtrees.


A is a parent of B and C.
B is called a child of A and also parent of D, E, F.

Tree is a collection of elements called Nodes, where each node can have arbitrary number of
children.

Field Description
Root Root is a special node in a tree. The entire tree is referenced through it. It does not
have a parent.
Parent Node Parent node is an immediate predecessor of a node.
Child Node All immediate successors of a node are its children.
Siblings Nodes with the same parent are called Siblings.
Path Path is a number of successive edges from source node to destination node.
Height of Node Height of a node represents the number of edges on the longest path between that
node and a leaf.
Height of Tree Height of tree represents the height of its root node.
Depth of Node Depth of a node represents the number of edges from the tree's root node to the
node.
Degree of Node Degree of a node represents a number of children of a node.
Edge Edge is a connection between one node to another. It is a line between two nodes or
a node and a leaf.

In the above figure, D, F, H, G are leaves. B and C are siblings. Each node excluding a root
is connected by a direct edge from exactly one other node
parent → children.
C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 62

Advantages of Tree
§ Tree reflects structural relationships in the data.
§ It is used to represent hierarchies.
§ It provides an efficient insertion and searching operations.
§ Trees are flexible, It allows to move subtrees around with minimum effort.

Binary Tree
• Binary Tree is a special data structure used for data storage purposes.
• A binary tree has a special condition that each node can have a maximum of two
children.
• A binary tree has the benefits of both an ordered array and a linked list as search is as
quick as in a sorted array and insertion or deletion operation are as fast as in linked
list.

Binary Tree Traversals


• When we wanted to display a binary tree, we need to follow some order in which all
the nodes of that binary tree must be displayed.
• In any binary tree, displaying order of nodes depends on the traversal method.

Displaying (or) visiting order of nodes in a binary tree is called as Binary Tree
Traversal.

There are three types of binary tree traversals.

1. In - Order Traversal
2. Pre - Order Traversal
3. Post - Order Traversal

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 63

Consider the following Binary tree

1. In - Order Traversal ( leftChild - root - rightChild )


In In-Order traversal, the root node is visited between the left child and right child. In this
traversal, the left child node is visited first, then the root node is visited and later we go for
visiting the right child node. This in-order traversal is applicable for every root node of all
subtrees in the tree. This is performed recursively for all nodes in the tree.
In the above example of a binary tree, first we try to visit left child of root node 'A', but A's
left child 'B' is a root node for left subtree. so we try to visit its (B's) left child 'D' and again D
is a root for subtree with nodes D, I and J. So we try to visit its left child 'I' and it is the
leftmost child. So first we visit 'I' then go for its root node 'D' and later we visit D's right
child 'J'. With this we have completed the left part of node B. Then visit 'B' and next B's
right child 'F' is visited. With this we have completed left part of node A. Then visit root
node 'A'. With this we have completed left and root parts of node A. Then we go for the right
part of the node A. In right of A again there is a subtree with root C. So go for left child of C
and again it is a subtree with root G. But G does not have left part so we visit 'G' and then
visit G's right child K. With this we have completed the left part of node C. Then visit root
node 'C' and next visit C's right child 'H' which is the rightmost child in the tree. So we stop
the process.

That means here we have visited in the order of I - D - J - B - F - A - G - K - C - H using In-


Order Traversal.

In-Order Traversal for above example of binary tree is


I-D-J-B-F-A-G-K-C-H

2. Pre - Order Traversal ( root - leftChild - rightChild )


In Pre-Order traversal, the root node is visited before the left child and right child nodes. In
this traversal, the root node is visited first, then its left child and later its right child. This pre-
order traversal is applicable for every root node of all subtrees in the tree.
In the above example of binary tree, first we visit root node 'A' then visit its left
child 'B' which is a root for D and F. So we visit B's left child 'D' and again D is a root for I
and J. So we visit D's left child 'I' which is the leftmost child. So next we go for visiting D's
right child 'J'. With this we have completed root, left and right parts of node D and root, left
parts of node B. Next visit B's right child 'F'. With this we have completed root and left parts
of node A. So we go for A's right child 'C' which is a root node for G and H. After visiting C,
C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 64

we go for its left child 'G' which is a root for node K. So next we visit left of G, but it does
not have left child so we go for G's right child 'K'. With this, we have completed node C's
root and left parts. Next visit C's right child 'H' which is the rightmost child in the tree.

So we stop the process.

That means here we have visited in the order of A-B-D-I-J-F-C-G-K-H using Pre-Order
Traversal.

Pre-Order Traversal for above example binary tree is


A-B-D-I-J-F-C-G-K-H

3. Post - Order Traversal ( leftChild - rightChild - root )


In Post-Order traversal, the root node is visited after left child and right child. In this
traversal, left child node is visited first, then its right child and then its root node. This is
recursively performed until the right most node is visited.

Here we have visited in the order of I - J - D - F - B - K - G - H - C - A using Post-Order


Traversal.

Post-Order Traversal for above example binary tree is


I-J-D-F-B-K-G-H-C-A

Binary Search Tree Operations


Following are the operations performed on binary search tree:

1. Insert Operation
• Insert operation is performed with O(log n) time complexity in a binary search tree.
• Insert operation starts from the root node. It is used whenever an element is to be
inserted.

The following algorithm shows the insert operation in binary search tree:

Step 1: Create a new node with a value and set its left and right to NULL.
Step 2: Check whether the tree is empty or not.
Step 3: If the tree is empty, set the root to a new node.
Step 4: If the tree is not empty, check whether a value of new node is smaller or larger than
the node (here it is a root node).
Step 5: If a new node is smaller than or equal to the node, move to its left child.
Step 6: If a new node is larger than the node, move to its right child.
Step 7: Repeat the process until we reach to a leaf node.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 65

2. Search Operation
• Search operation is performed with O(log n) time complexity in a binary search tree.
• This operation starts from the root node. It is used whenever an element is to be searched.

The following algorithm shows the search operation in binary search tree:

Step 1: Read the element from the user .


Step 2: Compare this element with the value of root node in a tree.
Step 3: If element and value are matching, display "Node is Found" and terminate the
function.
Step 4: If element and value are not matching, check whether an element is smaller or larger
than a node value.
Step 5: If an element is smaller, continue the search operation in left subtree.
Step 6: If an element is larger, continue the search operation in right subtree.
Step 7: Repeat the same process until we found the exact element.
Step 8: If an element with search value is found, display "Element is found" and terminate
the function.
Step 9: If we reach to a leaf node and the search value is not match to a leaf node, display
"Element is not found" and terminate the function.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 66

GRAPHS
A graph is a pictorial representation of a set of objects where some pairs of objects are
connected by links. The interconnected objects are represented by points termed as vertices,
and the links that connect the vertices are called edges.
Formally, a graph is a pair of sets (V, E), where V is the set of vertices and E is the set of
edges, connecting the pairs of vertices. Take a look at the following graph.

In the above graph,


V = {a, b, c, d, e}
E = {ab, ac, bd, cd, de}

Elementary Graph Operations


Following are basic primary operations of a Graph −
• Add Vertex − Adds a vertex to the graph.
• Add Edge − Adds an edge between the two vertices of the graph.
• Display Vertex − Displays a vertex of the graph.
Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses a
stack to remember to get the next vertex to start a search, when a dead end occurs in any
iteration.

As in the example given above, DFS algorithm traverses from S to A to D to G to E to B


first, then to F and lastly to C. It employs the following rules.
• Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a
stack.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 67

• Rule 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop
up all the vertices from the stack, which do not have adjacent vertices.)
• Rule 3 − Repeat Rule 1 and Rule 2 until the stack is empty.

Step Traversal Description

Initialize the stack.

Mark S as visited and put it onto


the stack. Explore any unvisited
adjacent node from S. We have
three nodes and we can pick any
of them. For this example, we
shall take the node in an
alphabetical order.

Mark A as visited and put it onto


the stack. Explore any unvisited
adjacent node from A.
Both Sand D are adjacent
to A but we are concerned for
unvisited nodes only.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 68

Visit D and mark it as visited and


put onto the stack. Here, we
have B and C nodes, which are
adjacent to D and both are
unvisited. However, we shall
again choose in an alphabetical
order.

We choose B, mark it as visited


and put onto the stack.
Here Bdoes not have any
unvisited adjacent node. So, we
pop Bfrom the stack.

We check the stack top for return


to the previous node and check if
it has any unvisited nodes. Here,
we find D to be on the top of the
stack.

Only unvisited adjacent node is


from D is C now. So we visit C,
mark it as visited and put it onto
the stack.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 69

As C does not have any unvisited adjacent node so we keep popping the stack until we find
a node that has an unvisited adjacent node. In this case, there's none and we keep popping
until the stack is empty.
Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and uses
a queue to remember to get the next vertex to start a search, when a dead end occurs in any
iteration.

As in the example given above, BFS algorithm traverses from A to B to E to F first then to C
and G lastly to D. It employs the following rules.
• Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in
a queue.
• Rule 2 − If no adjacent vertex is found, remove the first vertex from the queue.
• Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.

Step Traversal Description

Initialize the queue.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 70

We start from
visiting S(starting node),
and mark it as visited.

3
We then see an unvisited
adjacent node from S. In
this example, we have
three nodes but
alphabetically we
choose A, mark it as
visited and enqueue it.

Next, the unvisited


adjacent node
from S is B. We mark it
as visited and enqueue it.

Next, the unvisited


adjacent node
from S is C. We mark it
as visited and enqueue it.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 71

Now, S is left with no


unvisited adjacent nodes.
So, we dequeue and
find A.

From A we have D as
unvisited adjacent node.
We mark it as visited and
enqueue it.

At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithm we
keep on dequeuing in order to get all unvisited nodes. When the queue gets emptied, the
program is over.

Spanning Trees
A spanning tree is a subset of Graph G, which has all the vertices covered with minimum
possible number of edges. Hence, a spanning tree does not have cycles and it cannot be
disconnected.
By this definition, we can draw a conclusion that every connected and undirected Graph G
has at least one spanning tree. A disconnected graph does not have any spanning tree, as it
cannot be spanned to all its vertices.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 72

We found three spanning trees off one complete graph. A complete undirected graph can
have maximum nn-2 number of spanning trees, where n is the number of nodes. In the above
addressed example, n is 3, hence 33−2 = 3 spanning trees are possible.

SEARCHING AND SORTING

SEARCHING
• Searching is a process of locating a particular element present in a given set of
elements.
• Searching Algorithms are designed to check for an element or retrieve an element
from any data structure where it is stored.
Based on the type of search operation, these algorithms are generally classified into two
categories:
1. Linear Search or Sequential Search
• Linear search is a very simple search algorithm.
• In this type of search, a sequential search is made over all items one by one.
• Every item is checked and if a match is found then that particular item is returned,
otherwise the search continues till the end of the data collection.
• Linear search is mostly used to search an unordered list of elements (array in which
data elements are not sorted).

Example
If an array A[] is declared and initialized as,

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

and the value to be searched is VAL = 7, then searching means to find whether the value
‘7’ is present in the array or not. If yes, then it returns the position of its occurrence. Here,
POS = 3 (index starting from 0).

2. Binary Search
• Binary search is a fast search algorithm.
• This search algorithm works on the principle of divide and conquer.
• For this algorithm to work properly, the data collection should be in the sorted form.
• Binary search looks for a particular item by comparing the middle most item of the
collection.
• If a match occurs, then the index of item is returned.
• If the middle item is greater than the item, then the item is searched in the sub-array to
the left of the middle item.
• Otherwise, the item is searched for in the sub-array to the right of the middle item.
• This process continues on the sub-array as well until the size of the subarray reduces
to zero.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 73

Example
How Binary Search Works?
For a binary search to work, it is mandatory for the target array to be sorted. We shall learn
the process of binary search with a pictorial example. The following is our sorted array and
let us assume that we need to search the location of value 31 using binary search.

First, we shall determine half of the array by using this formula −


mid = low + (high - low) / 2
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. As the value is greater than 27
and we have a sorted array, so we also know that the target value must be in the upper
portion of the array.

We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.

The value stored at location 7 is not a match, rather it is more than what we are looking for.
So, the value must be in the lower part from this location.

Hence, we calculate the mid again. This time it is 5.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 74

We compare the value stored at location 5 with our target value. We find that it is a match.

We conclude that the target value 31 is stored at location 5.


Binary search halves the searchable items and thus reduces the count of comparisons to be
made to very less numbers.

SORTING
• Sorting refers to arranging data in a particular order or format.
• Sorting algorithm specifies the way to arrange data in a particular order.
• The importance of sorting lies in the fact that data searching can be optimized to a
very high level, if data is stored in a sorted manner.
• Sorting is also used to represent data in more readable formats.
Following are some of the examples of sorting in real-life scenarios −
§ Telephone Directory − The telephone directory stores the telephone numbers of
people sorted by their names, so that the names can be searched easily.
§ Dictionary − The dictionary stores words in an alphabetical order so that searching of
any word becomes easy.
Selection sort
• Selection sort is a simple sorting algorithm.
• This sorting algorithm is an in-place comparison-based algorithm in which the list is
divided into two parts, the sorted part at the left end and the unsorted part at the right
end.
• Initially, the sorted part is empty and the unsorted part is the entire list.
• The smallest element is selected from the unsorted array and swapped with the
leftmost element, and that element becomes a part of the sorted array.
• This process continues moving unsorted array boundary by one element to the right.
• This algorithm is not suitable for large data sets.

How Selection Sort Works?


Consider the following depicted array as an example.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 75

For the first position in the sorted list, the whole list is scanned sequentially. The first
position where 14 is stored presently, we search the whole list and find that 10 is the lowest
value.

So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in
the list, appears in the first position of the sorted list.

For the second position, where 33 is residing, we start scanning the rest of the list in a linear
manner.

We find that 14 is the second lowest value in the list and it should appear at the second
place. We swap these values.

After two iterations, two least values are positioned at the beginning in a sorted manner.

The same process is applied to the rest of the items in the array.
Following is a pictorial depiction of the entire sorting process −

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 76

Bubble sort or Exchange sort


• Bubble sort is a simple sorting algorithm.
• This sorting algorithm is comparison-based algorithm in which each pair of adjacent
elements is compared and the elements are swapped if they are not in order.
• This algorithm is not suitable for large data sets
How Bubble Sort Works?
We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're keeping it
short and precise.

Bubble sort starts with very first two elements, comparing them to check which one is
greater.

In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we
compare 33 with 27.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 77

We find that 27 is smaller than 33 and these two values must be swapped.

The new array should look like this −

Next we compare 33 and 35. We find that both are in already sorted positions.

Then we move to the next two values, 35 and 10.

We know then that 10 is smaller 35. Hence they are not sorted.

We swap these values. We find that we have reached the end of the array. After one
iteration, the array should look like this −

To be precise, we are now showing how an array should look like after each iteration. After
the second iteration, it should look like this −

Notice that after each iteration, at least one value moves at the end.

And when there's no swap required, bubble sorts learns that an array is completely sorted.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 78

Insertion Sort
• This is an in-place comparison-based sorting algorithm.
• Here, a sub-list is maintained which is always sorted.
• For example, the lower part of an array is maintained to be sorted.
• An element which is to be inserted in this sorted sub-list, has to find its appropriate
place and then it has to be inserted there.
• Hence the name, insertion sort.
• The array is searched sequentially and unsorted items are moved and inserted into the
sorted sub-list (in the same array).
• This algorithm is not suitable for large data sets.

How Insertion Sort Works?

We take an unsorted array for our example.

Insertion sort compares the first two elements.

It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.

Insertion sort moves ahead and compares 33 with 27.

And finds that 33 is not in the correct position.

It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that
the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the sorted sub-
list remains sorted after swapping.

By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.

These values are not in a sorted order.

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed
Department of CSE 79

So we swap them.

However, swapping makes 27 and 10 unsorted.

Hence, we swap them too.

Again we find 14 and 10 in an unsorted order.

We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.

This process goes on until all the unsorted values are covered in a sorted sub-list.

*******

C Programming & Data Structures YouTube: Engineering Drive By: H. Ateeq Ahmed

You might also like