0% found this document useful (0 votes)
6 views

Data Structure and Algorithm Lab Manual

This lab manual for Data Structures and Algorithms at Gomal University provides a comprehensive guide for BEE students, covering practical experiments aligned with the curriculum. It includes detailed lab exercises, safety rules, emergency response procedures, and guidelines for lab reports, aiming to enhance programming skills and theoretical understanding. The manual also outlines learning outcomes and recommended software for effective lab work.

Uploaded by

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

Data Structure and Algorithm Lab Manual

This lab manual for Data Structures and Algorithms at Gomal University provides a comprehensive guide for BEE students, covering practical experiments aligned with the curriculum. It includes detailed lab exercises, safety rules, emergency response procedures, and guidelines for lab reports, aiming to enhance programming skills and theoretical understanding. The manual also outlines learning outcomes and recommended software for effective lab work.

Uploaded by

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

Department of Electrical Engineering

Faculty of Engineering and Technology,


Gomal University, D. I. Khan

CS-215L: Data Structures and Algorithm


(Lab Manual)
__________________________________________________________________

OBE Based Lab Manual


OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

In this manual of Data Structure and Algorithms practical, efforts


have been made to include whole syllabus of Data Structure and
Algorithm practical at graduation level with relevant theoretical
back ground, the manual has been compiled to meet the
present need of the BEE students undergoing lab
experiments. An effort is in pipeline to include experiments
to match the advance level gradually. Finally, it is a pleasure
to thank Engr. Asad for his excellent work in
making & compiling the manual.

Reviewed By:

________________
Engr. Jamal Abdul Nasir
In-Charge Laboratories EED, F.E.T

Approved By:

________________
Engr. Dr. Ishtiaq Ahmad
Chairman EED, F.E.T
i|P ag e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Table of Contents
Lab No. 01: Character Type Array to Take User Entered Text and Display ............................................. 1
Lab No. 02: Develop a program for Insertion and Deletion of Elements in the Array ............................... 2
Lab No. 03: Develop a program for Single Link List creation and perform operations ............................. 3
Lab No. 04: Develop a program for user input Single Link List with operations ...................................... 6
Lab No. 05: Develop a program for Double Link List creation with all operations................................... 9
Lab No. 06: Develop a program Push and Pop Operations using Stacked Array .................................... 14
Lab No. 07 (a): Develop a program for FIFO based Queue Insertion and Deletion ................................ 16
Lab No. 07 (b): Develop a Program for FIFO based Queue Insertion and Deletion ................................ 19
Lab No. 07 (c): Develop a Program for FIFO based Functional Queue Insertion and Deletion ............... 21
Lab No. 08: Develop a Program for Bubble Sorting using functions ...................................................... 24
Lab No. 09: Develop a Program for Pre-defined Post Order, In Order and Pre-Order Traversing ........... 26
Lab No. 10: Develop a Program for Binary Search Tree Creation (BST) using Link List ....................... 28
Lab No. 11: Develop a Program for Heap sorting using functions to heapify the array........................... 31
Lab No. 12: Develop a program for elements searching in an array ....................................................... 33
Lab No. 13: Develop a program for Infix to Postfix conversion using functions .................................... 34

ii | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Basic Safety Rules & Hazards


Basic Safety Rules:
1. Try to type the program alone first to fingertip the programming skills in data structure and
algorithm and error removal from simulation to design either android based apps, even games
or any other official supported software. Try to find out the error from yourself so that you
become more precise in coding.
2. Start all exercises by inspecting the equipment. Always remain your USB clean and free of
virus before inserting in the lab computer as the exchange of viruses may harm both.
3. Never leave an active work area unattended. Always show your program to the lab instructor
before leaving the lab so that your simulation can be viewed and corrected in case of any
mistake.

Hazards
1. There are some hazards in computer lab which should be prevented with maximum including
voltage fluctuation which may burn the power supply and cause blast.
2. The most serious concerned in the computer laboratory is self-plugging of hardware parts with
CPU.
3. Avoid self-starting of main switch behind the sitting place of lab assistant as all the labs
equipment including network switch or Wi-Fi router is connected with it. Consult the assistant
immediate in case of any voltage fluctuation.
4. Avoid to install any software from yourself from your own USB and ask the assistant to do it
as your own manipulation in lab computer may cause the windows to be corrupted.

Emergency Response
1. In the event of electrical shock follow these procedures.
2. Turn off or disconnect the row main switch located on the respective line wall to avoid the
power supply burn.
3. Avoid to touch every electric switch as it may be short which can be harmful.
4. Don't touch any wire in case of voltage fluctuation in case of any mishappening.
Note:
Avoid to do lab work/assignment other than programming in this lab.

