Professional Documents
Culture Documents
Department of
Information Technology
Data Structure & Algorithms Lab (BTIT303-18)
Department of Information Technology
Index
i. Deletion at beginning
Practical No: 1
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
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;
Output of Code:
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
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++)
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;
Output of Code:
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:
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])
{
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:
Practical No: 5
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
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;
}
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;
}
}
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]<<" ";
}
}
}
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:
cout<<"Wrong Choice!!"<<endl;
break;
}
}
return 0;
}
Output of Code:
Practical No: 6
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].
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
{
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);
}
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]!='(')
{
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]);
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;
}
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:
Practical No: 7
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].
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;
}
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);
return 0;
}
Output of Code:
Practical No: 8
Recursion: The process in which a function calls itself directly or indirectly is called
recursion and the corresponding function is called as recursive function.
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);
}
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:
Practical No: 9
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
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>
void Insert()
int val;
if(rear==n-1)
cout<<"Queue Overflow"<<endl;
else
if (front==-1)
front=0;
cin>>val;
rear++;
queue[rear]=val;
void Delete()
if (front==-1||front>rear)
cout<<"Queue Underflow"<<endl;
return;
else
front++;
void Display()
if(front==-1)
cout<<"Queue is empty"<<endl;
else
cout<<queue[i]<<" ";
cout<<endl;
int main()
int ch;
cout<<"4) Exit"<<endl;
do
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:
Practical No: 10
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();
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;
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++;
}
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;
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;
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;
}
Output of Code:
1. Insertion at beginning: -
2. Insertion at end
Practical No: 11
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();
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;
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++;
}
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
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;
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)
{
Output of Code:
1. Deletion at beginning
2. Deletion at end
Practical No: 12
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;
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;
}
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:
Practical No: 13
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;
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;
}
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;
}
}
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:
flag = 0;
break;
}
}
return 0;
}
Output of Code:
Practical No: 14
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;
}
}
}
cout<<"Sorted array using Bubble Sort"<<endl;
for(i=0; i<n; i++)
cout<<A[i]<<" ";
cout<<endl;
return 0;
}
Output of Code:
Practical No: 15
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: -
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];
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:
Practical No: 16
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;
}
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:
Practical No: 17
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.
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];
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;
}
Output of Code:
Practical No: 18
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
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
}
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;
}
Output of Code:
Practical No: 19
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 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;
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())
{
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;
Output of Code:
Practical No: 20
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 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>
Output of Code:
Practical No: 21
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>
return true;
return false;
if(s<e+1)
return true;
int n=strlen(str);
return true;
int main()
char str[]="abba";
if(B(str))
else
cout<<endl;
return 0;
Output of Code:
Practical No: 22
Aim: Program to find the factorial of a given number using while loop and
ternary operator.
Program Code:
Output of Code:
Practical No: 23
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;
cout<<"OUTPUT : "<<A(m,n)<<endl;
return 0;
}
Output of Code:
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.
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;
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; }
Output of Code:
1. Call by Value
2. Call by Reference
Practical No: 25
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].
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;
}
}
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'))
{
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()))
{
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]);
}
}
}
}
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: