Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
236 views

315 14 - Lab Data Structure Using C ++

Uploaded by

Jeeva Sundaram
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
236 views

315 14 - Lab Data Structure Using C ++

Uploaded by

Jeeva Sundaram
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

.emaN e1.

sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.


.egaP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.

YTISREVINUALAGAPPA
APPAGALAUNIVERSITY
Master of Computer Applications


elcyC drihT eht ni )46.3:APGC( CA[Accredited
AN yb edarGwith
’+A’’A+’
htiwGrade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
]CGU-DRHM yb ytisrevinU I–yrogeand
taC Graded
sa dedarasG Category–I
dna University by MHRD-UGC]
300 036 – IDUKIARA
KARAIKUDI
K – 630 003
315 14 NOITACUDE ECNATSIDDIRECTORATE
FO ETAROTCEOF
RIDDISTANCE EDUCATION

LAB: DATA STRUCTURE USING C++


I - Semester

LAB: DATA STRUCTURE USING C++


Master of Computer Applications
315 14

itnem sYou
a egaare
p reinstructed
voc eht etatodpupdate
u ot dethe
tcurcover
tsni erpage
a uoYas mentioned below:
.emaN e1.sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.
aP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.

ISREVINUALAGAPPA
APPAGALAUNIVERSITY
Master of Computer Applications
rihT eht ni )46.3:APGC( CA[Accredited
AN yb edarGwith
’+A’’A+’
htiwGrade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
]CGU-DRHM yb ytisrevinU I–yrogeand
taC Graded
sa dedarasG Category–I
dna University by MHRD-UGC]
300 036 – IDUKIARA
KARAIKUDI
TACUDE ECNATSIDDIRECTORATE
K
FO ETAROTCEOF
– 630 003
RIDDISTANCE EDUCATION
LAB: DATA STRUCTURE USING C++
I - Semester
ALAGAPPA UNIVERSITY
[Accredited with ‘A+’ Grade by NAAC (CGPA:3.64) in the Third Cycle
and Graded as Category–I University by MHRD-UGC]
(A State University Established by the Government of Tamil Nadu)
KARAIKUDI – 630 003

Master of Computer Applications


I - Semester
315 14

LAB: DATA STRUCTURE USING C++


Author
Dr. Kavita Saini, Assistant Professor, School of Computer Science & Engineering, Galgotias University, Greater Noida

"The copyright shall be vested with Alagappa University"

All rights reserved. No part of this publication which is material protected by this copyright notice
may be reproduced or transmitted or utilized or stored in any form or by any means now known or
hereinafter invented, electronic, digital or mechanical, including photocopying, scanning, recording
or by any information storage or retrieval system, without prior written permission from the Alagappa
University, Karaikudi, Tamil Nadu.

Information contained in this book has been published by VIKAS® Publishing House Pvt. Ltd. and has
been obtained by its Authors from sources believed to be reliable and are correct to the best of their
knowledge. However, the Alagappa University, Publisher and its Authors shall in no event be liable for
any errors, omissions or damages arising out of use of this information and specifically disclaim any
implied warranties or merchantability or fitness for any particular use.

Vikas® is the registered trademark of Vikas® Publishing House Pvt. Ltd.


VIKAS® PUBLISHING HOUSE PVT. LTD.
E-28, Sector-8, Noida - 201301 (UP)
Phone: 0120-4078900  Fax: 0120-4078999
Regd. Office: 7361, Ravindra Mansion, Ram Nagar, New Delhi 110 055
 Website: www.vikaspublishing.com  Email: helpline@vikaspublishing.com

Work Order No. AU/DDE/DE1-238/Preparation and Printing of Course Materials/2018 Dated 30.08.2018 Copies - 500
SYLLABI-BOOK MAPPING TABLE
Lab: Data Structure Using C++
Syllabi Mapping in Book

BLOCK 1: SIMPLE C++ PROGRAMS


1. Introduction: Simple C++ Programs
2. Control Structures: Using if and switch constructs Programs
3. Looping, Arrays, Structure statements: for, while, do-while, Strings and Matrices Programs Problems

BLOCK 2: OOPs CONCEPTS


4. Functions: static function, friend function, constructor, destructor and operator overloading and Recursive programs
5. Inheritance and polymorphism: Inheritance types and polymorphism types, Virtual function
6. File: File Handling C++ Programs, opening and closing a data file - creating a data file, processing a data file
7. Pointers: Pointers and Pointers with Arrays Programs

BLOCK 3: LINEAR DATA STRUCTURE


8. Stacks : Stack Implementation, expression evaluation, Polish notation
9. Queues: Queue Implementation, Applications of Queue
10. Linked List programs: List, Merging lists, Linked list, Single linked list, Double Linked List, Header Linked list,
Insertion and Deletion of linked list, Traversing a linked list

BLOCK 4: NON LINEAR DATA STRUCTURE


11. Tree Programs : Trees, Binary Trees, Types of Binary trees, Binary Tree Representation, Traversing Binary Trees,
Binary Search tree, Insertion and Deletion operations
12. Graphs: Shortest Path Algorithms
o Dijkstra’s Algorithm
o Graphs with Negative Edge costs
o Acyclic Graphs
o All Pairs Shortest Paths Algorithm Minimum cost Spanning Trees
o Kruskal’s Algorithm
o Prims’s Algorithm
o Applications

BLOCK 5: SEARCHINGAND SORTINGALGORITHMS


13. Searching Techniques: Linear and Binary search Programs
14. Sorting techniques: Bubble sort, Quick sort, Insertion sort, Merge sort
Introduction
INTRODUCTION

Object-oriented Programming (OOP) is one of the most impressive programming


NOTES paradigms in software development. C++ has become one of the most popular
OOP languages used for developing real-world applications. C++ is a programming
language that extended from the ubiquitous C language. It treats data as a crucial
element—not allowing it to move freely around the system. Therefore, the main
emphasis in C is on data and not on the procedure. You can design programs
around the data being operated upon in C++. An object-oriented language helps
in combining data and functions that operate on data into a single unit known as
object. C++ is used for developing different types of applications, such as real-
time systems, simulation modelling, expert systems. It also provides flexibility to a
user to introduce new types of objects in his programming on the basis of the
requirement of the application.
This lab manual, Lab: Data Structure using C++, contains several programs
based on C++ concepts, such as classes, inheritance, stack and queue, to provide
the concept of programming. In addition, it will help students in coding and debugging
their programs. The manual provides all logical, mathematical and conceptual
programs that can help to write programs very easily in C++ language. These
exercises shall be taken as the base reference during lab activities for students of
MCA. There are also many Try Yourself Questions provided to students for
implementation in the lab.

Self-Instructional
8 Material
Simple C++ Programs

BLOCK I SIMPLE C++ PROGRAMS


Introduction NOTES
C++ language is invented by Bjarne Stroustrup in 1980 at Bell Laboratories,
New Jersey. C++ language was initially called “C with Classes” but in 1983 this
name was changed to C++. C++ is a superset of C.
The purpose of C++ is to overcome this limit and provide a better way to
manage larger, more complex programs, by using object oriented programming
(OOP). C++ is very popular language as it has many features as mentioned below:
 Classes and objects
 Encapsulation
 Information hiding
 Inheritance
 Polymorphism
Portable language
C++ is a portable language having feature of carrying the instruction from one
system to another system. In C++ Language .cpp file contain source code, we
can edit also this code. .exe file contain application, only we can execute this file.
When we write and compile any C++ program on window operating system that
program easily run on other window based system.

Fig. 1.1 Representing the C++ object file running on Windows.

Recommended System/Software Requirements:


1. Intel based desktop PC of 166MHz or faster processor with at least 64
MB RAM and 100 MB free disk space.
2. Turbo C++ compiler or GCC compilers
Self-Instructional
Material 1
Simple C++ Programs In this manual we have used Turbo C++. To write C++ code first we need to
open Torbo C++.
For every C++ program, we need to follow the steps given below for writing
and executing a program:
NOTES
Write a program code-> save your program (F2)->compile (Alt+F9)->
Run(Ctrl +F9)
Step 1: Click on Turbo C++ from start menu or double click on Turbo C++ on
desktop.

After clicking on Turbo C++ following screen will appear:

Step 2: Click on Start Turbo C++. After clicking on Start Turbo C++ button
following screen will appear:

Self-Instructional
2 Material
Simple C++ Programs

NOTES

This is the editor where we will write code of C++ programs.


Step 3: Write a program to print “Hello” on screen (Hello.cpp).

Step 4: Save program by name hello.cpp by pressing F2 key or by using menu


option File->Save As:

Self-Instructional
Material 3
Simple C++ Programs Step 5: Compile program by hello.cpp by pressing Alt+F9 keys or by using menu
option Compile-> Compile:

NOTES

Step 6: Run program by hello.cpp by pressing Ctrl +F9 keys or by using


menu option Run->Run.

Output:

Self-Instructional
4 Material
Simple C++ Programs Simple C++ Programs

1. Write a program to take two numbers as input and print their sum and
average.
//Program to take input in two numbers and print sum and NOTES
average
#include<iostream.h>
void main()
{
int num1,num2,sum,avg;

cout<<“Enter two numbers”<<endl; //output statement


cin>>num1; //input statement
cin>>num2;
sum=num1+num2;
avg=sum/2;
cout<<“Sum of two numbers “<<sum<<endl;
cout<<“Average of two numbers “<<avg;
}
Output:

2. Write a program to swap two numbers without using a third Variable.


#include <iostream.h>
void main()
{
int num1,num2;
cout<<“Enter two numbers”<<endl;
cin>>num1>>num2;
num2 = num1+num2;
num1 = num2 - num1;
num2 = num2 - num1;
cout<<“values after swaping :\n”;
cout<<“Value of a Num1 “<<num1<<endl;
cout<<“Value of a Num2 “<<num2<<endl;
}
Self-Instructional
Material 5
Simple C++ Programs Output:

NOTES

Try yourself:
(i) Write a program to calculate volume of cylinder.
Volume of cylinder= PI*r*r*h
(ii) Write a program to calculate curved surface area of cylinder.
Curved surface area of cylinder= 2*PI*r*h
(iii) Write a program to print ASCII value of digits, uppercase and lowercase
alphabets.
Control Structures: Using if and switch constructs Programs:
3. Write a program to check whether the number provided is even or odd.
#include <iostream.h>
void main()
{
int num;
cout<<“Enter a number: “;
cin>>num;
if(num%2==0)
{
cout<<“Number is even “;
}
else
{
cout<<“Number is odd “;
}

}
Output:
Enter a number: 2
Number is even
4. Write a program to print the largest number among three numbers given
by the user.
Self-Instructional
6 Material
// program to print the largest number among three numbers Simple C++ Programs
#include <iostream.h>
void main()
{
NOTES
int num1,num2,num3;
cout<<“Enter three numbers”<<endl;
cin>>num1>>num2>>num3;

if(num1 >= num2 && num1 >= num3)


{
cout << “Largest number: “ << num1;
}
else if(num2 >= num1 && num2 >= num3)
{
cout << “Largest number: “ << num2;
}
else
{
cout << “Largest number: “ << num3;
}

}
Output:

5. Write a single program that provides the sum, difference, multiplication