iii | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab Report Guidelines and Format


Reports are due at the beginning of the lab period. The reports are intended to be a complete
documentation of the work done in preparation for and during the lab. The report should be
complete so that someone else familiar with programming could use it to verify your work. Each
student should need to complete the given task as coding. Try to write the entire program from
yourself and simulate it. In case of errors, try to remove these errors and compile it with your own
mind. Error removal from own thinking can create much good ideas to program. Always show
your respective results to the lab instructor before leaving the lab. Your such interest in lab will
make you enough to program any complicated task related to projects as android application and
gaming design. Neatness, organization, and completeness will be rewarded. Points will be
deducted for any part that is not clear. Don’t copy your reports with your fellows. Each report will
contain the following sections:
1. Title
It consists of Lab No., Lab name/title and date.

2. Objectives
Write down the objectives that you think the lab will teach you.

3. Apparatus (Commands)
Write down the commands used in the Lab.

4. Theory (Comments)
Write down the comments of each step used in the lab code briefly if u can. (Not More than a line).
Not Compulsory to write
5. Schematic Diagram/flow chart (If Any)
Draw relevant schematic/code diagram/flow chart for each experiment.

6. Program Code (If Any)


Write the program code for each experiment and it is compulsory.

7. Procedure
Write the comments as procedure to the point if you can otherwise leave it. Not Compulsory

8. Readings Required (Output of program)


Your program should be enough beautiful and to the point with all information clearly to
understood.

