Data Structures Practical - WordFile
Data Structures Practical - WordFile
Sc
Data Structure is defined as the way in which data is organized in the memory location. There are 2 types of
data structures:
EXPERIMENT 1
OBJECTIVE:
Design, Develop and Implement a menu driven Program in C for the following Array operations
a. Creating an Array of N Integer Elements
b. Display of Array Elements with Suitable Headings
c. Inserting an Element at a given valid Position (POS)
d. Deleting an Element at a given valid Position(POS)
e. Exit.
Support the program with functions for each of the above operations.
THEORY:
An array is collection of items stored at contiguous memory locations. The idea is to store multiple items of
same type together. This makes it easier to calculate the position of each element by simply adding an offset to a
base value, i.e., the memory location of the first element of the array (generally denoted by the name of the
array).
Visualization of an array
ALGORITHM:
Step 1: Start.
Step 2: Read N value.
Step 3: Read Array of N integer
elements Step 4: Print array of N integer
elements.
Step 5: Insert an element at given valid position in an array.
Step 6: Delete an element at given valid position from an
array. Step 7: Stop.
PROGRAM IN C++
#include<iostream>
using namespace std;
/* Global variables declaration */
int a[10], n, elem, i, pos; //predefining array size to be maximum of size 10
/*Function Prototype and
Definitions*/ void create() //creating
an array
{
cout<<"\nEnter the size of the array elements<=9: ";
cin>>n;
cout<<"\nEnter the elements for the array:\n";
for(i=0; i<n; i++)
cin>>a[i]; //end of create()
} //end of create()
void display() //displaying an array elements
{
int i;
cout<<"\nThe array elements are:\n";
for(i=0; i<n; i++)
{
cout<<a[i]<<"\n";
}
} //end of display()
void insert() //inserting an element in to an array
{
cout<<"\nEnter the position for the new element:
"; cin>>pos;
cout<<"\nEnter the element to be inserted: ";
cin>>elem;
pos=pos-1;
for(i=n-1; i>=pos; i--)
{
a[i+1] = a[i];
}
a[pos] = elem;
n = n+1;
} //end of insert()
void del() //deleting an array element
{
cout<<"\nEnter the position of the element to be deleted: ";
cin>>pos;
pos=pos-1;
elem = a[pos];
for(i=pos; i<n-1; i++)
{
a[i] = a[i+1];
}
n = n-1;
cout<<"\nThe deleted element is\n"<<elem;
}//end of delete()
int main()
{
int ch;
create();
display();
cout<<"\n\n--------Menu----------\n";
cout<<"1.Insert\n 2.Delete\n 3.Exit\n";
cout<<" ";
cout<<"\nEnter your choice: ";
cin>>ch;
switch(ch)
{
case 1: insert();
display()
; break;
case 2: del();
display()
; break;
case 3: return 0;
break;
default: cout<<"\nInvalid choice:\n";
break;
}
}// end of main
PROGRAM OUTPUT:
QUESTIONS:
1. Write a program in C/C++ to create an array of SIZE=10 by inserting the following elements
3, 20, 10, 12, 61, 23
2. Write a program in C/C++ to create the following array and insert an element 20 at the position
3 in the following array
2, 3, 12, 50, 18, 1
3. Write a program in C/C++ to create the following array and delete the element at the position 5
in the following array
6, 22, 11, 44, 20, 2
EXPERIMENT 2
OBJECTIVE:
Design, Develop and Implement the following menu driven Programs in C/C++ using Array operations
(a) Write a program for Bubble sort algorithm
(b) Write a program for Merge Sort algorithm
(c) Write a program for Radix Sort algorithm
(d) Write a program for Insertion Sort algorithm
(e) Write a program for Selection Sort algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they
are in wrong order.
ALGORITHM:
Step 1: Start.
Step 2: Starting with the first element(index = 0), compare the current element with the next element of the
array.
Step 3: If the current element is greater than the next element of the array, swap them.
Step 4: If the current element is less than the next element, move to the next element.
PROGRAM IN C++
#include<iostream>
using namespace std;
int main()
{
int n, i, arr[50], j, temp;
cout<<"Enter total number of elements
:"; cin>>n;
cout<<"Enter "<<n<<" numbers :";
for(i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Sorting array using bubble sort technique...\n";
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
cout<<"Elements sorted successfully!\n";
cout<<"Sorted list in ascending order:\n";
for(i=0; i<n; i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
PROGRAM OUTPUT:
Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself for the two
halves, and then merges the two sorted halves.
#include <iostream>
using namespace std;
array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
indexOfMergedArray++;
}
}
// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
auto arr_size = sizeof(arr) / sizeof(arr[0]);
PROGRAM OUTPUT:
Given array is
12 11 13 5 6
7
Sorted array is
5 6 7 11 12 13
The idea of Radix Sort is to do digit by digit sort starting from least significant digit to most significant digit.
Radix sort uses counting sort as a subroutine to sort.
PROGRAM IN C++ to Radix sort a given array: 170, 45, 75, 90, 802, 24, 2, 66
#include <iostream>
using namespace std;
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver Code
int main()
{
int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function Call
radixsort(arr, n);
cout << "\nSorted array is: \n";
print(arr, n);
return 0;
}
PROGRAM OUTPUT:
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands.
The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and
placed at the correct position in the sorted part.
Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the elements before. Move the greater
elements one position up to make space for the swapped element.
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
cout << "\nSorted array is: \n";
printArray(arr, n);
return 0;
}
PROGRAM OUTPUT:
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 subarrays in
a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted
subarray is picked and moved to the sorted subarray.
arr[] = 64 25 12 22 11
11 25 12 22 64
PROGRAM IN C++ to Selection sort a given array: 64, 25, 12, 22, 11
#include <iostream>
using namespace std;
min_idx = j;
PROGRAM OUTPUT:
Sorted array:
11 12 22 25 64
QUESTIONS:
1. Write programs in C/C++ to perform Bubble/ Merge / Radix / Insertion / Selection
sort algorithm for the following array
12, 3, 40, 1, 60, 2, 99, 101
EXPERIMENT 3
OBJECTIVE:
Design, Develop and Implement the following menu driven Programs in C/C++ for implementing
(a) Write a program for Heap Sort algorithm
(b) Write a program for Quick Sort algorithm
(c) Write a program for linear search algorithm
(d) Write a program for displaying a sparse matrix
(e) Fibonacci numbers
(f) Factorial of a number
THEORY
a) HEAP SORT:
#include <iostream>
using namespace std;
// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
PROGRAM OUTPUT:
Sorted array is
5 6 7 11 12 13
b) QUICK SORT:
#include <stdio.h>
void quicksort(int a[40],int first,int last)
{
int i,j,pivot,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,0,j-1);
quicksort(a,j+1,last);
}
}
}
int main()
{
int a[40],n,i;
printf("How many elements are to be sorted?");
scanf("%d",&n);
printf("\nEnter array elements:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1); printf("\
nArray after sorting:\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
PROGRAM OUTPUT:
46
71
3
Given an array arr[] of n elements, Linear search helps to search a given element x in arr[].
ALGORITHM:
Step 1: Start.
Step 2: Start from the left most element of arr[]
Step 3: One by one compare x with each element of arr[]
Step 4: If x matches with an element, return the index.
Step 5: If x doesn’t match with any of elements, return -1
Step 6: Stop
PROGRAM IN C++
#include<iostream>
using namespace std;
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i< n; i++)
if (arr[i] == x)
return i;
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 4;
int n = sizeof(arr) / sizeof(arr[0]);
int result = search(arr, n, x);
(result == -1)? cout<<"Element is not present in array": cout<<"Element is present at index:\n" <<result;
return 0;
}
PROGRAM OUTPUT:
A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values.
If most of the elements of the matrix have 0 value, then it is called a sparse matrix.
ALGORITHM:
Step 1: Start
Step 2: Calculate Index of row, where non-zero element is located
Step 3: Calculate Index of column, where non-zero element is
located
Step 4: CalculateValue of the non zero element located at index – (row,column)
Step 5: Print in the form of matrix
Step 6: Stop
PROGRAM IN C++
#include <iostream>
using namespace std;
int main()
{
// Assume 4x5 sparse matrix
int sparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};
int size = 0;
for (int i = 0; i< 4; i++)
for (int j = 0; j < 5; j+
+)
if (sparseMatrix[i][j] != 0)
size++;
// number of columns in compactMatrix (size) must be
// equal to number of non - zero elements in
// sparseMatrix
int compactMatrix[3][size];
// Making of new matrix
int k = 0;
for (int i = 0; i< 4; i++)
for (int j = 0; j < 5; j+
+)
if (sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j];
k++;
}
for (int i=0; i<3; i++)
{
for (int j=0; j<size; j++)
cout<<compactMatrix[i][j]<<endl;
}
return 0;
PROGRAM OUTPUT:
0
0
1
1
3
3
2
4
2
3
1
2
3
4
5
7
2
6
In mathematics, the Fibonacci numbers form a sequence, the Fibonacci sequence, in which each number is the
sum of the two preceding ones. The sequence commonly starts from 0 and 1, although some authors omit the
initial terms and start the sequence from 1 and 1 or from 1 and 2. Starting from 0 and 1, the next few values in
the sequence are:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,…
PROGRAM IN C++
#include <iostream>
using namespace std;
int main()
{
int n1=0,n2=1,n3,i,number;
cout<<"Enter the number of elements: ";
cin>>number;
cout<<n1<<" "<<n2<<" "; //printing 0 and 1
for(i=2;i<number;i++) //loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
cout<<n3<<" ";
n1=n2;
n2=n3;
}
return 0;
PROGRAM OUTPUT:
Enter the number of elements: 10
0 1 1 2 3 5 8 13 21 34
Factorial of a whole number 'n' is defined as the product of that number with every whole number till 1. For
example, the factorial of 5 is 5×4×3×2×1, which is equal to 120. It is represented using the symbol '!' So,
120 is the value of 5!
PROGRAM IN C++
#include <iostream>
using namespace std;
int main()
{
int i,fact=1,number;
cout<<"Enter any Number: ";
cin>>number;
for(i=1;i<=number;i++){
fact=fact*i;
}
cout<<"Factorial of " <<number<<" is
"<<fact<<endl; return 0;
}
PROGRAM OUTPUT:
Enter any Number: 5
Factorial of 5 is 120
QUESTIONS:
1. Write programs in C/C++ to perform Heap / Quick Sort algorithm for the following array
12, 3, 40, 1, 60, 2, 99, 101
2. Write a program in C/C++ to search the element 5 in the following array using linear
search algorithm
20, 33, 12, 5, 8, 10
3. Write a program in C/C++ to for displaying a sparse matrix for the following matrix
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
02600
4. Find out the value of 7! using a C/C++ program.
EXPERIMENT 4
OBJECTIVE:
Design, Develop and Implement a menu driven Program in C for the following operations on STACK of
Integers (Array Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
d. Demonstrate Overflow and Underflow situations on Stack
e. Display the status of Stack
f. Exit
Support the program with appropriate functions for each of the above operations
THEORY:
A stack is an abstract data type (ADT), commonly used in most programming languages. It is named stack as it
behaves like a real-world stack. A real-world stack allows operations at one end only. For example, we can
place or remove a card or plate from top of the stack only. Likewise, Stack ADT allows all data operations at
one end only. At any given time, we can only access the top element of a stack. This feature makes it LIFO data
structure. LIFO stands for Last-in-first-out. Here, the element which is placed (inserted or added) last is
accessed first. In stack terminology, insertion operation is called PUSH operation and removal operation is
called POP operation.
A stack can be implemented by means of Array, Structure, Pointer and Linked-List. Stack can either be a fixed
size one or it may have a sense of dynamic resizing. Here, we are going to implement stack using arrays which
makes it a fixed size stack implementation.
Basic Operations:
push() - pushing (storing) an element on the stack.
pop() - removing (accessing) an element from the stack.
To use a stack efficiently we need to check status of stack as well. For the same purpose,
the following functionality is added to stacks;
peek() − get the top data element of the stack, without removing it.
isFull() − check if stack is full.
isEmpty() − check if stack is empty.
ALGORITHM:
Step 1: Start.
Step 2: Initialize stack size MAX and top of stack -1.
Step 3: Push integer element on to stack and display the contents of the stack.
if stack is full give a message as ‘Stack is Overflow’.
Step 3: Pop element from stack along with display the stack contents.
if stack is empty give a message as ‘Stack is Underflow’.
PROGRAM IN C++
#include<iostream>
using namespace std;
#define MAX 10
int stack[MAX], item;
int ch, top=-1, count=0, status=0;
/*PUSH FUNCTION*/
void push(int stack[], int item)
{
if (top==(MAX-1)) cout<<"\n\
nStack is Overflow"; else
{
stack[++top]=item;
status++;
}
}
int pop(int stack[])
{
int ret;
if(top==-1)
cout<<"\n\nStack is Underflow";
else
{
ret = stack[top--];
status--;
cout<<"\nPopped element is \n"<< ret;
}
return ret;
}
/* FUNCTION TO CHECK STACK IS
PALINDROME OR NOT */
void palindrome(int stack[])
{
int i, temp;
temp=status;
for(i=0; i<temp; i+
+)
{
if(stack[i]==pop(stack))
count++;
}
if(temp==count)
cout<<"\nStack contents are Palindrome";
else
cout<<"\nStack contents are not palindrome";
}
/*FUNCTION TO DISPLAY STACK*/
void display(int stack[])
{
int i;
cout<<"\nThe stack contents are:";
if(top==-1)
cout<<"\nStack is Empty";
else
{
for(i=top; i>=0; i--)
cout<<"\n"<< stack[i];
}
}
/*MAIN PROGRAM*/
int main()
{
do
{
cout<<"\n\n----MAIN MENU ---\n";
cout<<"\n 1. PUSH (Insert) in the Stack";
cout<<"\n 2. POP (Delete) from the Stack";
cout<<"\n 3. PALINDROME check using Stack";
cout<<"\n 4. Exit (End the Execution)"; cout<<"\
n Enter Your Choice: ";
cin>>ch;
switch(ch)
{
case 1: cout<<"\nEnter a element to be pushed:";
cin>>item;
push(stack, item);
display(stack);
break;
case 2: item=pop(stack);
display(stack);
break;
case 3: palindrome(stack);
break;
case 4: return 0;
break;
default:
cout<<"\nEND OF EXECUTION";
}//end switch
}while (ch!= 4);
}
PROGRAM OUTPUT:
----MAIN MENU----
----MAIN MENU----
----MAIN MENU----
----MAIN MENU----
Popped element is
7
The stack contents are:
5
4
----MAIN MENU----
----MAIN MENU----
Popped element is
4
Popped element is
5
Popped element is
4
Stack contents are Palindrome
----MAIN MENU----
QUESTIONS:
1. Write a program in C/C++ to insert the elements 12, 40, 19 into the following stack by Push
function
3, 22, 34 (consider array size= 10)
2. Write a program in C/C++ to delete 3 elements from the following stack by Pop
function 30, 20, 40, 60, 90, 110
EXPERIMENT 5
OBJECTIVE:
Design, Develop and Implement a Program in C for converting an Infix Expression to Postfix Expression.
Program should support for both parenthesized and free parenthesized expressions with the operators: +, -, *,
/,
% (Remainder), ^ (Power) and alphanumeric operands.
THEORY:
ALGORITHM:
Step 1: Start.
Step 2: Read an infix expression with parenthesis and without parenthesis.
Step 3: convert the infix expression to postfix expression.
Step 4: Stop
PROGRAM IN C
#include<stdio.h>
#include<stdlib.h> #include<ctype.h> #include<string.h>
char stack[SIZE];
int top = -1;
void push(char x)
{
if(top >= SIZE-1)
{
printf("\nStack Overflow.");
}
else
{
top = top+1;
stack[top] = x;
}
}
char pop()
{
char item ;
if(top==-1)
{
printf("stack underflow: invalid infix
expression"); getchar();
exit(1);
}
else
{
item = stack[top];
top = top-1;
return(item);
}
}
int priority(char x)
{ if(x=='
(') return
0;
if(x=='+'||x=='-')
return 1;
if(x=='*'||x=='/')
return 2;
if(x=='^')
return 3;
}
int main()
{
char exp[20];
char *e, x;
printf("Enter the expression:");
scanf("%s",exp);
e=exp;
while(*e!='\0')
{
if(isalnum(*e))
printf("%c",*e);
else if(*e=='(')
push(*e);
else if(*e==')')
{
while((x=pop())!='(')
printf("%c",x);
}
else
{
while(priority(stack[top])>=priority(*e))
printf("%c",pop());
push(*e);
}
e++;
}
while(top!=-1)
{
printf("%c",pop());
}
}
PROGRAM OUTPUT:
Enter the expression:(a+(b-
c)*d) abc-d*+
Manual check:
Symbol Stack Postfix
( (
a ( a
+ (+ a
( (+( a
b (+( ab
- (+(- ab
c (+(- abc
) (+ abc-
* (+* abc-
d (+* abc-d
) abc-d*+
QUESTIONS:
1. Write a program in C/C++ to convert the following Infix expression into Postfix
expression a + b * c - ( d / e + f ^ g ^ h )
2. Write a program in C/C++ to convert the following Infix expression into Postfix
expression ( 6 + 2 ) * 5 – 8 / 4
3. Write a program in C/C++ to convert the following Infix expression into Postfix
expression a + b * ( c ^ d – e ) ^ ( f + g * h ) – i
EXPERIMENT 6
OBJECTIVE:
Design, Develop and Implement a Program in C for the following Stack Applications
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
b. Solving Tower of Hanoi problem with n disks
Rules Of Evaluations
While reading the expression from left to right, push the element in the stack if it is an operand.
Pop the two operands from the stack, if the element is an operator and then evaluate it.
Push back the result of the evaluation. Repeat it till the end of the expression.
ALGORITHM:
Step 1: Start.
Step 2: Read the postfix/suffix expression.
Step 3: Evaluate the postfix expression based on the precedence of the operator.
Step 4: Stop.
PROGRAM IN C++:
PROGRAM 4A:
#include<iostream>
using namespace std;
#include<math>
#include<string>
double compute(char symbol, double op1, double op2)
{
switch(symbol)
{
case '+': return op1 + op2;
case' -': return op1 - op2;
case '*': return op1 * op2;
case '/': return op1 / op2;
case '$':
case '^': return
pow(op1,op2); default: return
0;
}
}
void main()
{
double s[20], res, op1, op2;
int top, i;
char postfix[20], symbol;
printf("\nEnter the postfix expression:\n");
flushall();
gets(postfix);
top=-1;
for(i=0; <strlen(postfix); i++)
{
symbol = postfix[i];
if(isdigit(symbol))
s[++top] = symbol - '0';
else
{
op2 = s[top--];
op1 = s[top--];
res = compute(symbol, op1, op2);
s[++top] = res;
}
}
res = s[top--];
printf("\nThe result is : %f\n", res);
}
PROGRAM OUTPUT:
RUN1:
THEORY:
The 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:
Only one disk can be moved at a time.
Each move consists of taking the upper disk from one of the stacks and placing it on top
of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a
Tower of Hanoi puzzle is 2n - 1, where n is the number of disks.
ALGORITHM:
Step 1: Start.
Step 2: Read N number of discs.
Step 3: Move all the discs from source to destination by using temp rod.
Step 4: Stop.
PROGRAM 4B:
#include<stdio.h>
#include<conio.h>
void TOWER(int, char[], char[], char[]);
void main()
{
int N;
clrscr;
printf("Enter the number of disks to be
transferred:"); scanf("%d",&N);
if(N<1)
{
printf("\nIncorrect value");
}
else
{
printf("\nThe following moves are required for n=%d\n\n",N);
TOWER(N, "BEG", "AUX", "END");
}
getch();
}
void TOWER(int NUM, char A[50], char B[50], char C[50])
{
if(NUM==1)
{
printf("%s->%s\t",A,C);
return;
}
TOWER(NUM-1,A,C,B);
printf("%s->%s\t",A,C);
TOWER(NUM-1,B,A,C);
return;
}
PROGRAM OUTPUT:
QUESTIONS:
3. Write a program in C/C++ to solve the Tower of Hanoi problem for 5 discs.
EXPERIMENT 7
OBJECTIVE:
Design, Develop and Implement a menu driven Program in C for the following operations on Circular QUEUE
of Characters
a. Insert an Element on to Circular QUEUE
b. Delete an Element from Circular QUEUE
c. Demonstrate Overflow and Underflow situations on Circular QUEUE
d. Display the status of Circular QUEUE
e. Exit
Support the program with appropriate functions for each of the above operations
THEORY:
Circular queue is a linear data structure. It follows FIFO principle. In circular queue the last node is
connected back to the first node to make a circle. Circular linked list fallow the First In First Out principle.
Elements are added at the rear end and the elements are deleted at front end of the queue. The queue is
considered as a circular queue when the positions 0 and MAX-1 are adjacent. Any position before front is also
after rear.
ALGORITHM:
Step 1: Start.
Step 2: Initialize queue size to MAX.
Step 3: Insert the elements into circular queue. If queue is full give a message as ‘queue is overflow”
Step 4: Delete an element from the circular queue. If queue is empty give a message as ‘queue is
underflow’.
Step 5: Display the contents of the
queue. Step 6: Stop.
PROGRAM IN C++
#include<stdio.h>
# define MAX 5
int cqueue_arr[MAX];
int front = -1; /*The queue is empty*/ /*Deletion in front*/
int rear = -1; /*The queue is empty*/ /*Insertion in rear*/
void insert(int item)
{
if((front == 0 && rear == MAX-1) || (front == rear+1))
{
printf("Queue Overflow");
return;
}
if(front == -1)
{
front = 0;
rear = 0;
}
else
{
if(rear == MAX-1)
rear = 0;
else
rear = rear+1;
}
cqueue_arr[rear] = item ;
}
void delete()
{
if(front == -1)
{
printf("Queue Underflow");
return ;
}
printf("Element deleted from queue is : %d \n",cqueue_arr[front]);
if(front == rear)
{
front = -1;
rear=-1;
}
else
{
if(front == MAX-1)
front = 0;
else
front = front+1;
}
}
void display()
{
int front_pos = front,rear_pos = rear;
if(front == -1)
{
printf("Queue is
empty"); return;
}
printf("Queue elements :\n");
if( front_pos <= rear_pos )
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
else
{
while(front_pos <= MAX-1)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
front_pos = 0;
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
}
printf("\n");
}
int main()
{
int choice,item;
do
{
printf("\n Circular Queue:");
printf("\n1.Insert"); printf("\
n2.Delete"); printf("\
n3.Display"); printf("\
n4.Quit"); printf("\nEnter your
choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Input the element for insertion in queue : ");
scanf("%d", &item);
insert(item);
break;
case 2 :
delete();
break;
case 3:
display();
break;
case 4:
break;
default:
printf("Wrong choice");
}
}while(choice!=4);
return 0;
}
PROGRAM OUTPUT
Circular Queue:
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice: 1
Input the element for insertion in queue : 22
Circular Queue:
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice: 1
Input the element for insertion in queue : 56
Circular Queue:
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice: 1
Input the element for insertion in queue : 35
Circular Queue:
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice: 1
Input the element for insertion in queue : 22
Circular Queue:
1. Insert
2. Delete
3.Display
4.Quit
Enter your choice: 3
Queue elements :
22 56 35 22
Circular Queue:
1. Insert
2. Delete
3.Display
4.Quit
Enter your choice: 2
Circular Queue:
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice: 3
Queue elements :
56 35 22
Circular Queue:
1. Insert
2.Delete
3.Display
4.Quit
Enter your choice: 4
QUESTIONS:
2. Write a program in C/C++ to delete the element 30 from the following Circular
Queue 12 , 10 , 20 , 30 , 130
3. Write a program in C/C++ to insert an element 60 after the element 20 in the following Circular
Queue
100 , 70 , 20 , 40 , 80
EXPERIMENT 8
OBJECTIVE:
Design, Develop and Implement a menu driven Program in C/C++ for the following operations on Singly
Linked List (SLL)
a. Create a SLL.
b. Insert at Beginning
c. Insert at Last
d. Insert at any random location
e. Delete from Beginning
f. Delete from Last
g. Delete node after specified location
h. Search for an element
i. Show
j. Exit
THEORY:
Linked List is a linear data structure and it is very common data structure which consists of group of nodes in a
sequence which is divided in two parts. Each node consists of its own data and the address of the next node and
forms a chain. Linked Lists are used to create trees and graphs.
They are a dynamic in nature which allocates the memory when required.
Insertion and deletion operations can be easily implemented.
PROGRAM in C:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node*)malloc(sizeof(struct
node)); if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value?\n");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
ptr -> next = NULL;
head = ptr; printf("\
nNode inserted");
}
else
{
temp = head;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = ptr;
ptr->next =
NULL;
printf("\nNode inserted");
}
}
}
//Insert at random position
void randominsert()
{
int i,loc,item;
struct node *ptr, *temp;
ptr = (struct node *) malloc (sizeof(struct
node)); if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter element value");
scanf("%d",&item);
ptr->data = item;
printf("\nEnter the location after which you want to insert ");
scanf("\n%d",&loc);
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\nCan't insert\n");
return;
}
}
ptr ->next = temp ->next;
temp ->next = ptr;
printf("\nNode inserted");
}
}
//Delete at the Beginning
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty\n");
}
else
{
ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}
//Delete at Last
void last_delete()
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("\nlist is empty");
}
else if(head -> next == NULL)
{
head = NULL;
free(head);
printf("\nOnly node of the list deleted ...\n");
}
else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL;
free(ptr);
printf("\nDeleted Node from the last ...\n");
}
}
//Delete at random position
void random_delete()
{
struct node *ptr,*ptr1;
int loc,i;
printf("\n Enter the location of the node after which you want to perform deletion \n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++)
{
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL)
{
printf("\nCan't delete");
return;
}
}
ptr1 ->next = ptr -
>next; free(ptr);
printf("\nDeleted node %d ",loc+1);
}
//Search for an
element void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("Item not found\n");
}
}
}
//Display the elements
void display()
{
struct node *ptr;
ptr = head;
if(ptr ==
NULL)
{
printf("Nothing to print");
}
else
{
printf("\nprinting values..........\n");
while (ptr!=NULL)
{
printf("\n%d",ptr->data);
ptr = ptr -> next;
}
}
}
PROGRAM OUTPUT:
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 1
Enter value
10
Node inserted
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 1
Enter value
20
Node inserted
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 1
Enter value
30
Node inserted
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 8
printing values . . . . .
30
20
10
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 2
Enter value?
40
Node inserted
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 2
Enter value?
50
Node inserted
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 8
printing values . . . . .
30
20
10
40
50
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 7
search? 10
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
7. Search for an
element 8.Show
9.Exit
Enter your
choice? 3
2 Node inserted
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 8
printing values . . . . .
30
20
10
99
40
50
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 4
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 8
printing values . . . . .
20
10
99
40
50
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 5
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 8
printing values . . . . .
20
10
99
40
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 6
Enter the location of the node after which you want to perform deletion
Deleted node 3
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8.Show
9.Exit
Enter your
choice? 8
printing values . . . . .
20
10
40
*********Main Menu*********
===============================================
1.Insert at Beginning
2.Insert at Last
8. Show
9.Exit
Enter your
choice? 9
EXPERIMENT 9
OBJECTIVE:
Design, Develop and Implement a menu driven Program in C/C++ for the following operations on Doubly
Linked List (DLL)
a. Create a DLL.
b. Print all the elements in DLL in forward traversal order
c. Print all elements in DLL in reverse traversal order
d. Exit
THEORY:
Doubly Linked List: In a doubly linked list, each node contains two links the first link points to the previous
node and the next link points to the next node in the sequence. In computer science, a doubly linked list is a
linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two
fields, called links, that are references to the previous and to the next node in the sequence of nodes. The
beginning and ending nodes' previous and next links, respectively, point to some kind of terminator, typically a
sentinel node or null, to facilitate traversal of the list. If there is only one sentinel node, then the list is circularly
linked via the sentinel node. It can be conceptualized as two singly linked lists formed from the same data items,
but in opposite sequential orders. A doubly linked list whose nodes contain three fields: an integer value, the
link to the next node, and the link to the previous node. The two node links allow traversal of the list in either
direction. While adding or removing a node in a doubly linked list requires changing more links than the same
operations on a singly linked list, the operations are simpler and potentially more efficient (for nodes other than
first nodes) because there is no need to keep track of the previous node during traversal or no need to traverse
the list to find the previous node, so that its link can be modified.
PROGRAM IN C:
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
newNode->next = head;
head = newNode;
}
//main function
int main() {
// Calling an Insert and printing list both in forward as well as reverse direction.
InsertAtTail(2); Print(); ReversePrint();
InsertAtTail(4); Print(); ReversePrint();
InsertAtTail(6); Print(); ReversePrint();
InsertAtHead(1); Print(); ReversePrint();
InsertAtHead(9); Print(); ReversePrint();
PROGRAM OUTPUT:
Forward: 1 2 4 6
Reverse: 6 4 2 1
Forward: 9 1 2 4 6
Reverse: 6 4 2 1 9
QUESTIONS:
1. Write a program in C/C++ to implement Doubly Linked List by inserting the following
data 1↔ 5 ↔ 8 ↔ 2 ↔ 7
2. Write a program in C/C++ to insert an element 3 before the 1st node (having data: 1) in the
following Doubly Linked List (Try yourself)
1↔ 7 ↔ 5 ↔ 2 ↔ 8
3. Write a program in C/C++ to delete the last node from the following DLL and also show how the
DLL can be used as Double Ended Queue (Try yourself)
10↔ 5 ↔ 2 ↔ 3 ↔ 1
EXPERIMENT 10
OBJECTIVE:
Design, Develop and Implement a menu driven Program in C for the following operations on Binary Search
Tree (BST) of Integers
a. Create a BST of N Integers: 8, 10, 3, 1, 6, 14, 7
a. Traverse the BST in Inorder
b. Traverse the BST in Preorder
c. Traverse the BST in and Post Order
THEORY:
A binary search tree (BST) is a tree in which all nodes follows the below mentioned properties
The left sub-tree of a node has key less than or equal to its parent node's key.
The right sub-tree of a node has key greater than or equal to its parent node's key.
Thus, a binary search tree (BST) divides all its sub-trees into two segments; left sub-tree and right sub-tree and
can be defined as
left_subtree (keys) ≤ node (key) ≤ right_subtree (keys)
Example of BST
Node definition: Define a node having some data, references to its left and right child nodes.
struct node
{
int data;
struct node *leftChild;
struct node *rightChild;
};
ALGORITHM:
Step 1: Start.
Step 2: Create a Binary Search Tree for N
elements. Step 3: Traverse the tree in inorder.
Step 4: Traverse the tree in preorder
Step 6: Traverse the tree in
postorder.
PROGRAM IN C:
#include<stdio.h>
#include<stdlib.h>
{
if(root==NULL)
return;
inorder(root->left); /*Start checking form the left sub-tree*/
printf("%d ",root->data); /*Print value of current node*/
inorder(root->right); /*Check right sub-tree*/
return;
}
void preorder(struct Node *root)
{
if(root!=NULL)
{
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
}
void postorder(struct Node *root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d ", root-
>data);
}
}
int main()
{
struct Node* root=NULL;
root=insertElement(root,8);
root=insertElement(root,10);
root=insertElement(root,3);
root=insertElement(root,1);
root=insertElement(root,6);
root=insertElement(root,14);
root=insertElement(root,7);
printf("Inorder traversal:\n");
inorder(root);
printf("\nPreorder traversal:\n");
preorder(root); printf("\
nPostorder traversal:\n");
postorder(root);
return 0;
}
PROGRAM OUTPUT:
Inorder traversal:
1 3 6 7 8 10 14
Preorder traversal:
8 3 1 6 7 10 14
Postorder traversal:
1 7 6 3 14 10 8
QUESTIONS:
1. Write a program in C/C++ to search the element 6 in the following binary tree (try yourself).
2. Write a program in C/C++ to insert the element 12 in the following binary tree (try yourself).
3. Write a program in C/C++ to perform Inorder, Preorder and Postorder tree traversal for
the following binary tree.
Note: If you want to perform Inorder, Preorder, Postorder, Searching, and Deletion in a single
program, use switch case.
EXPERIMENT 11
OBJECTIVE:
Design, Develop and Implement a Program in C for the following operations on Graph(G) of Cities
a. Create a Graph of N cities using Adjacency Matrix.
b. Print all the nodes reachable from a given starting node in a digraph using BFS method
c. Print all the nodes reachable from a given starting node in a digraph using DFS method
.
THEORY:
Adjacency Matrix
In graph theory, computer science, an adjacency matrix is a square matrix used to represent a finite graph.
The elements of the matrix indicate whether pairs of vertices are adjacent or not in the graph. In the special
case of a finite simple graph, the adjacency matrix is a (0, 1)-matrix with zeros on its diagonal. A graph G =
(V, E) where v= {0, 1, 2, . . .n-1} can be represented using two dimensional integer array of size n x n.
a[20][20] can be used to store a graph with 20 vertices.
a[i][j] = 1, indicates presence of edge between two vertices i and j.
a[i][j] = 0, indicates absence of edge between two vertices i and j.
A graph is represented using square matrix.
Adjacency matrix of an undirected graph is always a symmetric matrix, i.e. an edge (i, j) implies the edge (j,i).
Adjacency matrix of a directed graph is never symmetric, adj[i][j] = 1 indicates a directed edge from vertex i
to vertex j.
BFS
Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at
the tree root and explores the neighbor nodes first, before moving to the next level neighbors. Breadth First
Search algorithm(BFS) traverses a graph in a breadth wards motion and uses a queue to remember to get the
next vertex to start a search when a dead end occurs in any iteration.
DFS
Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at
the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along
each branch before backtracking.
Depth-first search, or DFS, is a way to traverse the graph. Initially it allows visiting vertices of the graph only,
but there are hundreds of algorithms for graphs, which are based on DFS. Therefore, understanding the
principles of depth-first search is quite important to move ahead into the graph theory. The principle of the
algorithm is quite simple: to go forward (in depth) while there is such possibility, otherwise to backtrack
#include<stdio.h>
#include<stdlib.h>
struct queue
{
int size;
int f;
int r;
int* arr;
};
int main()
{
struct queue q;
q.size = 400;
q.f = q.r = 0;
q.arr = (int*) malloc(q.size*sizeof(int));
// BFS implementation
int node;
int i=0;
int visited[4]={0,0,0,0};
int a[4][4]={
{0,0,1,1},
{0,0,0,0},
{0,1,0,0},
{0,1,0,0}
};
printf("%d",i);
visited[i]=1;
enqueue(&q,i); //Enqueue i for exploration
while(!isEmpty(&q))
{
int node=dequeue(&q);
for(int j=0;j<4;j++)
{
if(a[node][j]==1 && visited[j]==0)
{
printf("%d",j);
visited[j]=1;
enqueue(&q,j);
}
}
}
}
PROGRAM OUTPUT:
0231
#include<stdio.h>
int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10]
void main()
{
int i,j;
printf("Enter number of vertices:");
scanf("%d",&n); //read the adjacency matrix
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
for(i=0;i<n;i++)
visited[i]=0; //visited is initialized to zero
DFS(0);
}
void DFS(int i)
{
int j; printf("\
n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}
PROGRAM OUTPUT:
0
2
1
3
QUESTIONS:
1. Write a program in C/C++ to create the following Graph using Adjacency Matrix.
2. Write a program in C/C++ to perform DFS traversal for the following graph
3. Write a program in C/C++ to perform BFS traversal for the following graph