You are on page 1of 98

Chandigarh Engineering College, Landran (Mohali)

Department of
Information Technology
Data Structure & Algorithms Lab (BTIT303-18)
Department of Information Technology

Index

Sr. No. Practical Page No.

Write a program to insert a new element at end as well as


1. 3-4
at a given position in an array.

Write a program to delete an element from a given array


2. 5-7
whose value is given or whose position is given.

Write a program to find the location of a given element


3. 8-9
using Linear Search.

Write a program to find the location of a given element


4. 10-11
using Binary Search.

Write a program to implement push and pop operations on


5. 12-16
Laboratory File
a stack using linear array.

Write a program to convert an infix expression to a postfix


6. 17-22
expression using stacks.

Write a program to evaluate a postfix expression using


7. 23-26
Submitted By:
stacks. Submitted To:
8. Write a recursive function for Tower of Hanoi problem. 27-28
Yash Goyal Mr. Amitabh Sharma
Write a program to implement insertion and deletion
9. 29-32
1902941operations in a queue using linear array.
B.Tech Write a menu driven program to perform following
insertion operations in a single linked list:
IT (Z2) i. Insertion at beginning
10. ii. Insertion at end
33-40

iii. Insertion after a given node

iv. Traversing a linked list

11. Write a menu driven program to perform following 41-50


deletion operations in a single linked list:

Yash Goyal, 1902941Page 1


Department of Information Technology

i. Deletion at beginning

ii. Deletion at end

iii. Deletion after a given node

Write a program to implement push and pop operations on


12. 51-53
a stack using linked list.

Write a program to implement push and pop operations on


13. 54-58
a queue using linked list.

Program to sort an array of integers in ascending order


14. 59-60
using bubble sort.

Program to sort an array of integers in ascending order


15. 61-62
using selection sort.

Program to sort an array of integers in ascending order


16. 63-64
using insertion sort.

Program to sort an array of integers in ascending order


17. 65-67
using quick sort.

Program to traverse a Binary search tree in Pre-order, In-


18. 68-71
order and Post-order.

19. Program to traverse graphs using BFS. 72-75

20. Program to traverse graphs using DFS. 76-79

Program to check whether the entered string is palindrome


21. 80-81
or not using recursion.

Program to find the factorial of a given number using


22. 82-84
while loop and ternary operator.

23. Program to implement the Ackermann function. 85-86

Program to swap two numbers using call by value and call


24. 87-89
by reference.

Program to convert an infix expression to a prefix


25. 90-94
expression using stacks.

Yash Goyal, 1902941Page 2


Department of Information Technology

Yash Goyal, 1902941Page 3


Department of Information Technology

Practical No: 1

Aim: Write a program to insert a new element at end as well as at a given


position in an array.

Array: - An array is a collection of a fixed number of values of a single data type. The size
and type of arrays cannot be changed after its declaration. Arrays are of two types:

1. One-dimensional arrays
2. Multidimensional arrays

Syntax: - data_type array_name[array_size];

Program Code:
#include <iostream>
using namespace std;
int main()
{
int A[50], position, c, n, value, ch;
cout<<"Enter number of elements in the array"<<endl;
cin>>n;
cout<<"Enter "<<n<<" elements"<<endl;
for (c = 0; c < n; c++)
cin>>A[c];
cout<<"Press 1 to insert at end and 2 to insert at specified position"<<endl;
cin>>ch;
if (ch == 1)
{
position=n+1;
cout<<"Please enter the value"<<endl;
cin>>value;
for (c = n - 1; c >= position - 1; c--)
A[c+1] = A[c];
A[position-1] = value;

Yash Goyal, 1902941Page 4


Department of Information Technology

cout<<"Resultant array is"<<endl;


for (c = 0; c <= n; c++)
cout<<A[c]<<" ";
}
else
{
cout<<"Please enter the location where you want to insert an new element"<<endl;
cin>>position;
cout<<"Please enter the value"<<endl;
cin>>value;
for (c = n - 1; c >= position - 1; c--)
A[c+1] = A[c];
A[position-1] = value;
cout<<"Resultant array is"<<endl;
for (c = 0; c <= n; c++)
cout<<A[c]<<" ";
}
}

Output of Code:

Yash Goyal, 1902941Page 5


Department of Information Technology

Practical No: 2

Aim: Write a program to delete an element from a given array whose value
is given or whose position is given.

Array: - An array is a collection of a fixed number of values of a single data type. The size
and type of arrays cannot be changed after its declaration. Arrays are of two types:

1. One-dimensional arrays
2. Multidimensional arrays

Syntax: - data_type array_name[array_size];

Program Code:
#include <iostream>
using namespace std;
int main()
{
Cout<<”saket 212041 IT/B2”<<endl;
int A[100], search, position, n, d, ch, c;
cout<<"Enter number of elements in array"<<endl;
cin>>n;
cout<<"Enter "<<n<<" elements"<<endl;
for (d = 0; d < n; d++)

Yash Goyal, 1902941Page 6


Department of Information Technology

cin>>A[d];
cout<<"Enter 1 to delete an element whose value is given and any other number to
delete from specified position"<<endl;
cin>>ch;
if (ch==1)
{
cout<<"Enter a number to delete : "<<endl;
cin>>search;
for (d = 0; d < n; d++)
{
if (A[d] == search) /* If required element is found */
{
position=d+1;
if (position >= n+1)
cout<<"Deletion not possible"<<endl;
else
{
for (d = position - 1; d < n - 1; d++)
A[d] = A[d+1];
cout<<"Resultant array:"<<endl;
for (d = 0; d < n - 1; d++)
cout<<A[d]<<" ";
}
}
}
}
else
{
cout<<"Enter the location where you wish to delete element"<<endl;
cin>>position;

Yash Goyal, 1902941Page 7


Department of Information Technology

if (position >= n+1)


cout<<"Deletion not possible"<<endl;
else
{
for (c = position - 1; c < n - 1; c++)
A[c] = A[c+1];
cout<<"Resultant array:"<<endl;
for (c = 0; c < n - 1; c++)
cout<<A[c]<<" ";
} } }

Output of Code:

Yash Goyal, 1902941Page 8


Department of Information Technology

Practical No: 3

Aim: Write a program to find the location of a given element using Linear
Search.

Searching: - Searching is the process which is used to find whether a given number is
present in an array and if it is present then at what location it occurs.

Linear Search: - 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.