9. Lab Tasks (Can be brief questions from the lab or tasks to be performed by students.
Lab task will be according to the delivered theory lecture. Your respective theoretical lecture
would be implemented by you in lab to avail this lab logic completely.

iv | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Laboratory Goals
The main task for this lab is to enable the student to program the complicated problems related to
any engineering field in terms of coding, so that at the end of the engineering, student will remain
enough the accelerate work in projects and work in software houses. Programming is the
fundamental language in engineering to design any software, games or microcontroller-based
projects and student should remain enough skillful to do it with maximum interest and knowledge.
Student should know about the header files and their respective commands which are used in
almost every task in engineering world.

The Purpose of Technical Report


Report should show good technician supervisor that the experimental work, which was attended
with satisfactory results. Report issued by the College of Engineering provides practice in the art
of technical writing. Individual discussions and conclusions contained in the report of the
laboratory group allow each student to develop a deeper understanding of the laboratory work, and
the use of creativity in the development or implementation of laboratory experiments. The
technical report is written usually with the help of references. Skills in learning how to find the
professionals is the value of assets that are associated with professional engineering and technical
communications.

v|Page
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab Learnings Outcomes (LLOs)


LLOs LLOs Description
LLO 1 Describe and identify fundamentals concepts of basics and advanced data structures.
Applications and algorithm and principles of linear and non-linear data structures to a
LLO 2
particular problem.
Detection of complex error compile and execute complicated codes to learn applications
LLO 3
designing codes to run applications.
Develop small to moderate level programs to manipulate and manage data base while
LLO 4
exhibiting the programming skills.
Listen attentively to the lab demonstrations, follow the professional dress code safety rules
LLO 5
and lab timings as per instructions and display active team work and high ethical standards.

Lab 01: Develop a program for character type array to display user entered text or sentence.
Objective 1: Learn how to declare user input character type array and then display on screen.
Objective 2: To understand how to display the sentence or text.

Lab 02: Develop a program for insertion/deletion of elements in array at different locations.
Objective 1: Learn about the insertion of user input elements at different locations and deletion of user
input elements at different locations.
Objective 2: Simulate the code to detect the probably held error.

Lab 03: Develop a program for Single Link List creation, insertion, display, traversing, deletion.
Objective 1: Learn the pre-defined single link creation and develop code the deletion method of elements
in pre-defined values in single link list.
Objective 2: Apply the code by entering the different values for respective operations.

Lab 04: Develop a program for user input Single Link List creation with all respective operations.
Objective 1: Learn how to code the user input single link list creation, user input elements insertion with
in different locations of link list, elements deletion, traversing, ascending and descending display after
operations.
Objective 2: Detect the error in respective operation during debugging and simulation.

Lab 05: Develop a program for the Double Link List creation with all respective operations.
Objective 1: Learn to code the user I/P double link list creation, user entered elements insertion at different
locations, node to node traversing, deletion, ascending and descending order display.
Objective 2: Display the output to verify the results.

Lab 06: Develop a program for the Push and Pop operations using Stacked Array.
Objective 1: Learn to code the for the user input stack declaration.
Objective 2: Algorithms should be as Push (Insertion) & Pop operations within the declared stack.

vi | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab 07: Develop a FIFO based program to create Queue insertion and deletion using given three
method.
i. Pre-Defined Queue
ii. Linked List Queue
iii. Classes Based Queue
Objective 1: Write a Program to create general Pre-Defined (not user input one) Queue for insertion and
deletion.
Objective 2: Develop a Program to create Linked List based FIFO Queue for insertion & deletion purpose.
Objective 3: Learn to create the Classes Based FIFO Queue for insertion and deletion.

Lab 08: Develop a program for Bubble Sorting (Ascending & Descending order) using Functions and
Array.
Objective 1: Learn to code the functions with array to sort the elements in array.
Objective 2: Apply the defined functions including arrays for sort in both (Ascending & Descending)
orders.

Lab 09: Develop a program for Pre-defined Binary Tree creation using functions.
Objective 1: Write a code to create Binary Tree to traverse as In-order, Pre-order & Post-order.
Objective 2: Enter the values as right/left child values for traversing.
Objective 3: Display the results to yield traversing and conclude about three traversed trees output.

Lab 10: Develop a program for Pre-order, Post order and In-order traversing
Objective 1: Write a code to traverse according to three types.
Objective 2: Traverse using each method and compare result with manual performed traversed results.

Lab 11: Develop a program for Heap Sorting using Arrays and Functions.
Objective 1: Write a code to create the function to heapify the array.
Objective 2: Define the functions proto-types for sorting arrays.
Objective 3: Display and sort the user entered elements to heapify.

Lab 12: Write a program to search elements and its position in the ascended & descended array.
Objective 1: Write a code for elements searching and its position.
Objective 2: Display the results to verify the search with positions in both ascended & descended form.

Lab 13: Write a program for Infix to Postfix conversion using functions.
Objective 1: Define and write functions for Infix to Postfix conversion processes.
Objective 2: Display the results to verify the conversion either correct or not.

vii | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

MAPPING OF LLOs AND PLOs ALONG WITH TAXONOMY LEVELS

Table 1: LLOs and PLOs mapping Table with Taxonomy Levels


PLOs
LLOs
PLO 1 PLO 2 PLO 3 PLO 4 PLO 8

LLO 1 ✓

LLO 2 ✓

LLO 3 ✓

LLO 4 ✓

LLO 5 ✓

RECOMMENDED SOFTWARE
1. Visual Studio

2. Turbo C++

3. Dev C++

viii | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 01: Character Type Array to Take User Entered Text and Display
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int main ()
{
clrscr();
char country[10], city[15];
cin>>country;
cin>>city;
cout<<country<<city;
getch();

1|P ag e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 02: Develop a program for Insertion and Deletion of Elements in the Array

This program is to insert and delete elements in the array for nth number of elements.
#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

using namespace std;

int main()
{
clrscr();
int a[50],x,n,I,j,b[50];
cout<<”How many elements of Array you want to create?”;
cin>>n;
cout<<”\nEnter elements of Array\n”;
for(i=0;i<n;i++)
cin>>a[i];
cout<<”\nEnter element to delete:”;
cin>>x;
for(i=0,j=0;i<n;i++)
{
if(a[i]!=x)
b[j++]=a[i];
}

if(j==n)
{
cout<<”\nSoory!!!Element is not in the Array”;
exit(0);
}
else
{
cout<<”\nNew Array is “;
for(i=0;i<j;i++)
cout<<b[i]<<” “;
}
getch();
}

2|P ag e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 03: Develop a program for Single Link List creation and perform operations
a) Insertion,
b) Display,
c) Traversing
d) Deletion.

Link List is the term in which the data containing node are inter connected with each other by their
addresses using pointer type of variables which holds the addresses of the next neighbor node. In
link lists, the nodes are composed of two parts which are composed of the data to be inserted and
the pointer type variable to hold the address of the next node. Let’s see in the given example, the
node with two different parts having the data and addresses locations.

Header 100 200 300

1 200 2 300 3 NULL

4 Bytes 4 Bytes 4 Bytes 4 Bytes 4 Bytes 4 Bytes


In single link list, each node possesses 4,4 bytes for each part, i.e. total of 8 bytes takes single node
in memory. In single link list, the advantage we can avail is the less memory in the computer for
the node creation and the disadvantage is the we can only access the next neighbor node not the
previous node. It’s not the dual accessing link list through which we can perform the reverse
traversing but its only unique traversing towards forward direction.
//C++ program for insertion in a single linked
// list at a specified position