and division of two numbers.
#include <iostream.h>
void main()
{ int num1, num2; char op;
cout << “Enter two numbers: “;
cin >> num1 >> num2;
cout << “Enter operator : “;
cin >> op;
switch (op)
{
Self-Instructional
Material 7
Simple C++ Programs case ‘+’: cout <<“\n Sum of two numbers is: “<<
num1+num2;
break;
case ‘-’: cout <<“\n Subtraction of two numbers
NOTES is: “<< num1- num2;
break;
case ‘*’: cout <<“\n Multiplication of two numbers
is: “<< num1*num2;
break;
case ‘/’: cout <<“\n Division of two numbers is:
“<< num1/num2;
break;
default: cout << “\n Invalid operator”;
break;
}
}
Output:
Enter two numbers: 45
10
Enter operator: *
Multiplication of two numbers is: 450
Try yourself:
(1) Write a program to convert a lowercase alphabet to uppercase or
vice-versa.
(2) Write a program to check whether a year is leap year or not.
(3) Write a program to check whether a given character is uppercase or
lowercase alphabet or a digit or a special character.
Looping, Arrays, Structure statements: for, while, do-while, Strings and
Matrices Programs.
6. Write a program to print table of any number using for loop.
// program to print table of any number

#include <iostream.h>
void main()
{
int num, i;
cout<<“Enter a number: “;
cin>>num;
cout<<“Table of “<<num<<endl;
Self-Instructional for (i=1;i<=10;i++)
8 Material
{ Simple C++ Programs
cout<<num*i<<endl;
}
}
NOTES
Output:

7. Write a program to print Fibonacci Series (0, 1, 1, 2, 3, 5, 8, 13, 21,...)


// Program to print Fibonacci Series using for loop
#include <iostream.h>
void main()
{
int num, i, a=0, b=1, c;
cout<<“Enter a number of terms for Series: “;
cin>>num;
cout<<“Fibonacci series : \n”;
for (i=0; i<num; i++)
{
cout<<“\n”<<a;
c=a+b;
a=b;
b=c;
}
}
Output:

Self-Instructional
Material 9
Simple C++ Programs 8. Write a program to check the number is Armstrong or not.
A number is known as Armstrong number if sum of the cubes of its digits is
equal to the number itself.
NOTES For example
370 is an Armstrong number because:
370 = 3*3*3 + 7*7*7 + 0*0*0
= 27 + 343 + 0
= 370
// C++ Program to check Armstrong Number
#include <iostream.h>

void main()
{
int num, sum = 0, rem,temp;
cout<<“Enter a number: “;
cin>>num;

temp =num;
while (num>0)
{
rem= num%10;
sum= sum+(rem*rem*rem);
num= num/10;
}
if (temp==sum)
cout<<“Number in armstrong “<<endl;
else
cout<<“Number is not armstrong .”<<endl;
}
Output:

9. Write a C++ program to print table of a number using do while loop.


//C++ program to print table of any number using do while
loop
#include <iostream.h>
Self-Instructional
void main()
10 Material
{ Simple C++ Programs
int num, i;
cout << “Enter any number: “;
cin >> num;
NOTES
cout<<“\n Table of” <<num<<endl;
i=1;
do{
cout<<num*i<<endl;
i++;
}while (i<=10);
}

Output:

Try yourself:
(1) Write a program to reverse a number.
(2) Write a program to check whether a number is prime number or not.
(3) Write a program to convert binary number to decimal number.
10 Write a program that takes values in an array and also display them.
//C++ program to scan and print values using array
#include <iostream.h>
int main()
{
int arr[5],i;
cout << “Enter 5 numbers:\n “;
for (i=0;i<5;i++)
cin >> arr[i];
cout<<“\n Array values are “<<endl;
for (i=0;i<5;i++)
cout<<arr[i]<<endl;
}
Self-Instructional
Material 11
Simple C++ Programs Output:

NOTES

11. Write a program that take a string as input and print it.
//C++ Program to take input in string and print
#include <iostream.h>
#include <conio.h>
void main()
{
char str[15];
cout<<“Enter your name: “;
cin>>str;
cout<<“\n Welcome “<<str;
getch ();
}
12. Write a program to print length of a string provided.
//C++program to count string length
#include<iostream.h>
void main( )
{
int i,count=0;
char str[50];
cout<<“Enter any string “;
cin.getline (str, 50); //getline function allows
user to input string with space
//loop will run till it reaches to string terminator
‘\0’
for (i = 0; str[i] != ‘\0’; i++)
{
count ++;
}
cout << “\n Length of string is “ << count;
}
Self-Instructional
12 Material
Output: Simple C++ Programs

NOTES

13. Write a program to check whether a string is palindrome or not.


// C++ program to check a string is palindrome or not
#include<iostream>
using namespace std;
int main( )
{
int i,len=0;
char str[50],rev_str[50];

cout<<“Enter any string “;


cin.getline(str, 50); //getline function allows user
to input string with space
//count length of string
for (i = 0; str[i] != ‘\0’; i++)
{
len++;
}
//copy str to rev_str
int j=0;
for (i = len - 1; i >= 0 ; i—,j++)
{
rev_str[j] = str[i];
}
rev_str[j] =’\0' ; //reverse string is terminated
//compare both strings
int flag=0;
for (i = 0; i < len ; i++)
{
if (str[i]==rev_str[i])
flag = 1;
else
{
break; //exit from loop
}
}
Self-Instructional
Material 13
Simple C++ Programs if (flag == 1)
cout<<“ \n string is a palindrome”;
else
cout<<“ \n string is a not palindrome”;
NOTES
}
Output:

14. Write a program to print the largest number in an array.


//C++ program to print the largest number in an array
#include <iostream.h>
int main()
{
int arr[5], i, max;
cout << “Enter 5 numbers:\n “;
for (i=0;i<5;i++)
cin >> arr[i];
max= arr[0];
for (i = 1;i < 5; i++)
{
if (max < arr[i])
max = arr[i];
}
cout << “Largest element = “ << max;
}

Output:

Self-Instructional
14 Material
Simple C++ Programs
Try yourself
(1) Write a program to insert an element in an array.
(2) Write a program to find sum of elements of an array.
NOTES
(3) Write a program to find largest number from an array.
15. Write a program that provides the sum of two matrices.
//C++ program to print sum of two matrices
#include<iostream.h>
int main()
{
int i, j, m1[10][10], m2[10][10], sum[10][10];
cout << “Enter the elements of first matrix\n”;
for ( i = 0; i < 3; i++ )
{
cout<<“\n enter values for row “<<i+1<<endl;
for ( j = 0 ; j<3 ; j++ )
{ cin >> m1[i][j];}
}

cout << “Enter the elements of second matrix\n”;

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


{
cout<<“\n enter values for row “<<i+1<<endl;
for ( j = 0 ; j< 3 ; j++ )
{ cin >> m2[i][j];
}
}
cout << “Sum of two matrices \n”;
for ( i = 0 ;i < 3 ; i++ )
{
for ( j = 0 ; j<3 ; j++ )
{ sum[i][j] = m1[i][j]+m2[i][j];
cout << sum[i][j] << “\t”;

}
cout<<endl;
}
}

Self-Instructional
Material 15
Simple C++ Programs Output:

NOTES

16. Write a program to find out the product of two matrices.


//C++ program for matrix multiplication
#include<iostream.h>
int main()
{
int i,j,k, m1[10][10], m2[10][10], res[10][10];
cout << “Enter the elements of first matrix\n”;
for ( i = 0 ;i < 3 ; i++ )
{
cout<<“\n enter values for row “<<i+1<<endl;
for ( j = 0 ; j<3 ; j++ )
{ cin >> m1[i][j];}
}
cout << “Enter the elements of second matrix\n”;
for ( i = 0 ;i < 3; i++ )
{
cout<<“\n enter values for row “<<i+1<<endl;
for ( j = 0 ; j< 3 ; j++ )
{ cin >> m2[i][j];
}
}
for (i = 0; i < 3; ++i)
{

Self-Instructional
16 Material
for (j = 0; j < 3; ++j) Simple C++ Programs
{
res [i][j]=0;
for (k = 0; k < 3; ++k)
NOTES
{
res[i][j] += m1[i][k] * m2[k][j];
}
}
}
cout << “Multiplication of two matrices \n”;
for ( i = 0 ;i < 3 ; i++ )
{
for ( j = 0 ; j<3 ; j++ )
{
cout << res[i][j] << “\t”;
}
cout<<endl;
}
}
Output:

Try yourself:
(1) Write a program to print sum of diagonal values of a square matrix.
(2) Write a program to find highest and lowest element of a matrix.
(3) Write a program to convert first letter of each word of a string to uppercase
and other to lowercase.
(4) Write a program to find substring in string (pattern matching).
Self-Instructional
Material 17
OOPs Concepts

BLOCK II OOPs CONCEPTS


1. Write a program to demonstrate the use of class and object.
NOTES
//C++ sample program for class and object
#include<iostream.h>
//class
class student
{
private: //scope of variables is private
//member variables
int rno;
char name[10];
public: //scope of functions is public
// member functions
void input()
{
cout<<“\n Enter student roll number :”;
cin>>rno;
cout<<“\n Enter student name :”;
cin>>name;
}
void display()
{
cout<<“\n Roll Number :”<<rno;
cout<<“\n Name :”<<name;
}
} ; //class closed
int main()
{
student obj; //object of student class
obj.input(); //call of input function
obj.display(); //call of display function
}
Output:

Self-Instructional
18 Material
Keywords: private and public OOPs Concepts

You may have noticed two keywords: private and public in the above program.
The private keyword makes data and functions private. Private data and
functions can be accessed only from inside the same class. NOTES
The public keyword makes data and functions public. Public data and
functions can be accessed out of the class.
2. Write a program to demonstrate the use of constructor in a class.

//C++ sample program for constructor


#include<iostream.h>
//class
class student
{
private: //scope of variables is private
//member variables
int rno;
char name[10];
public: //scope of functions is public
student()
{
cout<<“Constructor \n”;
rno=0;
}
// member functions
void input()
{
cout<<“\n Enter student roll number :”;
cin>>rno;
cout<<“\n Enter student name :”;
cin>>name;
}
void display()
{
cout<<“\n Roll Number :”<<rno;
cout<<“\n Name :”<<name;
}
} ;
int main()
{

Self-Instructional
Material 19
OOPs Concepts student obj;
obj.input();
obj.display();
}
NOTES
Output:

3. Write a program to demonstrate the use of constructor and destructor


in a class.
//C++ sample program for constructor and destructor
#include<iostream.h>

//class

class student
{
private:
//member variables
int rno;
char name[10];

public

// constructor
student()
{
cout<<“Constructor \n”;
rno=0;
}

// member functions
void input()
{
cout<<“\n Enter student roll number :”;
cin>>rno;
Self-Instructional
20 Material
cout<<“\n Enter student name :”; OOPs Concepts
cin>>name;
}

NOTES
void display()
{
cout<<“\n Roll Number :”<<rno;
cout<<“\n Name :”<<name;
}

//destructor
~student()
{
cout<<“\n Destructor \n”;
}
} ;

int main()
{
student obj;
obj.input();
obj.display();
}

Output:

4. Write a program to demonstrate the use of static variable.


//C++ sample program for static variable
#include <iostream.h>
void test()
{
// static variable
static int count = 0;
cout << count <<endl;
count++;
Self-Instructional
Material 21
OOPs Concepts }
int main()
{
cout << “Static variable “ <<endl;
NOTES
for (int i=0; i<5; i++)
test();
}
Output:

Features of static function


 Static member functions have a class scope and they do not have access to
the ‘this’ pointer of the class.
 The main usage of static function is when the programmer wants to have a
function which is accessible even when the class is not instantiated.
 A normal member function is accessed using the object and an operator
called the dot member access operator.
 The functions declared static or static functions are accessed using only the