Program Code:
#include <iostream>
using namespace std;
int main()
{
int A[10], n, i, SE;
cout<<"Enter the size of array"<<endl;
cin>>n;
cout<<"Enter array elements"<<endl;
for(i=0;i<n;i++)
{
cin>>A[i];
}
cout<<"Enter the serch element"<<endl;
cin>>SE;
for(i=0;i<n;i++)
{
if(A[i]==SE)
{
cout<<"Element found at "<<i+1<<endl;
break;
}
Yash Goyal, 1902941Page 9
Department of Information Technology

}
if(i==5)
cout<<"Element is not found in the list"<<endl;
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 10


Department of Information Technology

Practical No: 4

Aim: Write a program to find the location of a given element using Binary
Search.

Searching: - Searching is the process which is used to find whether a given number is
present in an array and if it is present then at what location it occurs.

Binary Search: - It is a sorting algorithm which follows divide and conquer algorithm in
which, the list is divided into two parts and then each element is compared to  middle element
of the list. If we get a match then, position of middle element is returned otherwise, we search
into either of the halves depending upon the result produced through the match.

Program Code:
#include <iostream>
using namespace std;
int main()
{
int A[100], n, i, SE, first, last, mid;
cout<<"Enter the size of array"<<endl;
cin>>n;
cout<<"Enter array elements"<<endl;
for(i=0;i<n;i++)
{
cin>>A[i];
}
cout<<"Enter the serch element"<<endl;
cin>>SE;
first=0;
last=n-1;
mid=(first+last)/2;
while(first<=last)
{
if(SE==A[mid])

Yash Goyal, 1902941Page 11


Department of Information Technology

{
cout<<"Element found at "<<mid+1<<endl;
break;
}
else if(SE<A[mid])
last=mid-1;
else
first=mid+1;
mid=(first+last)/2;
}
if(first>last)
cout<<"Element is not found in the list"<<endl;
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 12


Department of Information Technology

Practical No: 5

Aim: Write a program to implement push and pop operations on a stack


using linear array.

Array: - An array is a collection of a fixed number of values of a single data type. The size
and type of arrays cannot be changed after its declaration. Arrays are of two types:

1. One-dimensional arrays
2. Multidimensional arrays

Syntax: - data_type array_name[array_size];

Stack: - A stack is a data structure in which items can be inserted only from one end and get
items back from the same end. There, the last item inserted into stack, is the first item to be
taken out from the stack. In short it is a data structure based on Last in First out [LIFO].
There are five operations of stack listed below: -

1. Top: - Open end of the stack is called Top, from this end item can be inserted.
2. Push: - To insert an item from Top of stack is called push operation. The push operation
changes the position of Top in stack.
3. POP: - To put-off, get or remove some item from top of the stack is the pop operation,
we can POP only from top of the stack.
4. IsEmpty: - Stack considered empty when there is no item on Top. IsEmpty operation
return true when no item in stack else false.
5. IsFull: - Stack considered full if no other element can be inserted on top of the stack.
This condition normally occurs when stack implemented through array.

Program Code:
#include<iostream>
using namespace std;
class Stack
{
int top;
int A[50];
public:
Stack()
{
top=-1;

Yash Goyal, 1902941Page 13


Department of Information Technology

}
void push();
void pop();
void view();
int isEmpty();
int isFull();
};
int Stack::isEmpty()
{
return (top==(-1)?1:0);
}
int Stack::isFull()
{
return ( top == 50 ? 1 : 0 );
}
void Stack::push()
{
if(isFull())
{
cout<<"STACK IS FULL { OVERFLOW }"<<endl;
}
else
{
int i;
cout<<"Enter an element = ";
cin>>i;
++top;
A[top]=i;
cout<<"Insertion successful"<<endl;

Yash Goyal, 1902941Page 14


Department of Information Technology

}
}
void Stack::pop()
{
if(isEmpty())
{
cout<<"STACK IS EMPTY [ UNDERFLOW ]"<<endl;
}
else
{
cout<<"Deleted item is : "<<A[top]<<endl;
top--;
}
}
void Stack::view()
{
if(isEmpty())
{
cout<<"STACK IS EMPTY [ UNDERFLOW ]"<<endl;
}
else
{
cout<<"STACK : ";
for(int i=top;i>=0;i--)
{
cout<<A[i]<<" ";
}
}
}

Yash Goyal, 1902941Page 15


Department of Information Technology

int main()
{
Stack a;
int ch;
ch=0;
while(ch!=4)
{
cout<<"\n1. Push"<<endl;
cout<<"2. Pop"<<endl;
cout<<"3. Display"<<endl;
cout<<"4. Quit"<<endl;
cout<<"Enter your Choice :: ";
cin>>ch;
switch(ch)
{
case 1:
a.push();
break;
case 2:
a.pop();
break;
case 3:
a.view();
break;
case 4:
ch=4;
cout<<endl<<"\t\tEnd of the program"<<endl;
break;
default:

Yash Goyal, 1902941Page 16


Department of Information Technology

cout<<"Wrong Choice!!"<<endl;
break;
}
}
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 17


Department of Information Technology

Practical No: 6

Aim: Write a program to convert an infix expression to a postfix expression


using stacks.

Stack: - A stack is a data structure in which items can be inserted only from one end and get
items back from the same end. There, the last item inserted into stack, is the first item to be
taken out from the stack. In short it is a data structure based on Last in First out [LIFO].

Infix Expression: - An infix expression is a single letter, or an operator, proceeded by


one infix string and followed by another infix string. In other words, the operator is in
between the two operands. The expression is in the form of a (op) b.

For example: (A+B) + (C-D)

Postfix Expression: - A postfix expression (also called Reverse Polish Notation) is a


single letter or an operator, preceded by two postfix string. Every postfix string longer than a
single variable contains first and last operands followed by an operator. In other words, the
operator is after the two operands. The expression is in the form of a b (op).

For example: AB+CD-+

Program Code:
#include<iostream>
#include<string>
#define MAX 40
using namespace std;
char stk[20];
int top=-1;
void push(char oper) //Push function here, inserts value in stack
{
if(top==MAX-1)
{
cout<<"Stack Full!!!!";
}
else
{

Yash Goyal, 1902941Page 18


Department of Information Technology

top++;
stk[top]=oper;
}
}
char pop() //Function to remove an item from stack. It decreases top by 1
{
char ch;
if(top==-1)
{
cout<<"Stack Empty!!!!";
}
else
{
ch=stk[top];
stk[top]='\0';
top--;
return(ch);
}
return 0;
}
int priority(char alpha)
{
if(alpha=='+'||alpha=='-')
{
return(1);
}
if(alpha=='*'||alpha=='/')
{
return(2);

Yash Goyal, 1902941Page 19


Department of Information Technology

}
if(alpha=='$'||alpha=='^')
{
return(3);
}
return 0;
}
string convert(string infix) //Main function for conversion
{
int i=0;
string postfix="";
while(infix[i]!='\0')
{
if(infix[i]>='a' && infix[i]<='z'||infix[i]>='A' && infix[i]<='Z')
{
postfix.insert(postfix.end(),infix[i]);
i++;
}
else if(infix[i]=='('||infix[i]=='{'||infix[i]=='[')
{
push(infix[i]);
i++;
}
else if(infix[i]==')'||infix[i]=='}'||infix[i]==']')
{
if(infix[i]==')')
{
while(stk[top]!='(')
{

Yash Goyal, 1902941Page 20


Department of Information Technology

postfix.insert(postfix.end(),pop());
}
pop();
i++;
}
if(infix[i]==']')
{
while(stk[top]!='[')
{
postfix.insert(postfix.end(),pop());
}
pop();
i++;
}
if(infix[i]=='}')
{
while(stk[top]!='{')
{
postfix.insert(postfix.end(),pop());
}
pop();
i++;
}
}
else
{
if(top==-1)
{
push(infix[i]);

Yash Goyal, 1902941Page 21


Department of Information Technology

i++;
}
else if(priority(infix[i])<=priority(stk[top]))
{
postfix.insert(postfix.end(),pop());
while(priority(stk[top])==priority(infix[i]))
{
postfix.insert(postfix.end(),pop());
if(top<0)
{
break;
}
}
push(infix[i]);
i++;
}
else if(priority(infix[i])>priority(stk[top]))
{
push(infix[i]);
i++;
}
}
}
while(top!=-1)
{
postfix.insert(postfix.end(),pop());
}
cout<<"The converted postfix string is : "<<postfix<<endl;
return postfix;

Yash Goyal, 1902941Page 22


Department of Information Technology

}
int main()
{
int cont;
string infix, postfix;
cout<<"Enter the infix expression : "; //Enter the expression
cin>>infix;
postfix=convert(infix);
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 23


Department of Information Technology

Practical No: 7

Aim: Write a program to evaluate a postfix expression using stacks.

Stack: - A stack is a data structure in which items can be inserted only from one end and get
items back from the same end. There, the last item inserted into stack, is the first item to be
taken out from the stack. In short it is a data structure based on Last in First out [LIFO].

Postfix Expression: - A postfix expression (also called Reverse Polish Notation) is a


single letter or an operator, preceded by two postfix string. Every postfix string longer than a
single variable contains first and last operands followed by an operator. In other words, the
operator is after the two operands. The expression is in the form of a b (op).

For example: AB+CD-+

Program Code:
#include <iostream>
#include <string.h>
using namespace std;
struct Stack
{
int top;
unsigned capacity;
int *array;
};
struct Stack* createStack(unsigned capacity) //Stack Operations
{
struct Stack* stack=(struct Stack*)malloc(sizeof(struct Stack));
if(!stack)return NULL;
stack->top=-1;
stack->capacity=capacity;
stack->array=(int*)malloc(stack->capacity*sizeof(int));
if(!stack->array)return NULL;
return stack;
}

Yash Goyal, 1902941Page 24


Department of Information Technology

int isEmpty(struct Stack* stack)


{
return stack->top==-1;
}
char peek(struct Stack* stack)
{
return stack->array[stack->top];
}
char pop(struct Stack* stack)
{
if(!isEmpty(stack))
return stack->array[stack->top--];
return '$';
}
void push(struct Stack* stack, char op)
{
stack->array[++stack->top]=op;
}
int evaluatePostfix(char* exp) //The function that returns value of a given expression
{
struct Stack* stack=createStack(strlen(exp)); //Create a stack
int i;
if(!stack)return -1; //See if stack was created successfully
for(i=0; exp[i]; ++i) //Scan all characters one by one
{
if(isdigit(exp[i]))
push(stack, exp[i]-'0');
else
{

Yash Goyal, 1902941Page 25


Department of Information Technology

int val1=pop(stack);
int val2=pop(stack);
switch (exp[i])
{
case '+':
push(stack, val2+val1);
break;
case '-':
push(stack, val2-val1);
break;
case '*':
push(stack, val2*val1);
break;
case '/':
push(stack, val2/val1);
break;
}
}
}
return pop(stack);
}
int main()
{
char exp1[]="231*+9-", exp2[]="53+62/*35*+";
cout<<"Expression 1 = 231*+9-"<<endl;
cout<<"Postfix Evaluation of Expression 1: "<<evaluatePostfix(exp1);
cout<<endl;
cout<<"Expression 2 = 53+62/*35*+"<<endl;
cout<<"Postfix Evaluation of Expression 2: "<<evaluatePostfix(exp2);

Yash Goyal, 1902941Page 26


Department of Information Technology

return 0;
}

Output of Code:

Yash Goyal, 1902941Page 27


Department of Information Technology

Practical No: 8

Aim: Write a recursive function for Tower of Hanoi problem.

Recursion: The process in which a function calls itself directly or indirectly is called
recursion and the corresponding function is called as recursive function.

Tower of Hanoi: - The Tower of Hanoi is also called the Tower of Brahma or Lucas'


Tower and sometimes pluralized as Towers. Tower of Hanoi is a mathematical
game or puzzle. It consists of three rods and a number of disks of different sizes, which can
slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size
on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is
to move the entire stack to another rod, obeying the following simple rules:

1. Only one disk can be moved at a time.


2. Each move consists of taking the upper disk from one of the stacks and placing it on top
of another stack or on an empty rod.
3. No larger disk may be placed on top of a smaller disk.

With 3 disks, the puzzle can be solved in 7 moves. 

Program Code:
#include<iostream>
using namespace std;
void TowerOfHanoi(int n, char x, char y, char z)
{
static int count = 0; //store number of counts
if(n == 1)
{
count++;
cout<<count<<". Move disk "<<n<<" from rod "<<x<<" to rod "<<y<<endl;
return;
}
TowerOfHanoi(n-1, x, z, y);
count++;
cout<<count<<". Move disk "<<n<<" from rod "<<x<<" to rod "<<y<<endl;
TowerOfHanoi(n-1, z, y, x);

Yash Goyal, 1902941Page 28


Department of Information Technology

}
int main()
{
int n; // Number of disks
cout<<"Enter the number of disks: ";
cin>>n;
TowerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
}

Output of Code:

Yash Goyal, 1902941Page 29


Department of Information Technology

Practical No: 9

Aim: Write a program to implement insertion and deletion operations in a


queue using linear array.

Array: - An array is a collection of a fixed number of values of a single data type. The size
and type of arrays cannot be changed after its declaration. Arrays are of two types:

1. One-dimensional arrays
2. Multidimensional arrays

Syntax: - data_type array_name[array_size];

Queue: - The queue is a basic data structure just like a stack. In contrast to stack that uses
the LIFO approach, queue uses the FIFO (first in, first out) approach. With this approach, the
first item that is added to the queue is the first item to be removed from the queue. Just like
Stack, the queue is also a linear data structure. The queue data structure includes the
following operations:

1. EnQueue: - Adds an item to the queue. Addition of an item to the queue is always
done at the rear of the queue.
2. DeQueue: - Removes an item from the queue. An item is removed or de-queued
always from the front of the queue.
3. isEmpty: - Checks if the queue is empty.
4. isFull: - Checks if the queue is full.
5. peek: - Gets an element at the front of the queue without removing it.

Yash Goyal, 1902941Page 30


Department of Information Technology

Program Code:
#include <iostream>

using namespace std;

int queue[100], n=100, front=-1, rear=-1;

void Insert()

int val;

if(rear==n-1)

cout<<"Queue Overflow"<<endl;

else

if (front==-1)

front=0;

cout<<"Insert the element in queue : ";

cin>>val;

rear++;

queue[rear]=val;

void Delete()

if (front==-1||front>rear)

cout<<"Queue Underflow"<<endl;

return;

else

Yash Goyal, 1902941Page 31


Department of Information Technology

cout<<"Element deleted from queue is : "<<queue[front]<<endl;

front++;

void Display()

if(front==-1)

cout<<"Queue is empty"<<endl;

else

cout<<"Queue elements are : ";

for (int i=front; i<=rear; i++)

cout<<queue[i]<<" ";

cout<<endl;

int main()

int ch;

cout<<"Queue Operations :- "<<endl;

cout<<"1) Insert element"<<endl;

cout<<"2) Delete element"<<endl;

cout<<"3) Display all the elements"<<endl;

cout<<"4) Exit"<<endl;

do

Yash Goyal, 1902941Page 32


Department of Information Technology

cout<<"Enter your choice : ";

cin>>ch;

switch (ch)

case 1:

Insert();

break;

case 2:

Delete();

break;

case 3:

Display();

break;

case 4:

cout<<"Exit"<<endl;

break;

default:

cout<<"Invalid choice"<<endl;

while(ch!=4);

return 0;

Output of Code:

Yash Goyal, 1902941Page 33


Department of Information Technology

Yash Goyal, 1902941Page 34


Department of Information Technology

Practical No: 10

Aim: Write a menu driven program to perform following insertion


operations in a single linked list:
i. Insertion at beginning
ii. Insertion at end
iii. Insertion after a given node
iv. Traversing a linked list

Linked List: - A Linked list is a data structure consisting of a group of nodes which
together represent a sequence. Each node is composed of a data and a link to the next node in
the sequence. The nodes are used to store data.

Program Code:
#include<iostream>
#include<stdlib.h>
using namespace std;
class Node
{
public:
int info;
Node* next;
};
class List:public Node
{
Node *first,*last;
public:
List()
{
first=NULL;
last=NULL;
}
void create();

Yash Goyal, 1902941Page 35


Department of Information Technology

void insert();
void display();
void search();
};
void List::create()
{
Node *temp;
temp=new Node;
int n;
cout<<"Enter an Element : ";
cin>>n;
temp->info=n;
temp->next=NULL;
if(first==NULL)
{
first=temp;
last=first;
}
else
{
last->next=temp;
last=temp;
}
}
void List::insert()
{
Node *prev,*cur;
prev=NULL;
cur=first;

Yash Goyal, 1902941Page 36


Department of Information Technology

int count=1,pos,ch,n;
Node *temp=new Node;
cout<<"Enter an Element : ";
cin>>n;
temp->info=n;
temp->next=NULL;
cout<<"INSERT AS"<<endl<<"1. FIRST NODE"<<endl;
cout<<"2. LAST NODE"<<endl;
cout<<"3. IN BETWEEN FIRST & LAST NODE"<<endl;
cout<<"Enter Your Choice : ";
cin>>ch;
switch(ch)
{
case 1:
temp->next=first;
first=temp;
break;
case 2:
last->next=temp;
last=temp;
break;
case 3:
cout<<"Enter the Position to Insert : ";
cin>>pos;
while(count!=pos)
{
prev=cur;
cur=cur->next;
count++;

Yash Goyal, 1902941Page 37


Department of Information Technology

}
if(count==pos)
{
prev->next=temp;
temp->next=cur;
}
else
cout<<"Not Able to Insert"<<endl;
break;
}
}
void List::display()
{
Node *temp=first;
if(temp==NULL)
{
cout<<"List is Empty ";
}
while(temp!=NULL)
{
cout<<temp->info;
cout<<" --> ";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
void List::search()
{
int value,pos=0;

Yash Goyal, 1902941Page 38


Department of Information Technology

bool flag=false;
if(first==NULL)
{
cout<<"List is Empty"<<endl;
return;
}
cout<<"Enter the Value to be Searched : ";
cin>>value;
Node *temp;
temp=first;
while(temp!=NULL)
{
pos++;
if(temp->info==value)
{
flag=true;
cout<<"Element "<<value<<" is found at "<<pos<<" position"<<endl;
return;
}
temp=temp->next;
}
if(!flag)
{
cout<<"Element "<<value<<" not found in the list"<<endl;
}
}
int main()
{
List l;

Yash Goyal, 1902941Page 39


Department of Information Technology

int ch;
while(1)
{
cout<<"**** MENU ****"<<endl;
cout<<"1. CREATE"<<endl<<"2. INSERT"<<endl;
cout<<"3. SEARCH"<<endl<<"4. DISPLAY"<<endl;
cout<<"5. EXIT"<<endl;
cout<<"Enter Your Choice : ";
cin>>ch;
switch(ch)
{
case 1:
l.create();
break;
case 2:
l.insert();
break;
case 3:
l.search();
break;
case 4:
l.display();
break;
case 5:
return 0;
}
}
return 0;
}

Yash Goyal, 1902941Page 40


Department of Information Technology

Output of Code:

1. Insertion at beginning: -

2. Insertion at end

Yash Goyal, 1902941Page 41


Department of Information Technology

3. Insertion after a given node

4. Traversing a linked list

Yash Goyal, 1902941Page 42


Department of Information Technology

Practical No: 11

Aim: Write a menu driven program to perform following deletion


operations in a single linked list:
i. Deletion at beginning
ii. Deletion at end
iii. Deletion after a given node

Linked List: - A Linked list is a data structure consisting of a group of nodes which
together represent a sequence. Each node is composed of a data and a link to the next node in
the sequence. The nodes are used to store data.

Program Code:
#include<iostream>
#include<stdlib.h>
using namespace std;
class Node
{
public:
int info;
Node* next;
};
class List:public Node
{
Node *first,*last;
public:
List()
{
first=NULL;
last=NULL;
}
void create();
void insert();

Yash Goyal, 1902941Page 43


Department of Information Technology

void del();
void display();
void search();
};
void List::create()
{
Node *temp;
temp=new Node;
int n;
cout<<"Enter an Element : ";
cin>>n;
temp->info=n;
temp->next=NULL;
if(first==NULL)
{
first=temp;
last=first;
}
else
{
last->next=temp;
last=temp;
}
}
void List::insert()
{
Node *prev,*cur;
prev=NULL;
cur=first;

Yash Goyal, 1902941Page 44


Department of Information Technology

int count=1,pos,ch,n;
Node *temp=new Node;
cout<<"Enter an Element : ";
cin>>n;
temp->info=n;
temp->next=NULL;
cout<<"INSERT AS"<<endl<<"1. FIRST NODE"<<endl;
cout<<"2. LAST NODE"<<endl;
cout<<"3. IN BETWEEN FIRST & LAST NODE"<<endl;
cout<<"Enter Your Choice : ";
cin>>ch;
switch(ch)
{
case 1:
temp->next=first;
first=temp;
break;
case 2:
last->next=temp;
last=temp;
break;
case 3:
cout<<"Enter the Position to Insert : ";
cin>>pos;
while(count!=pos)
{
prev=cur;
cur=cur->next;
count++;

Yash Goyal, 1902941Page 45


Department of Information Technology

}
if(count==pos)
{
prev->next=temp;
temp->next=cur;
}
else
cout<<"Not Able to Insert"<<endl;
break;
}
}
void List::del()
{
Node *prev=NULL,*cur=first;
int count=1,pos,ch;
cout<<"DELETE Operations"<<endl;
cout<<"1. FIRST NODE"<<endl<<"2. LAST NODE"<<endl;
cout<<"3. IN BETWEEN FIRST & LAST NODE"<<endl;
cout<<"Enter Your Choice : ";
cin>>ch;
switch(ch)
{
case 1:
if(first!=NULL)
{
cout<<"Deleted Element is "<<first->info<<endl;
first=first->next;
}
else

Yash Goyal, 1902941Page 46


Department of Information Technology

cout<<"Not Able to Delete"<<endl;


break;
case 2:
while(cur!=last)
{
prev=cur;
cur=cur->next;
}
if(cur==last)
{
cout<<"Deleted Element is "<<cur->info<<endl;
prev->next=NULL;
last=prev;
}
else
cout<<"Not Able to Delete"<<endl;
break;
case 3:
cout<<"Enter the Position of Deletion : ";
cin>>pos;
while(count!=pos)
{
prev=cur;
cur=cur->next;
count++;
}
if(count==pos)
{
cout<<"Deleted Element is "<<cur->info<<endl;

Yash Goyal, 1902941Page 47


Department of Information Technology

prev->next=cur->next;
}
else
cout<<"Not Able to Delete"<<endl;
break;
}
}
void List::display()
{
Node *temp=first;
if(temp==NULL)
{
cout<<"List is Empty ";
}
while(temp!=NULL)
{
cout<<temp->info;
cout<<" --> ";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
void List::search()
{
int value,pos=0;
bool flag=false;
if(first==NULL)
{
cout<<"List is Empty"<<endl;

Yash Goyal, 1902941Page 48


Department of Information Technology

return;
}
cout<<"Enter the Value to be Searched : ";
cin>>value;
Node *temp;
temp=first;
while(temp!=NULL)
{
pos++;
if(temp->info==value)
{
flag=true;
cout<<"Element "<<value<<" is found at "<<pos<<" position"<<endl;
return;
}
temp=temp->next;
}
if(!flag)
{
cout<<"Element "<<value<<" not found in the list"<<endl;
}
}
int main()
{
Cout<<”saket
List l;
int ch;
while(1)
{

Yash Goyal, 1902941Page 49


Department of Information Technology

cout<<"**** MENU ****"<<endl;


cout<<"1. CREATE"<<endl<<"2. INSERT"<<endl;
cout<<"3. DELETE"<<endl<<"4. SEARCH"<<endl;
cout<<"5. DISPLAY"<<endl<<"6. EXIT"<<endl;
cout<<"Enter Your Choice : ";
cin>>ch;
switch(ch)
{
case 1:
l.create();
break;
case 2:
l.insert();
break;
case 3:
l.del();
break;
case 4:
l.search();
break;
case 5:
l.display();
break;
case 6:
return 0;
}
}
return 0;
}

Yash Goyal, 1902941Page 50


Department of Information Technology

Output of Code:

1. Deletion at beginning

2. Deletion at end

Yash Goyal, 1902941Page 51


Department of Information Technology

3. Deletion after a given node

Yash Goyal, 1902941Page 52


Department of Information Technology

Yash Goyal, 1902941Page 53


Department of Information Technology

Practical No: 12

Aim: Write a program to implement push and pop operations on a stack


using linked list.
Linked List: - A Linked list is a data structure consisting of a group of nodes which
together represent a sequence. Each node is composed of a data and a link to the next node in
the sequence. The nodes are used to store data.

Stack: - A stack is a data structure in which items can be inserted only from one end and get
items back from the same end. There, the last item inserted into stack, is the first item to be
taken out from the stack. In short it is a data structure based on Last in First out [LIFO].
There are five operations of stack listed below: -

1. Top: - Open end of the stack is called Top, from this end item can be inserted.
2. Push: - To insert an item from Top of stack is called push operation. The push operation
changes the position of Top in stack.
3. POP: - To put-off, get or remove some item from top of the stack is the pop operation,
we can POP only from top of the stack.
4. IsEmpty: - Stack considered empty when there is no item on Top. IsEmpty operation
return true when no item in stack else false.
5. IsFull: - Stack considered full if no other element can be inserted on top of the stack.
This condition normally occurs when stack implemented through array.

Program Code:
#include<iostream>
using namespace std;
class StackNode // class to represent a stack node
{
public:
int data;
StackNode* next;
};
StackNode* newNode(int data)
{
StackNode* stackNode = new StackNode();
stackNode->data = data;

Yash Goyal, 1902941Page 54


Department of Information Technology

stackNode->next = NULL;
return stackNode;
}
int isEmpty(StackNode *root)
{
return !root;
}
void push(StackNode** root, int new_data)
{
StackNode* stackNode = newNode(new_data);
stackNode->next = *root;
*root = stackNode;
cout<<new_data<<endl;
}
int pop(StackNode** root)
{
if(isEmpty(*root))
return -1;
StackNode* temp = *root;
*root = (*root)->next;
int popped = temp->data;
int pop(StackNode**);
return popped;
}
int peek(StackNode* root)
{
if(isEmpty(root))
return -1;
return root->data;

Yash Goyal, 1902941Page 55


Department of Information Technology

}
int main()
{
StackNode* root = NULL;
cout<<"Stack Push:"<<endl;
push(&root, 100);
push(&root, 200);
push(&root, 300);
cout<<"Top element is "<<peek(root)<<endl<<endl;
cout<<"Stack Pop:"<<endl;
while(!isEmpty(root))
{
cout<<pop(&root)<<endl;
}
cout<<"Top element is "<<peek(root)<<endl;
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 56


Department of Information Technology

Practical No: 13

Aim: Write a program to implement push and pop operations on a queue


using linked list.

Linked List: - A Linked list is a data structure consisting of a group of nodes which
together represent a sequence. Each node is composed of a data and a link to the next node in
the sequence. The nodes are used to store data.

Queue: - The queue is a basic data structure just like a stack. In contrast to stack that uses
the LIFO approach, queue uses the FIFO (first in, first out) approach. With this approach, the
first item that is added to the queue is the first item to be removed from the queue. Just like
Stack, the queue is also a linear data structure. The queue data structure includes the
following operations:

1. EnQueue: - Adds an item to the queue. Addition of an item to the queue is always
done at the rear of the queue.
2. DeQueue: - Removes an item from the queue. An item is removed or de-queued
always from the front of the queue.
3. isEmpty: - Checks if the queue is empty.
4. isFull: - Checks if the queue is full.
5. peek: - Gets an element at the front of the queue without removing it.

Program Code:
#include <iostream>
using namespace std;
struct Node // Structure of Node
{
int data;
Node *link;
};
Node *front=NULL;
Node *rear=NULL;
bool isempty() //Function to check if queue is empty or not
{
if(front==NULL && rear==NULL)
return true;

Yash Goyal, 1902941Page 57


Department of Information Technology

else
return false;
}
void enqueue(int value) //Function to enter elements in queue
{
Node *ptr=new Node();
ptr->data=value;
ptr->link=NULL;
if(front==NULL) //If inserting the first element/node
{
front=ptr;
rear=ptr;
}
else
{
rear->link=ptr;
rear=ptr;
}
}
void dequeue() //Function to delete/remove element from queue
{
if(isempty())
cout<<"Queue is empty"<<endl;
else //Only one element/node in queue.
if( front==rear)
{
free(front);
front=rear=NULL;
}

Yash Goyal, 1902941Page 58


Department of Information Technology

else
{
Node *ptr=front;
front=front->link;
free(ptr);
}
}
void showfront() //Function to show the element at front
{
if(isempty())
cout<<"Queue is empty"<<endl;
else
cout<<"Element at front is : "<<front->data;
}
void displayQueue() //Function to display queue
{
if(isempty())
cout<<"Queue is empty"<<endl;
else
{
Node *ptr=front;
cout<<"Queue : ";
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
ptr=ptr->link;
}
cout<<endl;
}

Yash Goyal, 1902941Page 59


Department of Information Technology

}
int main() //Main Function
{
int choice, flag=1, value;
while(flag==1)
{
cout<<"****MENU****"<<endl;
cout<<"1. Enqueue"<<endl<<"2. Dequeue"<<endl;
cout<<"3. Showfront"<<endl<<"4. DisplayQueue"<<endl;
cout<<"5. Exit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch (choice)
{
case 1:
cout<<"Enter Value : ";
cin>>value;
enqueue(value);
break;
case 2:
dequeue();
break;
case 3:
showfront();
break;
case 4:
displayQueue();
break;
case 5:

Yash Goyal, 1902941Page 60


Department of Information Technology

flag = 0;
break;
}
}
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 61


Department of Information Technology

Practical No: 14

Aim: Program to sort an array of integers in ascending order using bubble


sort.

Bubble Sort: - Bubble Sort is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in wrong order.

Program Code:
#include<iostream>
using namespace std;
int main()
{
int A[50], i, j, n, temp;
cout<<"Enter the size of array : ";
cin>>n;
cout<<"Enter array elements : ";
for(i=0; i<n; i++)
{
cin>>A[i];
}
for(i=0; i<n-1; i++)
{
for(j=0; j<n-1; j++)
{
if(A[j]>A[j+1])
{
temp=A[j+1];
A[j+1]=A[j];
A[j]=temp;
}
}

Yash Goyal, 1902941Page 62


Department of Information Technology

}
cout<<"Sorted array using Bubble Sort"<<endl;
for(i=0; i<n; i++)
cout<<A[i]<<" ";
cout<<endl;
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 63


Department of Information Technology

Practical No: 15

Aim: Program to sort an array of integers in ascending order using


selection sort.

Selection Sort: - The selection sort algorithm sorts an array by repeatedly finding the
minimum element (considering ascending order) from unsorted part and putting it at the
beginning. The algorithm maintains two sub-arrays in a given array: -

1. The sub-array which is already sorted.


2. Remaining sub-array which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from
the unsorted sub-array is picked and moved to the sorted sub-array.

Program Code:
#include<iostream>
using namespace std;
int main()
{
int A[50], i, j, n, temp;
cout<<"Enter the size of array : ";
cin>>n;
cout<<"Enter array elements : ";
for(i=0; i<n; i++)
{
cin>>A[i];
}
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if(A[i]>A[j])
{
temp=A[i];

Yash Goyal, 1902941Page 64


Department of Information Technology

A[i]=A[j];
A[j]=temp;
}
}
}
cout<<"Sorted array using Selection Sort"<<endl;
for(i=0; i<n; i++)
cout<<A[i]<<" ";
cout<<endl;
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 65


Department of Information Technology

Practical No: 16

Aim: Program to sort an array of integers in ascending order using


insertion sort.

Insertion Sort: - Insertion sort is a sorting algorithm that builds a final sorted array
(sometimes called a list) one element at a time. It is used in complex computer programs such
as file search, data compression, and path finding. The insertion sort algorithm iterates
through an input array and removes one element per iteration, finds the place the element
belongs in the array, and then places it there. This process grows a sorted list from left to
right.

Program Code:
#include<iostream>
using namespace std;
int main()
{
int A[50], i, j, n, temp;
cout<<"Enter the size of array : ";
cin>>n;
cout<<"Enter array elements : ";
for(i=0; i<n; i++)
{
cin>>A[i];
}
for(i=1; i<n; i++)
{
temp=A[i];
j=i-1;
while(temp<A[j] && j>=0)
{
A[j+1]=A[j];
j=j-1;

Yash Goyal, 1902941Page 66


Department of Information Technology

}
A[j+1]=temp;
}
cout<<"Sorted array using Insertion Sort"<<endl;
for(i=0; i<n; i++)
cout<<A[i]<<" ";
cout<<endl;
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 67


Department of Information Technology

Practical No: 17

Aim: Program to sort an array of integers in ascending order using quick


sort.

Quick Sort: - Quick Sort is a Divide and Conquer algorithm. It picks an element as pivot
and partitions the given array around the picked pivot. There are many different versions of
quick sort that pick pivot in different ways.

1. Always pick first element as pivot.


2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.

Program Code:
#include<iostream>
using namespace std;
void quicksort(int A[50], int first, int last)
{
int pivot, i, j, temp;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(A[i]<A[pivot] && i<=last)
i++;
while(A[j]>A[pivot])
j--;
if(i<j)
{
temp=A[i];

Yash Goyal, 1902941Page 68


Department of Information Technology

A[i]=A[j];
A[j]=temp;
}
}
temp=A[pivot];
A[pivot]=A[j];
A[j]=temp;
quicksort(A, first, j-1);
quicksort(A, j+1, last);
}
}
int main()
{
int A[50], i, n;
cout<<"Enter the size of array : ";
cin>>n;
cout<<"Enter array elements : ";
for(i=0; i<n; i++)
{
cin>>A[i];
}
quicksort(A, 0, n-1);
cout<<"Sorted array using Quick Sort"<<endl;
for(i=0; i<n; i++)
cout<<A[i]<<" ";
cout<<endl;
return 0;
}

Yash Goyal, 1902941Page 69


Department of Information Technology

Output of Code:

Yash Goyal, 1902941Page 70


Department of Information Technology

Practical No: 18

Aim: Program to traverse a Binary search tree in Pre-order, In-order and


Post-order.

Binary Tree: - A tree is called binary tree if each node has zero child, one child or two
children. Empty tree is also a valid binary tree. We can visualize a binary tree as consisting of
a root and two disjoint binary trees, called the left and right sub-trees of the root.

Binary Search Tree: - A BST is a binary tree that is either empty or in which every node
contains a key (value) and satisfied the following conditions: -

1. All keys in the left sub-tree of the root are smaller than the key in the root node.
2. All keys in the right sub-tree of the root are greater than the key in the root node.
3. The left and right sub-trees of the root are again binary search tree.

Tree Traversal: - Traversal is a process to visit all the nodes of a tree and may their
values too. There are three ways which we can use to traverse a tree: -

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

1. In-order Traversal: - The in-order traversal of a nonempty binary tree is defined as


follows: -
● Traverse the left sub-tree in in-order
● Visit the root node
● Traverse the right sub-tree in in-order.

2. Pre-order Traversal: - The pre-order traversal of a nonempty binary tree is defined


as follows: -
● Visit the root node
● Traverse the left sub-tree in pre-order
● Traverse the right sub-tree in pre-order.

3. Post-order Traversal: - The post-order traversal of a nonempty binary tree is


defined as follows: -
● Traverse the left sub-tree in post-order
● Traverse the right sub-tree in post-order
● Visit the root node.

Yash Goyal, 1902941Page 71


Department of Information Technology

Program Code:
#include<iostream>
using namespace std;
struct Node
{
int data;
struct Node* left, *right;
Node(int data)
{
this->data=data;
left=right=NULL;
}
};
void printPostorder(struct Node* node)
{
if (node==NULL)
return;
printPostorder(node->left); //First recur on left subtree
printPostorder(node->right); //Then recur on right subtree
cout<<node->data<<" "; //Now deal with the node
}
void printInorder(struct Node* node) //Given a binary tree, print its nodes in inorder
{
if (node==NULL)
return;
printInorder(node->left); //First recur on left child
cout<<node->data<<" "; //Then print the data of node
printInorder(node->right); //Now recur on right child
}

Yash Goyal, 1902941Page 72


Department of Information Technology

void printPreorder(struct Node* node) //Given a binary tree, print its nodes in preorder
{
if (node==NULL)
return;
cout<<node->data<<" "; //First print data of node
printPreorder(node->left); //Then recur on left sutree
printPreorder(node->right); //Now recur on right subtree
}
int main() //Driver program to test above functions
{
struct Node *root=new Node(6);
root->left=new Node(4);
root->right=new Node(8);
root->left->left=new Node(2);
root->left->right=new Node(5);
root->right->left=new Node(7);
root->right->right=new Node(9);
root->left->left->left=new Node(1);
root->left->left->right=new Node(3);
cout<<"Preorder traversal of binary tree is "<<endl;
printPreorder(root);
cout<<endl<<"Inorder traversal of binary tree is "<<endl;
printInorder(root);
cout<<endl<<"Postorder traversal of binary tree is "<<endl;
printPostorder(root);
return 0;
}

Yash Goyal, 1902941Page 73


Department of Information Technology

Output of Code:

Yash Goyal, 1902941Page 74


Department of Information Technology

Practical No: 19

Aim: Program to traverse graphs using BFS.

Graph: - A graph is a pair (V, E), where V is a set of nodes, called vertices and E is a
collection of pairs of vertices, called edges. Vertices and edges are positions and store
elements. Removal of an edge from a circuit or connected graph creates a sub-graph that is a
tree. The graphs are classified into various categories such as directed, non-directed,
connected, non-connected, simple and multi-graph. Properties of a graph are as follows: -

● A vertex in a graph can be connected to any number of other vertices using edges.
● An edge can be bi-directed or directed.
● An edge can be weighted.

Graph Traversal: - Graph traversals are also known as graph search algorithms. Like
trees traversal algorithms, graph search algorithms can be thought of as starting at some
source vertex in a graph and “search” the graph by going through the edges and marking the
vertices. There are two such algorithms for traversing the graph: -

1. Breadth First Search (BFS)


2. Depth First Search (DFS)

1. Breadth First Search: - BFS algorithms work similar to level-order traversal of the
trees. Like level-order traversal BFS also uses queues. BFS works level by level. Initially,
BFS starts at a given vertex, which is at level 0. In the first stage, it visits all vertices at
level 1. In the second stage, it visits all vertices at second level. BFS continues this
process until all the levels of the graph are completed. Generally queue data structure is
used for sorting the vertices of a level.
2. Depth First Search: - DFS algorithms work similar to pre-order traversal of the
trees. Like pre-order traversal, internally this algorithm also uses stack. The process of
returning from the “dead end” is called Backtracking. We are trying to go away from
starting vertex into the graph as deep as possible, until we have to backtrack to the
preceding vertex. In DFS algorithm, we encounter the following types of edges: -
● Tree Edge: - Encounter new vertex.
● Back Edge: - From descendent to ancestor.
● Forward Edge: - From ancestor to descendent.
● Cross Edge: - Between a tree and a sub-tree.

Program Code:
#include<iostream>
#include<list>
using namespace std;

Yash Goyal, 1902941Page 75


Department of Information Technology

class Graph
{
int V; //No. of vertices
list<int> *adj; //Pointer to an array containing adjacency lists
public:
Graph(int V); //Constructor
void addEdge(int v, int w); //Function to add an edge to graph
void BFS(int s); //Print BFS traversal from a given source s
};
Graph::Graph(int V)
{
this->V=V;
adj=new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); //Add w to v’s list.
}
void Graph::BFS(int s)
{
bool *visited=new bool[V]; //Mark all the vertices as not visited
for(int i=0; i<V; i++)
visited[i]=false;
list<int>queue; //Create a queue for BFS
visited[s]=true; //Mark the current node as visited and enqueue it
queue.push_back(s);
list<int>::iterator i; //'i' will be used to get all adjacent vertices of a vertex
cout<<"\t";
while(!queue.empty())

Yash Goyal, 1902941Page 76


Department of Information Technology

{
s=queue.front(); //Dequeue a vertex from queue and print it
cout<<s<<" ";
queue.pop_front();
for(i=adj[s].begin(); i!=adj[s].end(); ++i)
{
if(!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
int main() // Driver program to test methods of graph class
{
Graph g(7); //Creation of a graph
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 0);
g.addEdge(1, 5);
g.addEdge(2, 5);
g.addEdge(3, 0);
g.addEdge(3, 4);
g.addEdge(4, 6);
g.addEdge(5, 1);
g.addEdge(6, 5);
cout<<"Following is Breadth First Traversal for given graph"<<endl;

Yash Goyal, 1902941Page 77


Department of Information Technology

cout<<"\t(starting from vertex 2)"<<endl<<endl;


g.BFS(2);
cout<<endl;
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 78


Department of Information Technology

Practical No: 20

Aim: Program to traverse graphs using DFS.

Graph: - A graph is a pair (V, E), where V is a set of nodes, called vertices and E is a
collection of pairs of vertices, called edges. Vertices and edges are positions and store
elements. Removal of an edge from a circuit or connected graph creates a sub-graph that is a
tree. The graphs are classified into various categories such as directed, non-directed,
connected, non-connected, simple and multi-graph. Properties of a graph are as follows: -

● A vertex in a graph can be connected to any number of other vertices using edges.
● An edge can be bi-directed or directed.
● An edge can be weighted.

Graph Traversal: - Graph traversals are also known as graph search algorithms. Like
trees traversal algorithms, graph search algorithms can be thought of as starting at some
source vertex in a graph and “search” the graph by going through the edges and marking the
vertices. There are two such algorithms for traversing the graph: -

1. Breadth First Search (BFS)


2. Depth First Search (DFS)

1. Breadth First Search: - BFS algorithms work similar to level-order traversal of the
trees. Like level-order traversal BFS also uses queues. BFS works level by level. Initially,
BFS starts at a given vertex, which is at level 0. In the first stage, it visits all vertices at
level 1. In the second stage, it visits all vertices at second level. BFS continues this
process until all the levels of the graph are completed. Generally queue data structure is
used for sorting the vertices of a level.
2. Depth First Search: - DFS algorithms work similar to pre-order traversal of the
trees. Like pre-order traversal, internally this algorithm also uses stack. The process of
returning from the “dead end” is called Backtracking. We are trying to go away from
starting vertex into the graph as deep as possible, until we have to backtrack to the
preceding vertex. In DFS algorithm, we encounter the following types of edges: -
● Tree Edge: - Encounter new vertex.
● Back Edge: - From descendent to ancestor.
● Forward Edge: - From ancestor to descendent.
● Cross Edge: - Between a tree and a sub-tree.

Program Code:
#include<iostream>
#include<list>
#include<memory>

Yash Goyal, 1902941Page 79


Department of Information Technology

using namespace std;


class Graph
{
int V; //No. of vertices
list<int>* adj; //Pointer to an array containing adjacency lists
void DFSUtil(int v, bool visited[]); //A function used by DFS
public:
Graph(int V); //Constructor
void addEdge(int v, int w); //Function to add an edge to graph
void DFS(); //Prints DFS traversal of the complete graph
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); //Add w to v’s list.
}
void Graph::DFSUtil(int v, bool visited[])
{
visited[v]=true; //Mark the current node as visited and print it
cout<<v<<" ";
list<int>::iterator i; //Recur for all the vertices adjacent to this vertex
for(i=adj[v].begin(); i!=adj[v].end(); ++i)
if (!visited[*i])
DFSUtil(*i, visited);
}

Yash Goyal, 1902941Page 80


Department of Information Technology

void Graph::DFS() //The function to do DFS traversal. It uses recursive DFSUtil()


{
bool *visited=new bool[V]; //Mark all the vertices as not visited
for(int i=0; i<V; i++)
visited[i]=false;
for(int i=0; i<V; i++)
if(visited[i]==false)
DFSUtil(i, visited);
}
int main()
{
Graph g(7); //Creation of a graph
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 0);
g.addEdge(1, 5);
g.addEdge(2, 5);
g.addEdge(3, 0);
g.addEdge(3, 4);
g.addEdge(4, 6);
g.addEdge(5, 1);
g.addEdge(6, 5);
cout<<"Following is Depth First Traversal"<<endl;
cout<<"\t";
g.DFS();
cout<<endl;
return 0;
}

Yash Goyal, 1902941Page 81


Department of Information Technology

Output of Code:

Yash Goyal, 1902941Page 82


Department of Information Technology

Practical No: 21

Aim: Program to check whether the entered string is palindrome or not


using recursion.

Palindrome String: - A palindrome string remains the same if its digits or characters are
reversed i.e. its value does not change. A palindrome string can also be called symmetric. For
example: The strings mam, malayalam, etc. are palindromes as they do not change even if
their characters are reversed. If there is only one character in string it returns true.

Program Code:
#include<iostream>

#include<string.h>

using namespace std;

bool A(char str[], int s, int e)

if(s==e) //If there is only one character

return true;

if(str[s]!=str[e]) //If first and last characters do not match

return false;

//If there are more than two characters,

//check if middle substring is also palindrome or not.

if(s<e+1)

return A(str, s+1, e-1);

return true;

bool B(char str[])

int n=strlen(str);

if(n==0) //An empty string is considered as palindrome

return true;

Yash Goyal, 1902941Page 83


Department of Information Technology

return A(str, 0, n-1);

int main()

char str[]="abba";

if(B(str))

cout<<"Entered string is a palindrome string";

else

cout<<"Entered string is not a palindrome string";

cout<<endl;

return 0;

Output of Code:

Yash Goyal, 1902941Page 84


Department of Information Technology

Practical No: 22

Aim: Program to find the factorial of a given number using while loop and
ternary operator.

Factorial: - For any positive number n, its factorial is given by:


fact = 1*2*3...*n
Factorial of negative number cannot be found and factorial of 0 is 1.

Program Code:

1. Using While Loop


#include<iostream>
using namespace std;
int factorial(int n)
{
if(n==0)
{
return 1;
}
int i=n, fact=1;
while(n/i!=n)
{
fact=fact*i;
i--;
}
return fact;
}
int main()
{
int num;
cout<<"Enter a number : ";
cin>>num;

Yash Goyal, 1902941Page 85


Department of Information Technology

cout<<"Factorial of "<<num<<" is "<<factorial(num)<<endl;


return 0;
}

2. Using Ternary Operator


#include<iostream>
using namespace std;
int factorial(int n)
{
return(n==1||n==0)?1:n*factorial(n-1);
}
int main()
{
int num;
cout<<"Enter a number : ";
cin>>num;
cout<<"Factorial of "<<num<<" is "<<factorial(num)<<endl;
return 0;
}

Output of Code:

1. Using While Loop

Yash Goyal, 1902941Page 86


Department of Information Technology

2. Using Ternary Operator

Yash Goyal, 1902941Page 87


Department of Information Technology

Practical No: 23

Aim: Program to implement the Ackermann function.

Ackermann Function: - The Ackermann function is the simplest example of a well-


defined total function which is computable but not primitive recursive, providing a
counterexample to the belief in the early 1900's that every computable function was also
primitive recursive. It grows faster than an exponential function, or even a multiple
exponential function.

Program Code:
#include<iostream>
using namespace std;
int A(int m, int n)
{
if(m==0)
{
return n+1;
}
else if(n==0)
{
return A(m-1,1);
}
else
{
return A(m-1,A(m,n-1));
}
}
int main()
{
int m,n;
cout<<"Enter two numbers : ";
cin>>m>>n;

Yash Goyal, 1902941Page 88


Department of Information Technology

cout<<"OUTPUT : "<<A(m,n)<<endl;
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 89


Department of Information Technology

Practical No: 24

Aim: Program to swap two numbers using call by value and call by
reference.

Call by value: - In call by value, original value cannot be changed or modified. In call by
value, passed value to the function is locally stored by the function parameter in stack
memory location. If the value of the argument is changed inside the function, the change is
visible inside the function and not visible in the actual argument in the main function.

Call by Reference: - In call by reference, original value is changed or modified because


we pass reference (address). Here, address of the value is passed in the function, so actual and
a formal argument shares the same address space. Hence, any value changed inside the
function, is reflected inside as well as outside the function.

Program Code:

1. Call by Value
#include<iostream>
using namespace std;
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
int main()
{
int a, b;
cout<<"Before Swapping"<<endl;
cout<<"Value of a : ";
cin>>a;
cout<<"Value of b : ";
cin>>b;

Yash Goyal, 1902941Page 90


Department of Information Technology

swap(a,b); //Passing value to function


cout<<"After Swapping"<<endl;
cout<<"Value of a : "<<a<<endl;
cout<<"Value of b : "<<b<<endl;
return 0;
}

2. Call by Reference
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
int main()
{
int a, b;
cout<<"Before Swapping"<<endl;
cout<<"Value of a : ";
cin>>a;
cout<<"Value of b : ";
cin>>b;
swap(a,b); //Passing value to function
cout<<"After Swapping"<<endl;
cout<<"Value of a : "<<a<<endl;
cout<<"Value of b : "<<b<<endl;
return 0; }

Yash Goyal, 1902941Page 91


Department of Information Technology

Output of Code:

1. Call by Value

2. Call by Reference

Yash Goyal, 1902941Page 92


Department of Information Technology

Practical No: 25

Aim: Program to convert an infix expression to a prefix expression using


stacks.

Stack: - A stack is a data structure in which items can be inserted only from one end and get
items back from the same end. There, the last item inserted into stack, is the first item to be
taken out from the stack. In short it is a data structure based on Last in First out [LIFO].

Infix Expression: - An infix expression is a single letter, or an operator, proceeded by


one infix string and followed by another infix string. In other words, the operator is in
between the two operands. The expression is in the form of a (op) b.

For example: (A+B) + (C-D)

Prefix Expression: - A prefix expression is a single letter, or an operator, followed by


two prefix strings. Every prefix string longer than a single variable contains an operator, first
operand and second operand. The expression is in the form of (op) a b.

For example: ++AB-CD

Program Code:
#include<iostream>
#include<stack>
#include<algorithm>
using namespace std;
bool isOperator(char c)
{
if(c=='+'||c=='-'||c=='*'||c=='/'||c=='^')
{
return true;
}
else
{
return false;
}
}

Yash Goyal, 1902941Page 93


Department of Information Technology

int precedence(char c)
{
if(c=='^')
return 3;
else if(c=='*'||c=='/')
return 2;
else if(c=='+'||c=='-')
return 1;
else
return -1;
}
string InfixToPrefix(stack<char>s, string infix)
{
string prefix;
reverse(infix.begin(), infix.end());
for(int i=0; i<infix.length(); i++)
{
if(infix[i]=='(')
{
infix[i]=')';
}
else if(infix[i]==')')
{
infix[i]='(';
}
}
for(int i=0; i<infix.length(); i++)
{
if((infix[i]>='a' && infix[i]<='z')||(infix[i]>='A' && infix[i]<='Z'))

Yash Goyal, 1902941Page 94


Department of Information Technology

{
prefix+=infix[i];
}
else if(infix[i]=='(')
{
s.push(infix[i]);
}
else if(infix[i]==')')
{
while((s.top()!='(') && (!s.empty()))
{
prefix+=s.top();
s.pop();
}
if(s.top()=='(')
{
s.pop();
}
}
else if(isOperator(infix[i]))
{
if(s.empty())
{
s.push(infix[i]);
}
else
{
if(precedence(infix[i])>precedence(s.top()))
{

Yash Goyal, 1902941Page 95


Department of Information Technology

s.push(infix[i]);
}
else if((precedence(infix[i])==precedence(s.top())) &&
(infix[i]=='^'))
{
while((precedence(infix[i])==precedence(s.top())) &&
(infix[i]=='^'))
{
prefix+=s.top();
s.pop();
}
s.push(infix[i]);
}
else if(precedence(infix[i])==precedence(s.top()))
{
s.push(infix[i]);
}
else
{
while((!s.empty()) &&
(precedence(infix[i])<precedence(s.top())))
{
prefix+=s.top();
s.pop();
}
s.push(infix[i]);
}
}
}

Yash Goyal, 1902941Page 96


Department of Information Technology

}
while(!s.empty())
{
prefix+=s.top();
s.pop();
}
reverse(prefix.begin(), prefix.end());
return prefix;
}
int main()
{
string infix, prefix;
cout<<"Enter an Expression : ";
cin>>infix;
stack<char>stack;
cout<<"INFIX EXPRESSION : "<<infix<<endl;
prefix=InfixToPrefix(stack, infix);
cout<<"PREFIX EXPRESSION : " <<prefix<<endl;
return 0;
}

Output of Code:

Yash Goyal, 1902941Page 97

You might also like