# include <iostream.h>
# include <conio.h>
# include <stdio.h>
# include <stdlib.h>
//using namespace std;
// A Linked list Node
struct Node
{
int data;
struct Node* next;
};
// Size of linked list
int size = 0;
// Function to create and return a Node
Node* getNode(int data)
{
// allocating space
Node* newNode = new Node();

3|P ag e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

// inserting the required data


newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a Node at required position
void insertPos(Node * *current, int pos, int data)
{
// This condition to check whether the
// position given is valid or not.
if (pos < 1 || pos > size + 1)
cout << "Invalid position!" << endl;
else {
// Keep looping until the pos is zero
while (pos--) {

if (pos == 0)
{
// adding Node at required position
Node* temp = getNode(data);

// Making the new Node to point to


// the old Node at the same position
temp->next = *current;

// Changing the pointer of the Node previous


// to the old Node to point to the new Node
*current = temp;
}
else
// Assign double pointer variable to point to the
// pointer pointing to the address of next Node
current = &(*current)->next;
}
size++;
}
}
// This Function prints contents of the Linked List
void printList(struct Node* head)
{
while (head != NULL) {
cout << " " << head->data;
head = head->next;
}
cout << endl;
}

4|P ag e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

// Driver Code
int main()
{
clrscr();
// Creating the list 3->5->8->10
Node* head = NULL;
head = getNode(3);
head->next = getNode(5);
head->next->next = getNode(8);
head->next->next->next = getNode(10);
size = 4;
cout << "Linked list before insertion: ";
printList(head);
int data = 12, pos = 3;
insertPos(&head, pos, data);
cout << "Linked list after insertion of 12 at position 3: ";
printList(head);
// Front of the Linked List
data = 1, pos = 1;
insertPos(&head, pos, data);
cout << "Linked list after insertion of 1 at position 1: ";
printList(head);
// Insetion at end of the Linked List
data = 15, pos = 7;
insertPos(&head, pos, data);
cout << "Linked list after insertion of 15 at position 7: ";
printList(head);
getch();
}

5|P ag e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 04: Develop a program for user input Single Link List with operations
a) Insertion in start, between and at end,
b) Display
c) Deletion at start, between and at end

# include <iostream.h>
# include <conio.h>
# include <stdlib.h>
# include <stdio.h>
//using namespace std;
struct node
{
int value;
struct node* next;
};
void insert();
void display();
void delete_node();
int count();
typedef struct node DATA_NODE;
DATA_NODE* head_node, * first_node, * temp_node = 0, * prev_node, next_node;
int data;
int main() {
int option = 0;
cout << "Singly Linked List C++ Example - All Operations\n";
while (option < 5)
{
cout << "\nOptions\n";
cout << "1 : Insert into Linked List \n";
cout << "2 : Delete from Linked List \n";
cout << "3 : Display Linked List\n";
cout << "4 : Count Linked List\n";
cout << "Others : Exit()\n";
cout << "Enter your option:";
cin>>option;
switch (option)
{
case 1:
insert();
break;
case 2:
delete_node();
break;
case 3:
display();
break;

6|P ag e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

case 4:
count();
break;
default:
break;
}
}
return 0;
}
void insert()
{
cout << "\nEnter Element for Insert Linked List : \n";
cin>>data;
temp_node = (DATA_NODE*)malloc(sizeof(DATA_NODE));
temp_node->value = data;
if (first_node == 0) {
first_node = temp_node;
}
else {
head_node->next = temp_node;
}
temp_node->next = 0;
head_node = temp_node;
fflush(stdin);
}
void delete_node()
{
int countvalue, pos, i = 0;
countvalue = count();
temp_node = first_node;
cout << "\nDisplay Linked List : \n";
cout << "\nEnter Position for Delete Element : \n";
scanf("%d", &pos);
if (pos > 0 && pos <= countvalue) {
if (pos == 1) {
temp_node = temp_node->next;
first_node = temp_node;
cout << "\nDeleted Successfully \n\n";
}
else {
while (temp_node != 0) {
if (i == (pos - 1)) {
prev_node->next = temp_node->next;
if (i == (countvalue - 1)) {
head_node = prev_node;
}

7|P ag e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

cout << "\nDeleted Successfully \n\n";


break;
}
else {
i++;
prev_node = temp_node;
temp_node = temp_node->next;
}
}
}
}
else
cout << "\nInvalid Position \n\n";
}
void display()
{
int count = 0;
temp_node = first_node;
cout << "\nDisplay Linked List : \n";
while (temp_node != 0) {
cout << "# " << temp_node->value;
count++;
temp_node = temp_node->next;
}
cout << "\nNo Of Items In Linked List: %d" << count;
}
int count()
{
int count = 0;
temp_node = first_node;
while (temp_node != 0)
{
count++;
temp_node = temp_node->next;
}
cout << "\nNo Of Items In Linked List : %d" << count;
return count;
}

8|P ag e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 05: Develop a program for Double Link List creation with all operations
a) Insertion,
b) Display,
c) Deletion,
d) Traversing
e) Reverse display with previous respective operations