class name and the scope resolution operator, unlike in normal member
functions where these are not used.
5. Write a program to demonstrate the use of static variable and static
function.
//C++ sample program for static variable and static function
#include <iostream.h>
class test
{
private:
static int count; //Static data
int n;
public:
//Constructor
test ()
{
count = count+1;
n=count;
Self-Instructional
}
22 Material
//static function OOPs Concepts
static void function1()
{
cout << “\nResult is: “ << count<<endl;
NOTES
}
//Normal function
void counter ()
{
cout << “\nCounter is: “ << n<<endl;
}
//Destructor
~test ()
{
count = count-1;
}
};
int test::count=0;
int main()
{
test obj1;
//Static function is accessed using class name and
scope resolution operator (::)
test::function1 ();
test obj2,obj3,obj4;
test::function1 ();
//normal function is accessed using object name and
the dot member access operator(.)
obj1.counter();
obj2.counter();
obj3.counter();
obj4.counter();
}
Output:

Self-Instructional
Material 23
OOPs Concepts 6. Write a program to demonstrate the use of static function and variable.
//C++ Program to count the object value using the keyword
static variable.
#include<iostream.h>
NOTES class static_class {
int n;
static int count; //static variable
public:
//constructor
static_class()
{
n = ++count;
}
void obj_number()
{
cout << “\n\tObject number is :” << n;
}
static void obj_count()
{
cout << “\nNumber of Objects :” << count;
}
};
int static_class::count;
int main()
{
static_class obj1, obj2;

obj1.obj_count();
obj1.obj_number();
obj2.obj_count();
obj2.obj_number();
return 0;
}
Try yourself:
(1) Write a program to swap two numbers using class
(2) Write a Program to Print Numbers From 1 to n using class
(3) Write a program to calculate area of a circle,a rectangle or a triangle
depending upon user’s choice using class

Self-Instructional
24 Material
7. Write a program to get and print student data using inheritance. OOPs Concepts

// program to get and print student data using inheritance


#include <iostream.h>
//class
NOTES
class student
{
private: //scope of variables is private
//member variables
int rno;
char name[10];
public: //scope of functions is public
// member functions
void input ()
{
cout<<“\n Enter student roll number :”;
cin>>rno;
cout<<“\n Enter student name :”;
cin>>name;
}

void display ()
{
cout<<“\n Roll Number :”<<rno;
cout<<“\n Name :”<<name;
}
} ; //class closed

class fee:public student //class fee(derived) class


is inheriting student (base) class
{
float fee; //default scope in private

public:
void input_data ()
{
input (); //call of input function of student
class
cout<<“\n Enter Fee :”;
cin>>fee;
}

Self-Instructional
Material 25
OOPs Concepts void display_data ()
{
display (); //call of display function of student
class
NOTES cout<<“\n Fee :”<<fee;
}
};
int main()
{
fee obj; //object of fee class
obj.input_data ();
obj.display_data ();
}
Output:

8. Write a program to overload a sum function.


#include <iostream.h>
class Test
{
public:
int sum(int a,int b)
{
return a + b;
}
int sum (int a, int b, int c)
{
return a + b + c;
}
};
int main()
{

Self-Instructional
26 Material
Test obj; OOPs Concepts
cout<<“Sum of two integers “<<obj.sum(310, 220)<<endl;
cout<<“Sum of three integers “<<obj.sum(12, 20, 23);
}
NOTES
Output:

Try yourself:
(1) Write a program to swap two numbers using class
(2) Write a Program to Print Numbers From 1 to n using class
(3) Write a program to calculate area of a circle, a rectangle or a triangle
depending on input using overloaded calculate function.
(4) Write a program that overloads the + operator and relational operators
(suitable) to perform the following operations:
a) Concatenation of two strings.
b) Comparison of two strings.
9. Write a program to print factorial of a given number using recursive
function.
//C++ Program to print factorial using recursive function
#include<iostream.h>
// Factorial Function
int factorial(int n)
{
if (n > 1)
return n * factorial(n - 1); //recursive call of
factorial function
else
return 1;
}

int main()
{
int n;
cout << “Enter a number : “;
cin >> n;

Self-Instructional
Material 27
OOPs Concepts
cout << “Factorial of “ << n << “ is “ << factorial(n);
return 0;
}
NOTES
Output:

10. Write a program to print Fibonacci series using recursive function.


//C++ Program to print Fibonacci series using recursive
function

#include<iostream.h>
int fibonacci (int n)
{
if ((n==1)||(n==0))
{
return (n);
}
else
{

return (fibonacci (n-1)+fibonacci (n-2)); ////recursive


call of fibonacci function
}
}

int main()
{
int n, i;

cout<<“Enter number of terms for Fibonacci Series:”;


cin>>n;
cout<<“Fibonacci Series “<<endl;

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


{

Self-Instructional
28 Material
cout<<“ “<<fibonacci (i); OOPs Concepts
}
return 0;
}
NOTES
Output:

Try yourself:
(1) Write a program that uses a recursive function to find the binary equivalent
of a given non-negative integer n.
(2) Write a programs functions to find the GCD of two given integers using
recursive function.
Input/Output with files
C++ provides various header files for Input/output to/from data files. These header
files are ofstream.h, ifstream.h and fstream.h.
 ifstream: Stream class to read from files.
 ofstream: Stream class to write on files.
 fstream: Stream class to both read and write from/to files.
11. Write a C++ program to create a file (data.txt).
/ /basic file operations
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main ()
{
ofstream file1;
file1.open (“data.txt”);
file1 << “This is my first file.\n”;
file1.close ();
getch();
}
The above code will create a file called data.txt. We have inserted “This is my first
file.” text in our file.

Self-Instructional
Material 29
OOPs Concepts Opening a file
open () function is used with filename and mode parameters
for opening a file.

NOTES Syntax:
open (filename, mode);
Filename parameter is used to give a filename to be opened and mode parameter
is used to give modes in which file should be open. There are various modes
available such as ios::in, ios::out, ios::binary, ios::ate etc. All these modes can be
combined using bitwise OR (|) operator.
Example of combining file modes is:
ofstream file1;
file1.open (“data.bin”, ios::out | ios::app | ios::binary);
Table 1.1 Modes of opening a file.

ios::in This mode open file in input mode only.


ios::out This mode open file in output mode only.
ios::binary This mode open file in binary mode.
This mode set the initial position at the end of the file.
ios::ate
If this flag is not set, the initial position is the beginning of the file.
This mode allows all output operations are be performed at the end
ios::app of the file (EoF), appending the content to the current content of the
file.

Closing a file
Close () function is used for closing a file.
Syntax:
filename.close ();
12. Write a program for creating and writing on a text file.
// C++ program of writing on a text file
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
ofstream file_out;
char file_name[20];
char str[80];
clrscr ();
cout<<“Enter file name to be created “;
cin>> file_name;
Self-Instructional
30 Material
//create a new file in output mode OOPs Concepts
file_out.open (file_name, ios::out);

cout<<“Enter data to be stored “;


NOTES
cin>> str;

file_out << str;


cout<<“Information stored in file”;

//close file
file_out.close ();
getch();
}
13. Write a program to retrieve/read data from a text file.
// C++ program of retrieve data from a text file
#include<iostream.h>
#include<fstream.h>
#include<conio.h>

void main()
{
ifstream file_in;
char file_name[20];
char str[80];

clrscr ();

cout<<“Enter file name: “;


cin>> file_name;

cout<<“Enter file name to open”;


file_in.open (file_name, ios::in);

file_in.get (str, 80);


cout<<str;

file_in.close ();
getch ();
}
Self-Instructional
Material 31
OOPs Concepts Creating Binary file
File streams include two functions to perform read () and write () operations on a
binary file.
NOTES write (void *buffer, int size);
read (void *buffer, int size);
The buffer is of type char* which represents the address of an array of bytes
where the read data elements are stored. The size parameter is an integer value
that specifies the number of characters to be read or written from/to the memory
block.
14. Write a program for reading and writing on a binary file.
//Read and Writing in a Binary File
#include<iostream.h>
#include<fstream.h>
#include<cstdio.h>

class Student
{
int rno;
char name[50];
public:
void setData()
{
cout << “\n Enter roll number”;
cin >>rno;
cout << “Enter name “;
cin.getline (name, 50);
}
void showData ()
{
cout << “\nAdmission no. : “ << rno;
cout << “\nStudent Name : “ << name;
}

};
// function to write in a binary file.
void write_data()
{

Self-Instructional
32 Material
ofstream file_out; OOPs Concepts
file_out.open (“student.dat”, ios::binary | ios::app);

Student obj;
NOTES
obj.setData ();
file_out.write((char*)&obj, sizeof(obj));
file_out.close();
}

//function to display records of file

void display()
{
ifstream file_in;
file_in.open(“student.dat”, ios::binary);

Student obj;

while(file_in.read((char*)&obj, sizeof(obj)))
{
obj.showData();
}

file_in.close();
}

};

int main()
{
for(int i = 1; i <= 4; i++)
write_record ();

//Display all records


cout << “\nList of records”;
display ();

//Search record
cout << “\nSearch result”;
search (100);
Self-Instructional
Material 33
OOPs Concepts //Delete record
delete_record(100);
cout << “\nRecord Deleted”;

NOTES
//Modify record
cout << “\nModify Record 101 “;
modify_record (101);
return 0;
}
Try yourself
(1) What task does the following program perform?
#include<iostream.h>
#include<fstream.h>
int main()
{ ofstream ofile;
ofile.open (“text.txt”);
ofile << “geeksforgeeks” << endl;
cout << “Data written to file” << endl; ofile.close();
}
(2) Write a program which copies one file to another.
(3) Write a program to that counts the characters, lines and words in the text
file.
15. Write a Program to print values of array using Pointers.
//C++ program of pointers with arrays
#include <iostream.h>
void main()
{
int arr[5],i,*ptr;
ptr = arr; //ptr pointer is holding address of arr[0]
element.
cout << “Enter 5 numbers:\n “;
for(i=0;i<5;i++)
cin >> arr[i];
cout<<“\n Array values using pointer “<<endl;
for(i=0;i<5;i++)
cout<<*(ptr + i)<<endl; //*(ptr+i) will
print array values

}
Self-Instructional
34 Material
Linear Data Structure

BLOCK III LINEAR DATA


STRUCTURE
NOTES
1. Write a Program to implement Stack using Array.
//C++ Program to implement Stack using Array
#include <iostream.h>
#define MAX 5
// stack class declaration
class stack
{
private:
int top;
int ele[MAX];
public:
//Default Constructor
stack()
{
top = -1;
}
//PUSH function
void push( int item )
{
if( top==MAX-1 )
{
cout<<“Stack Overflow”<<endl;
}
else
{
top++;
ele[top] = item;

cout<<“\n Inserted value is : “<< item;


}
}
//POP function
int pop( )
{
int item;
if( top==-1 )
Self-Instructional
Material 35
Linear Data Structure {
cout<<“\nStack Underflow”;
}
else
NOTES
{
item = ele[top];

top—;
}
return item;
}

//DISPLAY function
void display ()
{
if( top==-1 )
{
cout<<“\nStack Underflow”;
}
else
{
int i;
cout<<“Stack value are “<<endl;

for(i=top;i>=0;i—)
cout<<ele[i]<<endl;
}
}
}; //class closed