Double Link List is the linked nodes in which each node is connected with its next and previous
nodes with pointer type variables.
/////Double Link List////////////////
#include <stdio.h>
#include <conio.h>
#include <iostream.h>
#include <stdlib.h>

//using namespace std;


int insertdata(int x);
void display ();
void deleteint(int x);
void reversel();
int searchint(int x);
int compare_fn(int a,int b)
{
if(a>b)
return 1;
else if(b>a)
return -1;
}

int compare_no=1;

struct node
{
int data;
node *prev;
node *next;
};
node *top = NULL;

9|P ag e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

int main ()
{
int ch, d, y;
char ans='y';
while(ans=='y')
{
cout<<"\n\t 1. Insert 2. Delete 3. Reverse 4. EXIT\enter Choice: ";
cin>>ch;
if(ch==1)
{
cout<<"Enter an Element To be inserted: ";
cin>>d;
d=insertdata(d);
display ();
}
else if(ch==2)
{
cout<<"Enter Element to Be Deleted: ";
cin>>d;
deleteint(d);
display ();
}
else if(ch==3)
reversel ();
else
return 0;
}
return 0;
}

int searchint (int x)


{
int count=0;
node *searchele=top;
while (searchele! =NULL)
{
if (compare_fn (x, searchele->data) ==compare_no)
{
searchele=searchele->next;
count+=1;
}
else
break;

10 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

}
return count;
}

int insertdata (int x)


{
if(top==NULL)
{
top=new node;
top->data=x;
top->next=NULL;
top->prev=NULL;
}
else if(compare_fn(top->data, x) ==compare_no)
{
node *n=new node;
n->data=x;
n->next=top;
n->prev=NULL;
top->prev=n;
top=n;
}
else
{
int c=searchint(x);
node *insertele=top;
for (int i=0; i<c-1; i++)
insertele=insertele->next;
node *n=new node;
n->data=x;
node *b=insertele->next;
node *N =insertele;
n->prev=insertele;
n->next=b;
insertele->next=n;
if (b! =NULL)
b->prev=n;
}
}
void display ()
{
cout<<"Element in The Linked List Are: ";
node *disp=top;

11 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

while (disp! =NULL)


{
cout<<" "<<disp->data;
if(disp->next==NULL)
{
break;
}
disp=disp->next;
}
}
void deleteint (int x)
{
node *del=top;
if(del->data == x)
{
if(del->next==NULL && del->prev==NULL)
{
top=NULL;
return;
}
del->next->prev=NULL;
top=del->next;
}
else
{
node *delsuc=del->next;
if(del==NULL)
{
cout<<"\nElement Not Found\n";
return;
}
if(delsuc==NULL)
{
cout<<"\nElement Not Found\n";
return;
}
while(delsuc->data! = x)
{
del=del->next;
delsuc=delsuc->next;
if(del==NULL)
{
cout<<"\nElement Not Found\n";

12 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

return;
}
if(delsuc==NULL)
{
cout<<"\nElement Not Found\n";
return;
}
}
del->next=delsuc->next;
if(delsuc->next! =NULL)
delsuc->next->prev=del;
}
}

void reversel ()
{
node *a=top;
node *b, *c, *d;
while (a! =NULL)
{
d=a;
c=a->next;
b=a->prev;
a->prev=a->next;
a->next=b;
a=c;
}
top=d;
cout<<"After Reversing the linked list";
display ();
compare_no*=-1;
}

13 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 06: Develop a program Push and Pop Operations using Stacked Array
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>

///using namespace std;


int stack [100], n=100, top=-1;

void push (int val)


{
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else
{
top++;
stack[top]=val;
}
}

void pop ()
{
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}

void display ()
{
if(top>=0) {
cout<<"Stack elements are:";
for (int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}

int main ()

14 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

{
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;

do
{
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch)
{
case 1:
{
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2:
{
pop ();
break;
}
case 3:
{
display ();
break;
}
case 4:
{
cout<<"Exit"<<endl;
break;
}
default:
{
cout<<"Invalid Choice"<<endl;
}
}
} while (ch! =4);
return 0;}

15 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 07 (a): Develop a program for FIFO based Queue Insertion and Deletion
Queue is list of inserted elements which are sequentially filled through First Come First Out
(FIFO) phenomena. Elements in Que can either be inserted, deleted or displayed like array.

Front Rear
Null
1 2 3 4 5 6 7 8 9 10….
N=10
(Total Number of Elements insert in Queue)
Queue

Front and Rear are the pointer which will point the first and last point in the Queue respectively.

#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
#define MAX 10

//using namespace std;

class Queue
{
int front,rear;
int queue[MAX];

public:

Queue()
{
front=rear=-1;
}

void qinsert(int item)


{
if(rear==MAX-1)
{
cout<<"\nQUEUE OVERFLOW";
}
else if(front==-1 && rear==-1)
{

16 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

front=rear=0;
queue[rear]=item;
cout<<"\nITEM INSERTED: "<<item;
}
else
{
rear++;
queue[rear]=item;
cout<<"\nITEM INSERTED: "<<item;
}
}

void qdelete()
{
int item;

if(rear==-1)
{
cout<<"\nQUEUE UNDERFLOW";
}
else if(front==0 && rear==0)
{
item=queue[front];
front=rear=-1;
cout<<"\n\nITEM DELETED: "<<item;
}
else
{
item=queue[front];
front++;
cout<<"\n\nITEM DELETED: "<<item;
}
}

void qtraverse()
{
if(front==-1)
{
cout<<"\n\nQUEUE IS EMPTY\n";
}
else
{
cout<<"\n\nQUEUE ITEMS\n";

17 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

for(int i=front;i<=rear;i++)
{
cout<<queue[i]<<" ";
}
cout<<endl;
}
}
};

int main()
{
clrscr();
Queue q;

q.qtraverse();
q.qinsert(10);
q.qinsert(20);

q.qtraverse();

q.qdelete();
q.qinsert(30);

q.qtraverse();
getch();
}

18 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 07 (b): Develop a Program for FIFO based Queue Insertion and Deletion
/* Simple Queue Program in C++*/
/* Data Structure C++ Programs, C++ Array Examples */

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

#define MAX_SIZE 100

//using namespace std;

int main()

{
clrscr();
int item, choice, i;
int arr_queue[MAX_SIZE];
int rear = 0;
int front = 0;
int exit = 1;

cout << "\nSimple Queue Example - Array";

do
{
cout << "\n\n Queue Main Menu";

cout << "\n1.Insert \n2.Remove \n3.Display \nOthers to exit";


cout << "\nEnter Your Choice : ";
cin>>choice;
switch (choice)

{
case 1:
if (rear == MAX_SIZE)
cout << "\n## Queue Reached Max!!";
else {
cout << "\nEnter The Value to be Insert : ";
cin>>item;
cout << "\n## Position : " << rear + 1 << " , Insert Value : " << item;

19 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

arr_queue[rear++] = item;
}
break;
case 2:
if (front == rear)
cout << "\n## Queue is Empty!";
else {
cout << "\n## Position : " << front << " , Remove Value :" <<
arr_queue[front];
front++;
}
break;
case 3:
cout << "\n## Queue Size : " << (rear - front);
for (i = front; i < rear; i++)
cout << "\n## Position : " << i << " , Value : " << arr_queue[i];
break;
default:
exit = 0;
break;
}
}
while (exit);

return 0;
}

20 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 07 (c): Develop a Program for FIFO based Functional Queue Insertion and
Deletion

/* Simple Queue Program Using Class and Memeber Functions in C++*/


/* Data Structure C++ Programs,C++ Array Examples */

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

#define MAX_SIZE 100

//using namespace std;

class Queue {
private:
int item, i;
int arr_queue[MAX_SIZE];
int rear;
int front;

public:

Queue() {
rear = 0;
front = 0;
}

void insert() {
if (rear == MAX_SIZE)
cout << "\n## Queue Reached Max!";
else {
cout << "\nEnter The Value to be Insert : ";
cin>>item;
cout << "\n## Position : " << rear + 1 << " , Insert Value : " << item;
arr_queue[rear++] = item;
}
}

void removeData() {
if (front == rear)
cout << "\n## Queue is Empty!";

21 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

else {
cout << "\n## Position : " << front << " , Remove Value :" << arr_queue[front];
front++;
}
}

void display() {
cout << "\n## Queue Size : " << (rear - front);
for (i = front; i < rear; i++)
cout << "\n## Position : " << i << " , Value : " << arr_queue[i];
}
};

int main() {
int choice, exit_p = 1;
Queue obj;
cout << "\nSimple Queue Example - Class and Memeber Functions in C++";
do {
cout << "\n\n Queue Main Menu";

cout << "\n1.Insert \n2.Remove \n3.Display \nOthers to exit";


cout << "\nEnter Your Choice : ";
cin>>choice;
switch (choice) {
case 1:
obj.insert();
break;
case 2:
obj.removeData();
break;
case 3:
obj.display();
break;
default:
exit_p = 0;
break;
}
}
while (exit_p);
return 0;
}

22 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

In Binary Search Tree, user has to entered number before decision either it will be right child or
left. Pre-Defined size-based programming is known as Static Programming. The programming
which is used to write the Binary Search Tree is known as Dynamic Programming. First number
will always be base and move to root. The logic of left or right node will be base on comparison
with root. The number will be compared to root, if greater than root, it will move to right otherwise
move to left. Every next number would be checked in sequence with root and then be decided
either left child or right child. If let’s suppose the number is -10 which is less than the 1. It will
move towards the left child.
If root is equal

23 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 08: Develop a Program for Bubble Sorting using functions
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
//using namespace std;
void swapping(int &a, int &b)
{ //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size)
{
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void bubbleSort(int *array, int size)
{
for(int i = 0; i<size; i++)
{
int swaps = 0; //flag to detect any swap is there or not
for(int j = 0; j<size-i-1; j++)
{
if(array[j] > array[j+1])
{ //when the current item is bigger than next
swapping(array[j], array[j+1]);
swaps = 1; //set swap flag
}
}
if(!swaps)
break; // No swap in this pass, so array is sorted
}
}
void main()
{
clrscr();
int n;
cout << "Enter the number of elements: ";
cin >> n;

24 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

int arr[6]; //create an array with given number of elements


cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++)
{
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
bubbleSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
getch();
}

25 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 09: Develop a Program for Pre-defined Post Order, In Order and Pre-Order
Traversing

#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
//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);
printPostorder(node->right);
cout << node->data << " ";
}

void printInorder(struct Node* node)


{
if (node == NULL)
return;
printInorder(node->left);
cout << node->data << " ";
printInorder(node->right);
}

void printPreorder(struct Node* node)


{
if (node == NULL)
return;
cout << node->data << " ";

26 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

printPreorder(node->left);
printPreorder(node->right);
}

int main()
{
clrscr();
struct Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);

cout << "\nPreorder traversal of binary tree is \n";


printPreorder(root);

cout << "\nInorder traversal of binary tree is \n";


printInorder(root);

cout << "\nPostorder traversal of binary tree is \n";


printPostorder(root);

getch();
}

27 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 10: Develop a Program for Binary Search Tree Creation (BST) using Link
List

#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
//using namespace std;
struct tree
{
tree *l, *r;
int data;
}*root = NULL, *p = NULL, *np = NULL, *q;
void create()
{
int value,c = 0;
while (c < 7)

{
if (root == NULL)
{
root = new tree;
cout<<"enter value of root node\n";
cin>>root->data;
root->r=NULL;
root->l=NULL;
}
else
{
p = root;
cout<<"enter value of node\n";
cin>>value;
while(true)
{
if (value < p->data)
{
if (p->l == NULL)
{
p->l = new tree;
p = p->l;
p->data = value;
p->l = NULL;
p->r = NULL;
cout<<"value entered in left\n";
break;
}

28 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

else if (p->l != NULL)


{
p = p->l;
}
}
else if (value > p->data)
{
if (p->r == NULL)
{
p->r = new tree;
p = p->r;
p->data = value;
p->l = NULL;
p->r = NULL;
cout<<"value entered in right\n";
break;
}
else if (p->r != NULL)
{
p = p->r;
}
}
}
}
c++;
}
}

void inorder(tree *p)


{
if (p != NULL)
{
inorder(p->l);
cout<<p->data<<endl;
inorder(p->r);
}
}
void preorder(tree *p)
{
if (p != NULL)
{
cout<<p->data<<endl;
preorder(p->l);
preorder(p->r);
}
}

29 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

void postorder(tree *p)


{
if (p != NULL)
{
postorder(p->l);
postorder(p->r);
cout<<p->data<<endl;
}
}

int main()
{
clrscr();
create();
cout<<"printing traversal in inorder\n";
inorder(root);
cout<<"printing traversal in preorder\n";
preorder(root);
cout<<"printing traversal in postorder\n";
postorder(root);
getch();
}

30 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 11: Develop a Program for Heap sorting using functions to heapify the array
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>

///using namespace std;

// A function to heapify the array.


void MaxHeapify(int a[], int i, int n)
{
int j, temp;
temp = a[i];
j = 2*i;

while (j <= n)
{
if (j < n && a[j+1] > a[j])
j = j+1;
// Break if parent value is already greater than child value.
if (temp > a[j])
break;
// Switching value with the parent node if temp < a[j].
else if (temp <= a[j])
{
a[j/2] = a[j];
j = 2*j;
}
}
a[j/2] = temp;
return;
}
void HeapSort(int a[], int n)
{
int i, temp;
for (i = n; i >= 2; i--)
{
// Storing maximum value at the end.
temp = a[i];
a[i] = a[1];
a[1] = temp;
// Building max heap of remaining element.
MaxHeapify(a, 1, i - 1);
}
}

31 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

void Build_MaxHeap(int a[], int n)


{
int i;
for(i = n/2; i >= 1; i--)
MaxHeapify(a, i, n);
}
int main()
{
clrscr();
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
n++;
int arr[n];
for(i = 1; i < n; i++)
{
cout<<"Enter element "<<i<<": ";
cin>>arr[i];
}
// Building max heap.
Build_MaxHeap(arr, n-1);
HeapSort(arr, n-1);

// Printing the sorted data.


cout<<"\nSorted Data ";

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


cout<<"->"<<arr[i];

getch();
}

32 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 12: Develop a program for elements searching in an array


#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
//using namespace std;
int main()
{
clrscr();
int search(int [],int,int);
int n,i,a[100],e,res;
cout<<"How Many Elements:";
cin>>n;
cout<<"\nEnter Elements of Array in Ascending order\n";
for(i=0;i<n;++i)
{
cin>>a[i];
}
cout<<"\nEnter element to search:";
cin>>e;
res=search(a,n,e);
if(res!=-1)
cout<<"\nElement found at position="<<res+1;
else
cout<<"\nElement is not found....!!!";
getch();
}
int search(int a[],int n,int e)
{
int f,l,m;
f=0;
l=n-1;
while(f<=l)
{ m=(f+l)/2;
if(e==a[m])
return(m);
else
if(e>a[m])
f=m+1;
else
l=m-1;
}
getch();
}

33 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

Lab No. 13: Develop a program for Infix to Postfix conversion using functions
#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
#define SIZE 100
char stack[SIZE];
int top = -1;

void push(char item)


{
if(top >= SIZE-1)
{
cout<<"\nStack Overflow.";
}
else
{
top = top+1;
stack[top] = item;
}
}

/* define pop operation */


char pop()
{
char item ;

if(top <0)
{
cout<<"stack under flow: invalid infix expression";
getchar();
exit(1);
}
else
{
item = stack[top];
top = top-1;
return(item);
}
}

int is_operator(char symbol)


{

34 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol =='-')
{
return 1;
}
else
{
return 0;
}
}

int precedence(char symbol)


{
if(symbol == '^')/* exponent operator, highest precedence*/
{
return(3);
}
else if(symbol == '*' || symbol == '/')
{
return(2);
}
else if(symbol == '+' || symbol == '-') /* lowest precedence */
{
return(1);
}
else
{
return(0);
}
}

void InfixToPostfix(char infix_exp[], char postfix_exp[])


{
int i, j;
char item;
char x;

push('('); /* push '(' onto stack */


strcat(infix_exp,")"); /* add ')' to infix expression */

i=0;
j=0;
item=infix_exp[i]; /* initialize before loop*/

while(item != '\0') /* run loop till end of infix expression */


{
if(item == '(')

35 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

{
push(item);
}
else if( isdigit(item) || isalpha(item))
{
postfix_exp[j] = item; /* add operand symbol to postfix expr */
j++;
}
else if(is_operator(item) == 1) /* means symbol is operator */
{
x=pop();
while(is_operator(x) == 1 && precedence(x)>= precedence(item))
{
postfix_exp[j] = x; /* so pop all higher precendence
operator and */
j++;
x = pop(); /* add them to postfix expresion */
}
push(x);
push(item); /* push current oprerator symbol onto stack */
}
else if(item == ')') /* if current symbol is ')' then */
{
x = pop(); /* pop and keep popping until */
while(x != '(') /* '(' encounterd */
{
postfix_exp[j] = x;
j++;
x = pop();
}
}
else
{ /* if current symbol is neither operand not '(' nor ')' and nor
operator */
cout<<"\nInvalid infix Expression.\n"; /* the it is illegeal symbol */
getchar();
exit(1);
}
i++;

item = infix_exp[i]; /* go to next symbol of infix expression */


} /* while loop ends here */
if(top>0)
{
cout<<"\nInvalid infix Expression.\n"; /* the it is illegeal symbol */

36 | P a g e
OBE/2020/Data Structures and Algorithm (Lab Manual)/Rev 1

getchar();
exit(1);
}
if(top>0)
{
cout<<"\nInvalid infix Expression.\n"; /* the it is illegeal symbol */
getchar();
exit(1);
}

postfix_exp[j] = '\0'; /* add sentinel else puts() fucntion */


}
int main()
{
clrscr();
char infix[SIZE], postfix[SIZE]; /* declare infix string and postfix string */
cout<<"ASSUMPTION: The infix expression contains single letter variables and single
digit constants only.\n";
cout<<"\nEnter Infix expression : ";
gets(infix);
InfixToPostfix(infix,postfix); /* call to convert */
cout<<"Postfix Expression: ";
puts(postfix); /* print postfix expression */
getch();
}

37 | P a g e

You might also like