void main()
{
int item = 0, choice, value; char ans;
stack s = stack();
do
{
cout<<“1. Push”<<endl<<”2. Pop”<<endl<<”3.
Display”<<endl<<”4. Exit”;
cout<<“\nEnter your choice: “;
cin>>choice;

Self-Instructional
36 Material
switch(choice) Linear Data Structure
{
case 1:
cout<<“Enter the value to be insert: “;
NOTES
cin>>value;
s.push(value);
break;
case 2:
value=s.pop();
cout<<“\nDeleted value is “<<value;
break;
case 3:
s.display();
break;
case 4:
// exit(0);
default:
cout<<“Invalid choice”;
}

cout<<“\nDo you want to cont…(y/n)”;


cin>>ans;
}while (ans==’y’ || ans==’Y’);

}
Output:

Self-Instructional
Material 37
Linear Data Structure Algorithm: To transform infix expression to postfix expression value from stack
using array.
Description: Here Q is an arithmetic expression written in Infix expression.
Algorithm finds P as a Postfix expression
NOTES
Stack is an array where we will PUSH and POP values.
MAX is a constant used to define maximum limit of TOP is the top most element
of Stack where insertion and deletion is allowed.
DATA is data to be inserted in Stack.
1. Push “(“ onto Stack, and add “)” to the end of Q.
2. Scan Q from left to right and repeat Step 3 to 6 for each element of Q until
the Stack is empty.
3. If an operand is encountered, add it to P.
4. If a “(“ left parenthesis is encountered THEN push it onto Stack.
5. If an operator is encountered ,then:
1. Repeatedly POP from Stack and add to P each operator (on the top of
Stack) which has the same precedence as or higher precedence than
operator.
2. Add operator to Stack.
[End of If]
6. If a right parenthesis is encountered ,then:
1. Repeatedly pop from Stack and add to P each operator (on the top of
Stack) until a left parenthesis is encountered.
2. Remove the left Parenthesis.
[End of If]
[End of If]
7. END.
2. Write a program to convert infix expression to postfix expression.
//C++ Program to convert INFIX EXPRESSION TO POSTFIX
EXPRESSION
#include<iostream.h>
# define MAX 100

//STACK CLASS DECLARATION


class stack
{
public:
char stack_array[MAX];
int top;
Self-Instructional
38 Material
//DEFAULT CONSTRUCTOR USED TO INITIALIZE TOP=-1 Linear Data Structure
stack()
{
top=-1;
NOTES
}
//PUSH FUNCTION
void push(char symbol)
{
if (full())
{
cout<<“\nStack overflow:\n”;
}
else
{
top=top+1;
stack_array [top] = symbol;
}
}
//POP FUNCTION
char pop()
{
if (empty())
return (‘#’); // Return value ‘#’ indicates
stack is empty
else
return (stack_array[top-1);
}
int empty()
{
if (top==-1)
return (1);
else
return (0);
}
int full()
{
if (top==49)
return (1);
else
return (0);
}
Self-Instructional
Material 39
Linear Data Structure }; //STACK CLASS CLOSED
//EXPRESSION CLASS DECLARATION
class Expression
{
NOTES
char infix[MAX];
char postfix[MAX];
public:
//INPUT FUNCTION TO TAKE INFIX EXPRESSION FROM THE USER
void input()
{
cout<<“\nEnter an infix expression: (Ex. 2+3-(7*6)”;
cin>>infix;
}
int white_space(char symbol)
{
if(symbol==’ ‘ || symbol==’\t’ || symbol==’\0')
return 1;
else
return 0;
}
//POSTFIX CONVERSION FUNCTION
void ConvertToPostfix()
{
stack s;
int l,precedence,p;
char entry1,entry2;
p=0;
for(int i=0;infix[i]!=’\0';i++)
{
entry1=infix[i];
if(!white_space(entry1))
{
Switch (entry1)
{
case ‘(‘:
s.push(entry1);
break;
case ‘)’:
while ((entry2=s.pop())!=’(‘)
postfix [p++]=entry2;
Self-Instructional
40 Material
break; Linear Data Structure
case ‘+’:
case ‘-’:
case ‘*’:
NOTES
case ‘/’:
if (!s.empty())
{
precedence = prec(entry1);
entry2=s.pop();
while (precedence<=prec(entry2))
{
Postfix [p++] =entry2;
if (!s.empty())
entry2= s.pop ();
else
break;
}
if (precedence>prec(entry2))
s.push (entry2);
}
s.push (entry1);
break;
default:
postfix [p++]=entry1;
break;
}
}
}
while (!s.empty()) //while stack is not
empty
postfix [p++]=s.pop();

postfix [p]=’\0';
cout<<“\nThe postfix expression is: “<<postfix<<endl;
}
int prec(char symbol)
{
Switch (symbol)
{
case ‘/’:

Self-Instructional
Material 41
Linear Data Structure // Precedence of / is 4
return(4);
case ‘*’:
// Precedence of * is 3
NOTES
return(3);
case ‘+’:
// Precedence of + is 2
return(2);
case ‘-’:
// Precedence of - is 1
return(1);
case ‘(‘:
// Precedence of ( is 0
return(0);
default:
return(-1);
}
}
};
int main()
{
char ch=’y’;
Expression expr;
do
{
expr.input();
expr.ConvertToPostfix();
cout<<“\n\nDo you want to continue ? (y/n): “;
cin>>ch;
}while(ch==’y’ || ch==’Y’);
return 0;
}
Output:

Self-Instructional
42 Material
Algorithm: For evaluation of postfix expression using stack. Linear Data Structure

Description:
Here P is an arithmetic expression written in postfix expression. Stack is an array
where we will PUSH all the operands and final value. NOTES
TOP is the top most element of Stack where insertion and deletion is allowed
1. Add a Right Parenthesis “)” at the end of P postfix expression.
2. Scan P from left to right and repeat Step 3 to 4 for each element of P until
“)” is encountered.
3. If an operand is encountered, add it to STACK.
4. If an operator * is encountered, then
a) Remove two TOP elements of the stack where A is the TOP and B is
the TOP-1 element.
b) Evaluate B * A.
c) Place the result of step (b ) on to Stack
5. Set value equal to TOP element on stack.
6. Exit.
3. Write a program to evaluate postfix expressions using stack.
//C++ program to evaluate of Postfix Expressions Using
Stack
#include <iostream.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
const int MAX = 50 ;
//Postfix class declaration
class postfix
{
private:
int stack[MAX] ;
int top, nn ;
char *s ;
public:
//constructor
postfix ( )
{
top = -1 ;
}
Self-Instructional
Material 43
Linear Data Structure void setexpr ( char *str )
{
s = str;
}
NOTES
void push ( int item )
{
if ( top == MAX - 1 )
cout << endl << “Stack overflow “ ;
else
{
top++;
stack [top] = item ;
}
}
int pop( )
{
if ( top == -1 )
{
cout << endl << “Stack underflow “ ;
return NULL ;
}
int data = stack[top] ;
top—;
return data ;
}
void calculate( )
{
int n1, n2, n3 ;
while ( *s )
{
if ( *s == ‘ ‘ || *s == ‘\t’ )
{
s++;
continue;
}
if ( isdigit ( *s ) )
{
nn = *s - ‘0’ ;
push ( nn ) ;
}
Self-Instructional
44 Material
else Linear Data Structure
{
n1 = pop ( );
n2 = pop ( );
NOTES
switch ( *s )
{
case ‘+’ :
n3 = n2 + n1 ;
break ;
case ‘-’ :
n3 = n2 - n1 ;
break ;
case ‘/’ :
n3 = n2 / n1 ;
break ;
case ‘*’ :
n3 = n2 * n1 ;
break ;
case ‘%’ :
n3 = n2 % n1 ;
break ;
case ‘$’ :
n3 = pow ( n2 , n1 ) ;
break ;
default :
cout << “Invalid operator” ;
exit ( 1 ) ;
}

push ( n3 ) ;
}
s++ ;
}
}
void show( )
{
nn = pop ( ) ;
cout << “Final Result : “ << nn ;
}

Self-Instructional
Material 45
Linear Data Structure } ;
void main( )
{
char expr[MAX] ;
NOTES
cout << “\nEnter postfix expression to be evaluated :
“ ;
cin.getline (expr, MAX);
postfix q ;
q.setexpr (expr);
q.calculate ( );
q.show ( );
}
Algorithm to Push Value in Stack Using Linked List

Description:
Here TOP is a pointer variable which contains the address
of Top node.
NEW is the new node to be inserted in linked list.
INFO is data to be inserted in linked list
PUSH_STACK (TOP, INFO)
[OVERFLOW?]
1 IF NEW = NULL THEN
WRITE: OVERFLOW
EXIT
2 ELSE
IF TOP = NULL THEN
SET NEXT [TOP] = NULL

ELSE
SET NEXT [NEW] = TOP
[END OF IF]
SET DATA [TOP] = INFO
SET TOP = NEW
[END OF IF]
3 END
Algorithm To Pop Value From Stack Using Linked List

Description:
Here TOP is the Top node of Stack to be deleted
TEMP is name given to the node to be deleted from the list
Self-Instructional
46 Material
POP_STACK (TOP) Linear Data Structure
[UNDERFLOW?]
IF TOP = NULL THEN
WRITE: UNDER FLOW
NOTES
EXIT
ELSE
SET INFO=DATA [TOP]
SET TEMP = TOP
SET TOP =NEXT [TOP]
DELETE TEMP
[END OF IF]
END
4. Write a program to implement stack using linked list.
//C++ program for Stack implementation using linked list
#include <iostream.h>

//structure for NODE


struct NODE
{
int data;
NODE *next;
};

class STACK
{
private:
NODE *top,*temp,*curr;
public:
STACK ()
{
top= NULL;
}
//PUSH Function to insert value to Stack
void push(int d)
{
temp = new NODE; //allocate memory to new node
temp->data = d;
if (temp==NULL)
{
cout<<“Overflow”;
Self-Instructional
Material 47
Linear Data Structure }
else if (top==NULL)
{
top=temp;
NOTES
top->next=NULL;

}
else
{
temp->next=top;
top=temp;

}
//POP Function to delete value from Stack
int pop()
{
int d;
if (top==NULL)
{
cout<<“Underflow”;
}
else
{
d= top->data ;
temp=top;
top=top->next;
delete temp;
}
return d;
}

//Function to traversal/print STACK


void traversal()
{
if(top == NULL)
{
cout << “Underflow” << endl;
}
Self-Instructional
48 Material
else Linear Data Structure
{
curr= top;
while (curr!=NULL)
NOTES
{cout << curr->data << endl;

curr= curr->next;
}

}
}

};

//MAIN FUNCTION
int main()
{
STACK s;
int d, ch;
char ans;

cout<<“ Stack operations”;

do
{
cout<<“\n 1.Push\n 2.Pop\n 3.Print “;
cout<<“\n Enter your choice \n”;
cin>>ch;
switch (ch)
{
case 1:
{
cout<<“\nEnter value to be inserted “;
cin>>d;
s.push (d);
break;
}
case 2:
Self-Instructional
Material 49
Linear Data Structure {
d=s.pop ();
cout<<“\n Deleted value “<<d;
break;
NOTES
}

case 3:
{
cout<<“\n Stack Value are \n”;
s.traversal ();
break;
}
default:
{
cout<<“\n Invalid choice \n”;
}
}
cout<<“\n\nCont...(y/n)”;
cin>>ans;
}
while (ans==’y’|| ans==’Y’);
}
Output:

Self-Instructional
50 Material
Linear Data Structure
Try yourself:
(1) Write a program to solving Towers of Hanoi problem that using a recursive
function.
(2) Write a program to convert infix expression to prefix expression. NOTES
Queues: Queue Implementation, Applications of Queue

Algorithms for queue Insertion using Array


INSERT _QUEUE (INT DATA)
IF (REAR=SIZE) THEN
WRITE “QUEUE IS FULL”
ELSE IF (REAR=0) THEN
FRONT=1
END IF
REAR=REAR+1
QUEUE [REAR]=DATA
EXIT
Algorithms for queue deletion using Array
DELETE-QUEUE ( )
IF (FRONT=0) THEN
WRITE “QUEUE IS EMPTY”
ELSE
ITEM=QUEUE [FRONT]
IF (FRONT=REAR) THEN
REAR=0
FRONT=0
ELSE
FRONT=FRONT+1
END IF
END IF
EXIT
5. Write a program to implement queue using linked list.
//C++ program for Queue implementation using linked list
#include <iostream>
using namespace std;
//structure for NODE
struct NODE
{
int data;
Self-Instructional
Material 51
Linear Data Structure NODE *next;
};

class QUEUE
NOTES
{
private:
NODE *front,*rear,*temp,*curr;
public:
QUEUE()
{
front=rear= NULL;
}
//enQueue (Insertion) Function to insert value to Queue
void enQueue(int d)
{
temp = new NODE; //allocate memory to new node
temp->data = d;
if (temp==NULL)
{
cout<<“Overflow”;
}

else if (front==NULL)
{
front=rear=temp;
rear->next=NULL;

}
else
{
rear -> next = temp;
rear = temp;

}
//deQueue (delete) Function to delete value from Queue
int deQueue()
{
int d;
Self-Instructional
52 Material
if(front == NULL) Linear Data Structure
{
cout<<“Queue is Empty”;
}
NOTES
else
{
d= front->data;
temp=front;
front = front -> next;
delete temp;
}
return d;
}

//Function to traversal/print STACK


void traversal()
{
if (front == NULL)
{
cout << “Underflow” << endl;
}
else
{
curr=front;
while (curr!=NULL)
{cout << curr->data << endl;

curr=curr->next;
}

}
}

};

//MAIN FUNCTION
int main()
{
QUEUE q;
Self-Instructional
Material 53
Linear Data Structure int d, ch;
char ans;
cout<<“ Queue operations”;

NOTES
do
{
cout<<“\n 1.Insert \n 2.Delete \n 3.Print “;
cout<<“\n Enter your choice \n”;
cin>>ch;
switch(ch)
{
case 1:
{
cout<<“\nEnter value to be inserted “;
cin>>d;
q. enQueue( d);
break;
}
case 2:
{
d=q.deQueue();
cout<<“\n Deleted value “<<d;
break;
}

case 3:
{
cout<<“\n Queue Value are \n”;
q.traversal();
break;
}
default:
{
cout<<“\n Invalid choice \n”;
}
}
cout<<“\n\nCont...(y/n)”;
cin>>ans;
}while(ans==’y’|| ans==’Y’);
}
Self-Instructional
54 Material
Output: Linear Data Structure

NOTES

Try yourself:
(1) Write a program to implement queue using array.
(2) Write a program to implement priority queue.
6. Write a program to insert a node at the beginning of singly linked list.
//C++ program to insert node at the beginning of single
linked list
#include <iostream.h>

//structure for NODE


struct NODE
{
int data;
NODE *next;
};
Self-Instructional
Material 55
Linear Data Structure class linked_list
{
private:
NODE *start,*end,*temp,*curr;
NOTES
public:
linked_list()
{
start = end= NULL;
}
//Function to insert at the beginning
void insert_beginning (int d)
{
temp = new NODE; //allocate memory to new node
temp->data = d;
temp->next = NULL;

if(start == NULL)
{
start =end= temp;
end->next=NULL;
}
else
{
temp->next = start;
start=temp;
}
}
//Function to traversal/print single linked list
void traversal()
{
if(start == NULL)
{
cout << “Underflow” << endl;
}
else
{
curr=start;
while(curr!=NULL)
{cout << curr->data << endl;
curr=curr->next;
Self-Instructional
56 Material
} Linear Data Structure

}
}
NOTES
};
void main()
{
linked_list list;
int d;
char ans;
do
{
cout<<“\nEnter value to be inserted “;
cin>>d;
list.insert_beginning (d);
cout<<“\n\nCont...(y/n)”;
cin>>ans;
}while(ans==’y’|| ans==’Y’);

cout<<“\n Value are \n”;


list.traversal();

}
Output:

Self-Instructional
Material 57
Linear Data Structure 7. Write a program to insert a node at the end of singly linked list.
//C++ program to Insert Node at the end of single linked
list
#include <iostream.h>
NOTES
struct NODE
{
int data;
NODE *next;
};
class linked_list
{
private:
NODE *start,*end,*temp,*curr;
public:
linked_list()
{
start = end= NULL;
}
//Function to insert at the end
void insert_end(int d)
{
temp = new NODE; //allocate memory to new node
temp->data = d;
temp->next = NULL;

if(start == NULL)
{
start =end= temp;
end->next=NULL;
}
else
{
end->next=temp;
end=temp;
}
}
//Function to traversal/print single linked list
void traversal()
{

Self-Instructional
58 Material
if(start == NULL) Linear Data Structure
{
cout << “Underflow” << endl;
}
NOTES
else
{
curr=start;
while(curr!=NULL)
{cout << curr->data << endl;

curr=curr->next;
}

}
}
};

void main()
{
linked_list list;
int d;
char ans;
do
{
cout<<“\nEnter value to be inserted “;
cin>>d;
list.insert_end(d);
cout<<“\n\nCont...(y/n)”;
cin>>ans;
}while(ans==’y’|| ans==’Y’);

cout<<“\n Value are \n”;


list.traversal();

Self-Instructional
Material 59
Linear Data Structure Output:

NOTES

8. Write a program to insert a node at the beginning of double linked list.


//C++ program to insert node at the beginning of double
linked list
#include <iostream.h>

//structure for NODE


struct NODE
{
NODE *prev;
int data;
NODE *next;
};
class linked_list
{
private:
NODE *start,*end,*temp,*curr;
public:
linked_list()
{
start = end= NULL;
}
//Function to insert at the beginning in double linked
list
void insert_beginning (int d)
{
temp = new NODE; //allocate memory to new node
temp->data = d;
Self-Instructional
60 Material
temp->next = NULL; Linear Data Structure
if(start == NULL)
{
start =end= temp;
NOTES
end->next=NULL;
end->prev=NULL;
}
else
{
temp->prev=NULL;
temp->next=start;
start->prev=temp;
start=temp;
}
}

//Function to traversal/print double linked list (START


to END)
void traversal_S_to_E()
{
if(start == NULL)
{
cout << “Underflow” << endl;
}
else
{
curr=start;
while (curr!=NULL)
{cout << curr->data << endl;

curr=curr->next;
}

}
}

//Function to traversal/print double linked list (END to


START)
void traversal_E_to_S()
{
if(end == NULL)
Self-Instructional
Material 61
Linear Data Structure {
cout << “Underflow” << endl;
}
else
NOTES
{
curr=end;
while(curr!=NULL)
{cout << curr->data << endl;

curr=curr->prev;
}

}
}

};

//MAIN FUNCTION
int main()
{
linked_list list;
int d;
char ans;
do
{
cout<<“\nEnter value to be inserted “;
cin>>d;
list.insert_beginning (d);
cout<<“\n\nCont...(y/n)”;
cin>>ans;
}while(ans==’y’|| ans==’Y’);

cout<<“\n Value of list from start to end \n”;


list.traversal_S_to_E();
cout<<“\n Value of list from end to start \n”;
list.traversal_E_to_S();

Self-Instructional
62 Material
Output: Linear Data Structure

NOTES

9. Write a program to insert a node at the end of double linked list.


//C++ program to insert node at the end of double linked
list
#include <iostream.h>
//structure for NODE
struct NODE
{
NODE *prev;
int data;
NODE *next;
};
class linked_list
{
private:
NODE *start,*end,*temp,*curr;
public:
linked_list ()
{
start = end= NULL;
}
//Function to insert at the end in double linked list
void insert_end (int d)
{
temp = new NODE; //allocate memory to new node
temp->data = d;
temp->next = NULL;
if(start == NULL)
{

Self-Instructional
Material 63
Linear Data Structure start =end= temp;
end->next=NULL;
end->prev=NULL;
}
NOTES else
{
end->next=temp;
temp->prev=end;
temp->next=NULL;
end=temp;
}
}
//Function to traversal/print double linked list (START
to END)
void traversal_S_to_E()
{
if(start == NULL)
{
cout << “Underflow” << endl;
}
else
{
curr=start;
while (curr!=NULL)
{cout << curr->data << endl;
curr=curr->next;
}
}
}
//Function to traversal/print double linked list (END to
START)
void traversal_E_to_S()
{
if (end == NULL)
{
cout << “Underflow” << endl;
}
else
{
curr=end;
while (curr!=NULL)
{cout << curr->data << endl;
curr=curr->prev;
}

Self-Instructional
64 Material
} Linear Data Structure
}
};
//MAIN FUNCTION
int main() NOTES
{
linked_list list;
int d;
char ans;
do
{
cout<<“\nEnter value to be inserted “;
cin>>d;
list.insert_end (d);
cout<<“\n\nCont...(y/n)”;
cin>>ans;
}while (ans==’y’|| ans==’Y’);
cout<<“\n Value of list from start to end \n”;
list.traversal_S_to_E ();
cout<<“\n Value of list from end to start \n”;
list.traversal_E_to_S ();
}
Output:

Try yourself:
(1) Write a program to implement circular linked list.
(2) Write a program to merge two linked lists.
(3) Write a program to sort a linked list.

Self-Instructional
Material 65
Non Linear Data Structure

BLOCK IV NON LINEAR DATA


STRUCTURE
NOTES
Algorithm: For inorder traversal
A binary tree t is in memory. This algorithm does an inorder traversal of t. An array
stack is used to temporarily hold the address of nodes.
INORDER_TRAVERSAL (INFO, LEFT, RIGHT, ROOT)
1. [PUSH NULL TO STACK AND INITIALIZE PTR]
SET TOP = 1
SET STACK [TOP] =NULL
SET PTR = ROOT

2. REPEAT WHILE PTR ‘“ NULL


SET TOP = TOP +1
SET STACK [TOP] = PTR
SET PTR = LEFT [PTR]
[END OF LOOP]
3. SET PTR = STACK[TOP]
SET TOP = TOP -1
4. REPEAT STEPS 5 TO 7 WHILE PTR ‘“ NULL
5. APPLY PROCESS TO INFO[PTR]
6. [RIGHT CHILD?]
IF RIGHT [PTR] ‘“ NULL THEN
SET PTR = RIGHT [PTR]
GOTO STEP 2
[END OF IF]
7. SET PTR = STACK[TOP]
SET TOP = TOP -1
[END OF STEP 4 LOOP]
8. END
Algorithm: For pre-order traversal
A binary tree t is in memory. This algorithm does a preorder traversal of t. An
array stack is used to temporarily hold the address of nodes.
PREORDER _TRAVERSAL (INFO, LEFT, RIGHT, ROOT)
1. [INITIALLY PUSH NULL TO STACK AND INITIALIZE PTR]
SET TOP =1
SET STACK [TOP]:=NULL
SET PTR = ROOT
Self-Instructional 2. REPEAT STEPS 3 TO 5 WHILE PTR ‘“ NULL
66 Material
3. APPLY PROCESS TO INFO[PTR] Non Linear Data Structure
4. [RIGHT CHILD?]
IF RIGHT [PTR] ‘“ NULL THEN
SET PTR = RIGHT [PTR]
NOTES
SET TOP = TOP +1
SET STACK [TOP]:= RIGHT [PTR]
[END OF IF]

5. [LEFT CHILD?]
IF LEFT [PTR] ‘“ NULL THEN
SET PTR = LEFT [PTR]
ELSE
SET PTR = STACK [TOP]
SET TOP = TOP -1
[END OF IF]
[END OF LOOP]
6. END
Algorithm: For post-order traversal
A binary tree t is in memory. This algorithm does postorder traversal of t. An array
stack is used to temporarily hold the address of nodes.
POSTORDER _TRAVERSAL (INFO, LEFT, RIGHT, ROOT)
1. [INITIALLY PUSH NULL TO STACK AND INITIALIZE PTR]
SET TOP =1
SET STACK [1] =NULL
SET PTR =ROOT
2. [PUSH LEFT-MOST PATH ONTO STACK ]
REPEAT STEPS 3 TO 5 WHILE PTR ‘“ NULL
3. SET TOP:=TOP+1
SET STACK [TOP] =PTR

[PUSHES PTR ON STACK]


4. IF RIGHT[PTR] ‘“ NULL THEN [PUSH ON STACK]
SET TOP =TOP+1
SET STACK [TOP] = RIGHT [PTR]
[END OF IF STRUCTURE]
5. SET PTR = LEFT[PTR] [UPDATE POINTER PTR]
[END OF STEP 2 LOOP]
6. [POP NODE FROM STACK]
SET PTR = STACK [TOP]
SET TOP =TOP-1
Self-Instructional
Material 67
Non Linear Data Structure 7. REPEAT WHILE PTR>0
a. APPLY PROCESS TO INFO[PTR]
b. [POP NODE FROM STACK]
SET PTR = STACK [TOP]
NOTES
SET TOP =TOP-1
[END OF LOOP]
8. IF PTR<0 THEN
a) SET PTR:= -PRT
b) GOTO STEP 2
[END OF IF STRUCTURE]
9. END
1. Write a program for binary tree insertion and in-order traversal.
//C++ Program for inorder traversal of binary tree
# include <iostream.h>
//structure for NODE
struct NODE
{
int data;
struct NODE *left;
struct NODE *right;
}*root;

class BST
{
public:

//constructor
BST ()
{
root = NULL;
}
// Function to insert value into tree
void insert(NODE *tree, NODE *newnode)
{
if (root == NULL)
{
root = new NODE;
root->data = newnode->data;
root->left = NULL;
root->right = NULL;
Self-Instructional
68 Material
cout<<“Root Node is Added”<<endl; Non Linear Data Structure
return;
}
if (tree->data == newnode->data)
NOTES
{
cout<<“Element already in the tree”<<endl;
return;
}
if (tree->data > newnode->data)
{
if (tree->left != NULL)
{
insert(tree->left, newnode);
}
else
{
tree->left = newnode;
(tree->left)->left = NULL;
(tree->left)->right = NULL;
cout<<“Node Added To Left”<<endl;
return;
}
}
else
{
if (tree->right != NULL)
{
insert (tree->right, newnode);
}
else
{
tree->right = newnode;
(tree->right)->left = NULL;
(tree->right)->right = NULL;
cout<<“Node Added To Right”<<endl;
return;
}
}
}

Self-Instructional
Material 69
Non Linear Data Structure // Function for inorder tree traversal
void inorder (NODE *ptr)
{
if (root == NULL)
NOTES
{
cout<<“\n Underflow\n”;
return;
}
if (ptr != NULL)
{
inorder(ptr->left);
cout<<ptr->data<<“ “;
inorder(ptr->right);
}
}

// function to display tree structure


void display(NODE *ptr, int level)
{
int i;
if (ptr != NULL)
{
display (ptr->right, level+1);
cout<<endl;
if (ptr == root)
cout<<“Root->: “;
else
{
for (i = 0;i < level;i++)
cout<<“ “;
}
cout<<ptr->data;
display (ptr->left, level+1);
}}
};

// main function
int main()
{
int ch, num;
Self-Instructional
70 Material
BST bst; Non Linear Data Structure
NODE *temp;
char ans;
do
NOTES
{
cout<<“\n1.Insert Element “<<endl;
cout<<“2.Inorder Traversal”<<endl;
cout<<“3.Display Tree Structure”<<endl;
cout<<“4. Exit”<<endl;

cout<<“Enter your choice : “;


cin>>ch;
switch (ch)
{
case 1:
temp = new NODE;
cout<<“Enter value to be inserted : “;
cin>>temp->data;
bst.insert (root, temp);
break;
case 2:
cout<<“Inorder Traversal of BST:”<<endl;
bst.inorder (root);
break;
case 3:
cout<<“Display BST:”<<endl;
bst.display (root,1);
break;
case 4:
break;
default:
cout<<“Invalid choice”<<endl;
}
cout<<“\n\nCont...(y/n)”;
cin>>ans;
}while (ans==’y’|| ans==’Y’);

Self-Instructional
Material 71
Non Linear Data Structure Output:

NOTES

2. Write a program for binary tree insertion and preorder traversal.


//C++ Program for preorder traversal of binary tree
# include <iostream.h>
//structure for NODE
struct NODE
{
int data;
struct NODE *left;
struct NODE *right;
}*root;

class BST
{
public:
//constructor
BST ()
{
root = NULL;
}
Self-Instructional
72 Material
// Function to inserting value into tree Non Linear Data Structure
void insert(NODE *tree, NODE *newnode)
{
if (root == NULL)
NOTES
{
root = new NODE;
root->data = newnode->data;
root->left = NULL;
root->right = NULL;
cout<<“Root Node is Added”<<endl;
return;
}
if (tree->data == newnode->data)
{
cout<<“Element already in the tree”<<endl;
return;
}
if (tree->data > newnode->data)
{
if (tree->left != NULL)
{
insert (tree->left, newnode);
}
else
{
tree->left = newnode;
(tree->left)->left = NULL;
(tree->left)->right = NULL;
cout<<“Node Added To Left”<<endl;
return;
}
}
else
{
if (tree->right != NULL)
{
insert (tree->right, newnode);
}
else
{
Self-Instructional
Material 73
Non Linear Data Structure tree->right = newnode;
(tree->right)->left = NULL;
(tree->right)->right = NULL;
cout<<“Node Added To Right”<<endl;
NOTES
return;
}
}
}

// Function for preorder tree traversal


void preorder(NODE *ptr)
{
if (root == NULL)
{
cout<<“\nUnderflow\n”;
}
if (ptr != NULL)
{
cout<<ptr->data<<“ “;
preorder (ptr->left);
preorder (ptr->right);
}
}
};

// main function
int main()
{
int ch, num;
BST bst;
NODE *temp;
char ans;
do
{
cout<<“\n1.Insert element “<<endl;
cout<<“2.preorder traversal”<<endl;
cout<<“3. Exit”<<endl;

cout<<“Enter your choice : “;


cin>>ch;
Self-Instructional
switch(ch)
74 Material
{ Non Linear Data Structure
case 1:
temp = new NODE;
cout<<“Enter value to be inserted : “;
NOTES
cin>>temp->data;
bst.insert(root, temp);
break;
case 2:
cout<<“preorder Traversal of BST:”<<endl;
bst.preorder(root);
break;
case 3:
break;
default:
cout<<“Invalid choice”<<endl;
}
cout<<“\n\nCont...(y/n)”;
cin>>ans;
}while(ans==’y’|| ans==’Y’);

}
Output:

Self-Instructional
Material 75
Non Linear Data Structure 3. Write a program for binary tree insertion and post-order traversal.
//C++ Program for postorder traversal of binary tree
# include <iostream.h>
NOTES
//structure for NODE
struct NODE
{
int data;
struct NODE *left;
struct NODE *right;
}*root;

class BST
{
public:

//constructor
BST ()
{
root = NULL;
}
// Function to insert value into tree
void insert(NODE *tree, NODE *newnode)
{
if (root == NULL)
{
root = new NODE;
root->data = newnode->data;
root->left = NULL;
root->right = NULL;
cout<<“Root Node is Added”<<endl;
return;
}
if (tree->data == newnode->data)
{
cout<<“Element already in the tree”<<endl;
return;
}
if (tree->data > newnode->data)
{
Self-Instructional
76 Material
if (tree->left != NULL) Non Linear Data Structure
{
insert(tree->left, newnode);
}
NOTES
else
{
tree->left = newnode;
(tree->left)->left = NULL;
(tree->left)->right = NULL;
cout<<“Node Added To Left”<<endl;
return;
}
}
else
{
if (tree->right != NULL)
{
insert (tree->right, newnode);
}
else
{
tree->right = newnode;
(tree->right)->left = NULL;
(tree->right)->right = NULL;
cout<<“Node Added To Right”<<endl;
return;
}
}
}

// Function for postorder tree traversal

void postorder(NODE *ptr)


{
if (root == NULL)
{
cout<<“\n Underflow”<<endl;
return;
}
if (ptr != NULL)
Self-Instructional
Material 77
Non Linear Data Structure {
postorder (ptr->left);
postorder (ptr->right);
cout<<ptr->data<<“ “;
NOTES
}
}
};

// main function
int main()
{
int ch, num;
BST bst;
NODE *temp;
char ans;
do
{
cout<<“\n1.Insert element “<<endl;
cout<<“2.post-order traversal”<<endl;
cout<<“3. Exit”<<endl;

cout<<“Enter your choice : “;


cin>>ch;
switch (ch)
{
case 1:
temp = new NODE;
cout<<“Enter value to be inserted : “;
cin>>temp->data;
bst.insert(root, temp);
break;
case 2:
cout<<“post-order Traversal of BST:”<<endl;
bst.postorder(root);
break;
case 3:
break;
default:
cout<<“Invalid choice”<<endl;
}
Self-Instructional
78 Material
cout<<“\n\nCont...(y/n)”; Non Linear Data Structure
cin>>ans;
}while (ans==’y’|| ans==’Y’);
}
NOTES
Output:

Try yourself:
(1) Write a program to check whether a tree is a binary search tree.
(2) Write a program to search an element in a tree recursively.
(3) Write a program for depth first binary tree search using recursion.
(4) Write a program to find the largest value in a tree using inorder traversal.
Graphs

Directed Graph (digraph)


In a directed graph, the edges are represented by ordered pairs of vertices (u, v)
and shown diagrammatically as directed arrows.

Self-Instructional
Material 79
Non Linear Data Structure

NOTES

An edge (u, v) is incident from (i.e. leaves) u and is incident to (i.e.


enters) v. If a graph contains an edge (u, v), then v is adjacent to u and is
represented notationally as u  v.
Note v being adjacent to u does not imply that u is adjacent to v unless
edge (v, u)  E. Thus (u, v) and (v, u) are distinct edges in a directed graph.
We say that u and v are neighbours if either (u, v)  E or (v, u)  E.
For each vertex we define the out-degree as the number of edges leaving
the vertex, in-degree as the number of edges entering a vertex, and
the degree as out-degree + in-degree (i.e. total number of edges at the vertex).
If a vertex has degree = 0, then the vertex is isolated.
If the directed graph has no self-loops, then it is a simple directed graph.
Undirected Graph
In an undirected graph, the edges are represented by unordered pairs of vertices.
Thus (u, v) and (v, u) represent the same edge and are shown diagrammatically
as simply a connecting line (note undirected graphs may not contain self-loops).

An edge (u, v) is incident on u and v, and u and v are adjacent to each


other.
The degree is the number of edges incident on a vertex.
To convert an undirected graph into a directed one, simply replace each
edge (u, v) with (u, v) and (v, u). Conversely to convert a directed graph into an
undirected one, replace each edge (u, v) or (v, u) with (u, v) and remove all self-
loops.
Self-Instructional
80 Material
Paths Non Linear Data Structure

A path of length k from u to u’ is a sequence of vertices <v0, v1, ..., vk>


with u = v0, u’ = vk, and (vi-1, vi)  E.
If a path p from u to u’ exists, then u’ is reachable from u (denoted uu’ NOTES
if G is a directed graph).
The path is simple if all the vertices are distinct.
A subpath is a contiguous subsequence <vi, vi+1, ..., vj> with 0  i  j  k.
A cycle is a path with v0 = vk (and is also simple if all the vertices except
the end points are distinct). An acyclic graph is a graph with no cycles.
Connected Components
In an undirected graph, a connected component is a subset of vertices thar are
all reachable from each other. The graph is connected if it contains exactly one
connected component, i.e. every vertex is reachable from everyother.
In a directed graph, a strongly connected component is a subset
of mutually reachable vertices, i.e. there is a path between any two vertices in the
set.
Special Graphs
A complete graph an undirected graph where all vertices are adjacent to all other
vertices, i.e. there are edges between every pair of vertices.
A bipartite graph is an undirected graph that can be partitioned into V1
and V2 such that for every edge (u, v)  E either
u  V1 and v  V2 OR u  V2 and v  V1
i.e. the graph can be separated so that the only edges are between vertices
in different subsets.
A forest is an undirected acyclic graph. If it is also connected, then it is
a tree.
A directed acyclic graph is known as a DAG.
Graph Representation
Two common methods for implementing a graph in software is either using
an adjacency list or an adjacency matrix.
Adjacency List
In an adjacency list implementation, we simply store the adjacent vertices (i.e.
edges) for each vertex in a linked list denoted Adj[u]. If we sum up the lengths of
all the adjacency lists, we get either

Self-Instructional
Material 81
Non Linear Data Structure

 (V + E) storage is required.


NOTES
This representation is good for sparse graphs where |E| << |V|2. One
drawback is that to determine if an edge (u, v)  E requires a list search (V).
For the original directed graph, the adjacency list would be

Adjacency Matrix
In an adjacency matrix implementation, we store the edges in a V×V matrix A either
as binary values or real numbers for weighted edges.
 (V2) storage is required (independent of E).
This representation is good for dense graphs where |E|  |V|2. The advantage
is it only takes (1) time to determine if an edge (u, v)  E since it is simply a
matrix element access. If the graph is undirected, then A = AT so only the upper
triangular half needs to be stored.
For the original directed graph, the adjacency matrix would be

Self-Instructional
82 Material
Shortest Path Algorithms Non Linear Data Structure

(i) Dijkstra’s Algorithm


Dijkstra's algorithm maintains a set S of vertices where minimum paths have been NOTES
found and a priority queue Q of the remaining vertices under discovery ordered
by increasing u.d's.
DIJKSTRA (G,w,s)
1. INITIALIZE-SINGLE-SOURCE (G,s)
2. S=
3. Q = G.V
4. while Q  
5. u = EXTRACT-MIN(Q)
6. S = S  {u}
7. for each vertex v  G.Adj[u]
8. RELAX(u,v,w)
INITIALIZE-SINGLE-SOURCE (G,s)
1. for each vertex v G.V
2. v.d =
3. v.pi = NIL
4. s.d = 0
RELAX (u,v,w)
1. if v.d > u.d + w(u,v)
2. v.d = u.d + w(u,v)
3. v.pi = u
(ii) Floyd-Warshall Algorithm for finding Shortest Path
The Floyd-Warshall algorithm works based on a property of intermediate vertices
of a shortest path. An intermediate vertex for a path p = <v1, v2, ..., vj> is any
vertex other than v1 or vj.
Algorithm:
FLOYD-WARSHALL(W)
1. n = W.rows
2. D(0) = W
3. (0) = (0)ij = NIL if i=j or wij =
= i if ij and wij <
4. for k = 1 to n
5. let D(k) = (d(k)ij) be a new nxn matrix
6. for i = 1 to n
7. for j = 1 to n
Self-Instructional
Material 83
Non Linear Data Structure 8. dk ij = min(d(k-1)ij, d(k-1)ik + d(k-1)kj)
9. if d(k-1)ij  d(k-1)ik + d(k-1)kj
10. (k)ij = (k-1)ij
11. else
NOTES
12. (k)ij = (k-1)kj
13. return D(n)
Basically the algorithm works by repeatedly exploring paths between every pair
using each vertex as an intermediate vertex.
Minimum cost Spanning Trees

(i) Kruskal’s Algorithm


Kruskal’s algorithm is a greedy algorithm. To find out minimum spanning tree
(MST) of a connected and weighted graph, we use Kruskal’s algorithm. This
means it finds a subset of the edges to forms a tree including each vertex in such a
way that the total weight of all the edges in the tree is minimal. In case a graph is
not a connected graph it finds a MST connected component and that is a minimum
spanning forest.
Algorithm:
MST-KRUSKAL (G,w)
A=
for each vertex v  G.V
MAKE-SET (v)
sort the edges of G.E into nondecreasing order by weight w
for each edge (u,v)  G.E, taken in nondecreasing order by weight
if FIND-SET(u)  FIND-SET(v)
A = A  {(u,v)}
UNION (u,v)
return A
Basically the algorithm works as follows:
1. Make each vertex a separate tree
2. Sort the edges in nondecreasing order
3. Add an edge if it connects different trees and merge the trees together
The run time of Kruskal's algorithm depends on the implementation of the
set operations, but can be made to run in O(E lg V).
(ii) Prims Algorithm
Prim's algorithm is a very simple modification to Dijkstra's shortest path algorithm.
Self-Instructional
With Prim's algorithm, you build the minimum spanning tree node by node. You
84 Material
are going to maintain a "current spanning tree", which will be a subset of the nodes Non Linear Data Structure

in the graph, and the edges that compose a minimum spanning tree of those nodes.
Algorithm:
MST-PRIM (G,w,r) NOTES
1. for each u  G.V
2. u.key =
3. u.pi = NIL
4. r.key = 0
5. Q = G.V
6. while Q 
7. u = EXTRACT-MIN(Q)
8. for each v  G.Adj[u]
9. if v  Q and w(u,v) < v.key
10. v.pi = u
11. v.key = w(u,v)
Basically the algorithm works as follows:
1. Initialize Q and set the source (root) key to 0
2. While Q is not empty, dequeue the vertex with minimum weight edge and
add it to the tree by adding edge (u.,u) to T
3. For each vertex v in Adj[u] that is still in Q, check if w(u,v) (the edge weights
from u for all vertices not in T) are less than the current v.key (the current
smallest edge weight) and if so update the predecessor and key fields
Graph traversing Methods
1. Breadth First Search(BFS)
2. Depth First Search(DFS)
Algorithm for BFS (Breadth First Search):
This Algorithm executes a breadth first search on a graph G beginning at a starting
node A
1. [Initialize all nodes to the ready state]
Set status:=1
2. Put the starting node A in Queue and change its status to the
Set status :=2
3. Repeat steps 4 and 5 until Queue is Empty:

Self-Instructional
Material 85
Non Linear Data Structure 4. Remove the front node N of Queue process N and change the status of N
to the processed
state
NOTES Set status: =3
5. Add to the rear of Queue all the neighbors of N that are in the ready state
(state=1), and
Change their status to the waiting state
Set status:=2
[End of step 3 loop]
End
Algorithm for DFS (Depth First Search)
This algorithm executes a Depth First Search on a graph G beginning A
1. [initialize all nodes to the ready state ]
Set status: =1
2. Push the starting node A onto stack and change its status to the waiting
state
Set status: =2
3. Repeat step 4 and 5 until stack is empty
4. Pop the top node N of stack . process N and change its status to the
processed state
Set status: =3
5. Push onto stack all the neighbors of N that are still in the ready state
(status=1),and change their status to the waiting state
Set status: =2
[End of step 3 loop]
6. End
DFS Applications:
DFS can be used directly, but is more often used as an intermediate technique
within another algorithm. This lecture examines three applications of DFS.
 Parenthesis Theorem
 Topological Sorting
 Strongly Connected Component Decomposition (SCCD)

Self-Instructional
86 Material
Searching and Sorting

BLOCK V SEARCHING AND Algorithms

SORTING ALGORITHMS
NOTES
Searching refers to the operation of finding the location of a given item in a collection
of items.
Algorithm for Sequential Search
INPUT : LIST OF SIZE N, TARGET VALUE T
OUTPUT : POSITION OF T IN THE LIST
1. BEGIN
2. SET FOUND = FALSE
SET I = 0
3. WHILE IN AND FOUND IS FALSE
IF LIST [I] = T THEN
SET FOUND = TRUE
EXIT
ELSE
SET I =I+1
[END OF STEP 3 LOOP]
4. IF FOUND = FALSE THEN
WRITE: T IS NOT IN LIST
ELSE
WRITE: T IS FOUND AT I LOCATION
[END OF IF]
5 . END
1. Write a program to search a given value in an array using sequential search.
//C++ program for sequential search
#include <iostream.h>
//definition of sequential_Search function
void sequential_search (int a[ ] ,int size ,int key)
{
int flag , i ;
flag =0;
for ( i=0 ; i<size ; i++)
{
if ( a [i] == key )
{
flag = 1 ;
break ;
Self-Instructional
Material 87
Searching and Sorting }
Algorithms
}
if ( flag == 1)
cout<<"value found at "<<i+1<<"location";
NOTES
else
cout<<"value not found";
}
void main()
{
int arr[10],i,k;
cout<<"Enter 10 values";
for(i=0;i<10;i++)
cin>>arr[i];

cout<<"Enter values to be searched";


cin>>k;
//call of sequential_search function
sequential_search (arr, 10, k);
}
Output:

Algorithm for Binary Search


INPUT : SORTED LIST OF SIZE N, KEY VALUE KEY
OUTPUT : POSITION OF KEY IN THE LIST = KEY
1. BEGIN
2. [INTIALIZE]
SET MAX = SIZE
SET MIN = 1
SET FOUND = FALSE
3. WHILE (FOUND IS FALSE AND MAX ?MIN)
SET MID = (MAX + MIN)/2
4. IF KEY = LIST [MID] THEN
Self-Instructional SET I = MID
88 Material
SET FOUND = TRUE Searching and Sorting
Algorithms
EXIT
ELSE IF KEY < LIST [MID] THEN
SET MAX = MID -1
NOTES
ELSE
SET MIN = MIN +1
[END OF IF]
[END OF LOOP]
5. IF FOUND = FALSE THEN
WRITE: VALUE IS NOT IN LIST
ELSE
WRITE VALUE FOUND AT MID LOCATION
6. END
2. Write a program to search an element in the array using binary search.
//C++ program for binary Search

#include <iostream.h>
// Binary Search Function
void binary_search (int a[ ] , int size , int key)
{
int low ,high ,mid ,flag ;
flag= 0;
low = 0;
high = size -1;
while (low <= high && flag ==0)
{
mid =(low +high)/2;
if ( key == a [mid])
{
flag=1;
break;
}
else if (key < a[mid ] )
{
high = mid -1;
}
else
{
low = mid +1;
}
Self-Instructional
Material 89
Searching and Sorting }
Algorithms
if ( flag ==1)
{
cout<<"value found at location"<<mid +1;
NOTES
}
else
cout<<"value not found";
}

void main()
{
int arr[10],i,k;
cout<<"Enter 10 values\n";
for(i=0;i<10;i++)
cin>>arr[i];

cout<<"Enter value to be searched ";


cin>>k;
//call of binary_Search function
binary_search(arr,10,k);
}
Output:

Sorting techniques: Bubble sort, Quick sort, Insertion sort, Merge sort
Sorting refers to the operation of arranging data in some given order such as
increasing or decreasing with numerical data and alphabetically with character
data.
Selection Sort
Selection sort algorithm starts by comparing first two elements of an array and
swapping if necessary.

Self-Instructional
90 Material
This algorithm is not suitable for large data sets as its average and worst Searching and Sorting
Algorithms
case complexities are of (n2), where n is the number of items.
3. Write a program to sort an array using selection sort.
//C++ program for selection sort NOTES
#include <iostream.h>
void selection_sort (int a[ ], int size )
{
int temp ,i,j, min;

for(int i = 0; i < size-1 ; i++) {

min = i ; //considering element i as minimum

for(int j = i+1; j < size ; j++ )


{
if(a[ j ] < a[ min ])
{
min = j ;
}
}
temp= a[ min ];
a[ min ]=a[ i ] ;
a[ i]=temp;

}
}
//main function
void main()
{
int arr[10],i;
cout<<"Enter 10 values\n";
for(i=0;i<10;i++)
cin>>arr[i];
//call of selection sort function
selection_sort(arr,10);
cout<<" \n Sorted Values \n";
for(i=0;i<10;i++)
cout<<endl<<arr[i];
}

Self-Instructional
Material 91
Searching and Sorting Output:
Algorithms

NOTES

4. Write a program to sort an array using bubble sort.


//C++ program for bubble sort
#include <iostream.h>
void bubble_sort (int a[ ], int size )
{
int temp ,i,j;
for (i=0; i<size; i++)
{
for (j=0; j<size-1; j++)
{

if(a[j]>a[j+1])
{
temp =a[j];
a[j]=a[j+1];
a[j+1]=temp;
} }
}
}
/main function

void main()
{
int arr[10],i;
cout<<"Enter 10 values\n";
for (i=0;i<10;i++)
Self-Instructional cin>>arr[i];
92 Material
//call of bubble sort function Searching and Sorting
Algorithms
bubble_sort(arr,10);

cout<<" \n Sorted Values \n";


NOTES
for(i=0;i<10;i++)
cout<<endl<<arr[i];
}
Output:

Insertion Sort Algorithm


ALGORITHM - INSERTION SORT
INPUT - LIST [ ] OF N ITEMS
OUTPUT - LIST [ ] OF N ITEMS IN SORTED ORDER
1. BEGIN
2. FOR I = 2 TO N DO
3. IF LIST [I] < LIST [I -1] THEN
4. SET I : = I - 1
5. SET TEMP: = LIST [I]
6. REPEAT
7. SET LIST [J + 1] = LIST [J];
8. SET I : = J - 1
9. UNTIL (J  1 AND LIST [J]> TEMP)
10. SET LIST [J+1] : =TEMP
[END OF IF]
[END OF STEP 2 LOOP]
10. END
5. Write a C++ program to sort an array using insertion sort.
//C++ program for insertion sort
#include <iostream.h> Self-Instructional
Material 93
Searching and Sorting /insertion sort function definition
Algorithms
void insert_sort(int a[ ],int size)
{
int i,temp,j;
NOTES
for (i = 1; i < size; i++)
{
temp = a[i];
j = i-1;
while (j >= 0 && a[j] > temp)
{
a[j+1] = a[j];
j--;
}
a[j+1] = temp;
}
}

//main function
void main()
{
int arr[10],i,k;
cout<<"Enter 10 values\n";
for(i=0;i<5;i++)
cin>>arr[i];
//call of Insertion Sort function
insert_sort (arr, 5);
cout<<" \n Sorted Values \n";
for (i=0;i<5;i++)
cout<<endl<<arr[i];
}
Output:

Self-Instructional
94 Material
Algorithm for Quick Sort Searching and Sorting
Algorithms
QUICK_SORT ( ARRAY ,FIRST ,LAST )
1. SET LOW : = FIRST
SET HIGH : = LAST NOTES
SET PIVOT : =ARRAY[( LOW + HIGH) /2 ]
2. REPEAT THROUGH STEP 7 WHILE (LOW ?HIGH)
3. REPEAT STEP 4 WHILE (ARRAY [LOW]<PIVOT)
4. SET LOW := LOW+1
5. REPEAT STEP 6 WHILE (ARRAY [HIGH]>PIVOT)
6. SET HIGH := HIGH-1
7. IF (LOW <=HIGH)
ARRAY [LOW] <->ARRAY [HIGH]
SET LOW := LOW+1
SET HIGH:= HIGH-1
8. IF (FIORST<HIGH) THEN
QUICK_SORT (ARRAY,FIRST,HIGH)
9. IF (LOW < LAST)
QUICK_SORT (ARRAY,LOW,LAST)
10. END
6. Write a C++ program to sort an array using quick sort.
//C++ program for quick sort
#include <iostream.h>
void quick_sort (int a[ ], int first, int last)
{
int low ,high ,pivot, temp, i ;
low= first ;
high =last ;
pivot =a[(first +last)/2];
do
{
while (a[low]<pivot)
{
low++;
}
while (a [high]>pivot)
{
high--;
}
if(low <=high)
{ Self-Instructional
Material 95
Searching and Sorting temp= a [low];
Algorithms
a [low]= a[high];
a[high]= temp ;
low++;
NOTES
high--;
}
}while (low <=high);
if (first <high)
{
quick_sort (a, first, high);
}
if(low< last)
{
quick_sort (a, low, last);
}
}
void main()
{
int arr[10],i,k;
cout<<"Enter 10 values\n";
for(i=0;i<10;i++)
cin>>arr[i];
//call of Quick Sort function
quick_sort(arr,0,10);

cout<<" \n Sorted Values \n";


for(i=0;i<10;i++)
cout<<endl<<arr[i];
}
Output:

Self-Instructional
96 Material
Algorithm for Shell Sort Searching and Sorting
Algorithms
ALGORITHM _ SHELL SHORT
INPUT _ LIST OF N ELEMENTS
OUTPUT _ LIST OF N ELEMENTS IN ASSENDING ORDER NOTES
SHELL_ SORT ( LIST ,SIZE)
1. [INITIALIZE]
SET GAP := N/2
2. REPEAT THROUGH STEP 6 WHILE GAP =0
SET SWAP := 0
4. REPEAT THROUGH STEP 6 WHILE SWAP=1
5. REPEAT THROUGH STEP 6 FOR I=1,3 ,.....I<(N-GAP)
6. IF ( LIST [I] > LIST [I+ GAP]) THEN
SET LIST [I] ,-. LIST [I+ GAP]
SET SWAP := 1
[END OF FOR LOOP ]
[END OF INNER WHILE LOOP]
[END OF OUTER WHILE LOOP]
7. END
7. Write a program to implement shell sort.
//C++ program for shell sort
#include <iostream.h>

void shell_sort (int a[ ], int size )

{
int temp , gap ,i ,swap ;
gap = size /2 ;
do
{
do
{
swap =0;
for ( i=0 ; i < size-gap ; i ++)
{
if(a[i] > a[ i+ gap])
{
temp = a[i] ;
a[i] = a [i+ gap];
a[ i+ gap]= temp;
Self-Instructional
Material 97
Searching and Sorting
Algorithms
swap=1;
}}
}while ( swap ==1);
NOTES
gap= gap/2 ;
}while (gap >0) ;
}

void main()
{
int arr[10],i,k;
cout<<"Enter 10 values\n";
for(i=0;i<10;i++)
cin>>arr[i];
//call of shell sort function
shell_sort(arr,10);
cout<<" \n Sorted Values \n";
for(i=0;i<10;i++)
cout<<endl<<arr[i];
}
Output:

8. Write a program to implement merge sort.


//C++ program for merge sort
#include <iostream.h>
// function to merge the two half into a sorted data.
void merge_array(int a[], int low, int high, int mid)
{
// low to mid and mid+1 to high array are already
sorted
Self-Instructional
98 Material
int i, j, k; Searching and Sorting
Algorithms
int temp_arr[high-low+1];
i = low;
k = 0;
NOTES
j = mid + 1;
while (i <= mid && j <= high) // merging of two parts
into temp array
{
if (a[i] < a[j])
{
temp_arr[k] = a[i];
k++;
i++;
}
else
{
temp_arr[k] = a[j];
k++;
j++;
}
}
while (i <= mid) // insertion of remaining values
from i to mid into temp array.
{
temp_arr[k] = a[i];
k++;
i++;
}
while (j <= high) // insertion of remaining values
from j to high into temp array.
{
temp_arr[k] = a[j];
k++;
j++;
}
// assign sorted data stored in temp array to an array
for (i = low; i <= high; i++)
{
a[i] = temp_arr[i-low];
}
}
Self-Instructional
Material 99
Searching and Sorting // A function to split array into two parts.
Algorithms
void merge_sort(int a[], int low, int high)
{
int mid;
NOTES if (low < high)
{
mid=(low+high)/2;
// split array into two parts
merge_sort(a, low, mid);
merge_sort(a, mid+1, high);
// merge arraythem to get sorted values
merge_array(a, low, high, mid);
}
}
void main()
{
int arr[10],i,k;
cout<<"Enter 10 values\n";
for(i=0;i<10;i++)
cin>>arr[i];
//call of merge sort function
merge_sort(arr, 0, 9);
cout<<" \n Sorted Values \n";
for(i=0;i<10;i++)
cout<<endl<<arr[i];
}
Output:

Try yourself:
(1) Write a program to sort n numbers in descending order using bubble sort.
(2) Write a program to implement selection sort method using functions.
(3) Write a program to sort the n names in an alphabetical order.
Self-Instructional
100 Material
.emaN e1.sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.


.egaP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.

YTISREVINUALAGAPPA
APPAGALAUNIVERSITY
Master of Computer Applications


elcyC drihT eht ni )46.3:APGC( CA[Accredited
AN yb edarGwith
’+A’’A+’
htiwGrade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
]CGU-DRHM yb ytisrevinU I–yrogeand
taC Graded
sa dedarasG Category–I
dna University by MHRD-UGC]
300 036 – IDUKIARA
KARAIKUDI
K – 630 003
315 14 NOITACUDE ECNATSIDDIRECTORATE
FO ETAROTCEOF
RIDDISTANCE EDUCATION

LAB: DATA STRUCTURE USING C++


I - Semester

LAB: DATA STRUCTURE USING C++


Master of Computer Applications
315 14

itnem sYou
a egaare
p reinstructed
voc eht etatodpupdate
u ot dethe
tcurcover
tsni erpage
a uoYas mentioned below:
.emaN e1.sruIncrease
oC eht fothe
ezifont
s tnosize
f ehof
t esthe
aerCourse
cnI .1 Name.
aP revoC e2.ht nuse
i rethe
daefollowing
h a sa gniwasolaloheader
f eht esin
u the
.2 Cover Page.

ISREVINUALAGAPPA
APPAGALAUNIVERSITY
Master of Computer Applications
rihT eht ni )46.3:APGC( CA[Accredited
AN yb edarGwith
’+A’’A+’
htiwGrade
detidby
ercNAAC
cA[ (CGPA:3.64) in the Third Cycle
]CGU-DRHM yb ytisrevinU I–yrogeand
taC Graded
sa dedarasG Category–I
dna University by MHRD-UGC]
300 036 – IDUKIARA
KARAIKUDI
TACUDE ECNATSIDDIRECTORATE
K
FO ETAROTCEOF
– 630 003
RIDDISTANCE EDUCATION
LAB: DATA STRUCTURE USING C++
I - Semester

You might also like