Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Data Structures with Algorithms : 22MCAL16

S.no Programs/Experiment Page no


1 Implement a Program in C for converting an Infix expression to Postfix 9-11
Expression
2 Design,develop, and execute a program in C to evaluate a valid postfix 12-13
expression using stack.Assume that the postfix expression is read as a single
line consisting of non-negative single digit operands and binary arithmetic
operators. The arithmetic operators are +(add),-(subtract),*(Multiply) and
/(Divide)
3 Design , develop and execute a program in C to simulate the working of queue 14-17
of integers using an array. Provide the following operations a.Insert b.Delete
c.Display
4 Write a C Program to simulate the working of a singly linked list providing the 18-29
following operations a) Display & Insert b) Delete from beginning/end c)
Delete a given element
5 Write a C Program to implement the following searching techniques a. Linear 30-31
Search b.Binary Search
6 Write a C Program to implement the following sorting algorithms using user 32-37
defined functions a) Bubble Sort(Ascending order b) selection sort(Descending
order)
7 Find the Minimum Cost Spanning tree of a given undirected graph using 38-41
Kruskal’s algorithm (C Programming)
8 From a given Vertex in a weighted connected graph, Find the Shortest Paths to 42-26
other vertices using Dijikstra’s Algorithm
Demonstration Experiments (For CIE) if any

9 Using circular representation for a polynomial design, develop and execute a


program in C to accept two Polynomials, add them, and then print the resulting
polynomials.
10 Design,develop, and execute a program in C to evaluate a valid postfix
expression using stack.Assume that the postfix expression is read as a single
line consisting of non-negative single digit operands and binary arithmetic
operators. The arithmetic operators are +(add),-(subtract),*(Multiply) and
/(Divide)

Note 1: In the practical Examination each student has to pick one question from a lot of all 8 questions.

Note 2: Change of program is not permitted in the Practical Examination.


1
1. Implement a Program in C for converting an Infix expression to Postfix Expression
#include<stdio.h>

#include<ctype.h>

char stack[100];

int top = -1;

void push(char x)

stack[++top] = x;

char pop()

if(top == -1)

return -1;

else

return stack[top--];

int priority(char x)

if(x == '(')

return 0;

if(x == '+' || x == '-')

return 1;

if(x == '*' || x == '/')


2
return 2;

return 0;

int main()

char exp[100];

char *e, x;

clrscr();

printf("Enter the expression: ");

scanf("%s",exp);

printf("\n");

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))

3
printf("%c",pop());

push(*e);

e++;

while(top != -1)

printf("%c",pop());

getch();

return 0;

OUTPUT :

2.Design,develop, and execute a program in C to evaluate a valid postfix expression using


stack.Assume that the postfix expression is read as a single line consisting of non-negative
single digit operands and binary arithmetic operators. The arithmetic operators are +(add),-
(subtract),*(Multiply) and /(Divide)

#include<stdio.h>
int stack[20];
int top = -1;

4
void push(int x)
{
stack[++top] = x;
}

int pop()
{
return stack[top--];
}

int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;
clrscr();
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}

5
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
getch();
return 0;
}

OUTPUT :

3. Design , develop and execute a program in C to simulate the working of queue


of integers using an array. Provide the following operations a.Insert b.Delete
c.Display

#include <stdio.h>

#define MAX_SIZE 100

int queue[MAX_SIZE];

6
int front = -1, rear = -1;

void insert() {

int element;

if (rear == MAX_SIZE - 1) {

printf("Error: Queue is full\n");

return;

printf("Enter element to insert: ");

scanf("%d", &element);

if (front == -1)

front = 0;

rear++;

queue[rear] = element;

printf("Element inserted successfully\n");

void delete() {

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

printf("Error: Queue is empty\n");

return;

front++;

printf("Element deleted successfully\n");

void display() {

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

7
printf("Error: Queue is empty\n");

return;

printf("Queue elements: ");

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

printf("%d ", queue[i]);

printf("\n");

int main() {

int choice;

while (1) {

printf("Queue Operations\n");

printf("1. Insert\n");

printf("2. Delete\n");

printf("3. Display\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

insert();

break;

case 2:

8
delete();

break;

case 3:

display();

break;

case 4:

printf("Exiting the program...\n");

return 0;

default:

printf("Invalid choice\n");

return 0;

OUTPUT:

Queue Operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter element to insert: 10
Element inserted successfully

Queue Operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter element to insert: 20
Element inserted successfully
9
Queue Operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 1
Enter element to insert: 30
Element inserted successfully

Queue Operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 3
Queue elements: 10 20 30

Queue Operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 2
Element deleted successfully

Queue Operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 3
Queue elements: 20 30

Queue Operations
1. Insert
2. Delete
3. Display
4. Exit
Enter your choice: 4
Exiting the program...

10
4. Write a C Program to simulate the working of a singly linked list providing the following
operations a) Display & Insert b) Delete from beginning/end c) Delete a given element
#include<stdio.h>

#include<stdlib.h>

struct node

int data;

struct node *next;

};

struct node *head;

void beginsert();

void begin_delete();

void last_delete();

void random_delete();

void display();

void search();

void main()

int choice =0;

clrscr();

while(choice != 9)

printf("\n\n*********Main Menu *******\n");

printf("\nChoose one option from the following list ...\n");

11
printf("\n=======================================================\n");

printf("\n1.Insert in begining \n2.Delete from Beginning\n3.Delete from last\n4.Delete node after specified
location\n5.Search for an element\n6.Show\n7.Exit\n");

printf("\nEnter your choice?\n");

scanf("%d",&choice);

switch(choice)

case 1:

beginsert();

break;

case 2:

begin_delete();

break;

case 3:

last_delete();

break;

case 4:

random_delete();

break;

case 5:

search();

break;

case 6:

display();

break;

case 7:

exit(0);
12
break;

default:

printf("Please enter valid choice..");

getch();

void beginsert()

struct node *ptr;

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;

ptr -> next = head;

head = ptr;

printf("\nNode inserted");

13
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");

void last_delete()

struct node *ptr, *ptr1;

if(head== NULL)

printf("\nlist is empty");

else if(head->next == NULL)

14
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");

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++)

15
{

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);

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");

16
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");

void display()

struct node *ptr;

ptr = head;

17
if(ptr == NULL)

printf("Nothing to print");

else

printf("\nprinting values.....\n");

while (ptr!=NULL)

printf("\n%d",ptr->data);

ptr = ptr ->next;

OUTPUT :

18
19
20
21
22
5. Write a C Program to implement the following searching techniques a. Linear Search
b.Binary Search

#include <stdio.h>
#include <stdlib.h>
main()
{
/* Declare variables - array_of_number,search_key.i.j,low,high*/
int array[100],search_key,i,j,n,low,high, location,choice;
void linear_search(int search_key, int array[100], int n);
void binary_search(int search_key, int array[100], int n);
clrscr();
/*read the elements of array */
printf("ENTER THE SIZE OF THE ARRAY:");
scanf("%d",&n);
printf("ENTER THE ELEMENTS OF THE ARRAY:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&array[i]);
}
/* Get the Search Key element for Linear Search */

printf("ENTER THE SEARCH KEY:");


scanf("%d",&search_key);
/* Choice of Search Algorithm */
printf("________________________________\n");
printf("1.LINEAR SEARCH\n");
printf("2.BINARY SEARCH\n");
printf("________________________________\n");
printf("ENTER YOUR CHOICE:");
scanf("%d",&choice);
switch(choice)
{
case 1:
linear_search(search_key,array,n);
break;
case 2:
binary_search(search_key,array,n);
break;

23
default:
exit(0);
}
getch();
return 0;
}

/* LINEAR SEARCH*/

void linear_search(int search_key,int array[100],int n)


{
/*Declare Variable */
int i,location;
for(i=1;i<=n;i++)
{
if(search_key==array[i])
{
location = i;
printf("______________________________________\n");
printf("The location of Search Key=%d is %d\n",search_key,location);
printf("______________________________________\n");
}
}
}

/* Binary Search to find Search Key */

void binary_search(int search_key,int array[100], int n)


{
int mid,i,low,high;
low = 1;
high=n;
mid=(low + high)/2;
i=1;
while(search_key != array[mid])
{
if(search_key<= array[mid])
{
low = 1;
high=mid+1;
mid=(low+high)/2;

24
}
else
{
low= mid+1;
high = n;
mid=(low+high)/2;
}
}
printf("______________________________________\n");
printf("location=%d\t",mid);
printf("Search Key=%d Found!\n",search_key);
printf("______________________________________\n");
}

6. Write a C Program to implement the following sorting algorithms using user defined
functions a) Bubble Sort(Ascending order b) selection sort(Descending order)

#include<stdio.h>

#include<stdlib.h>

void display(int a[], int n);

void bubble_sort(int a[], int n);

void selection_sort(int a[], int n);

//------------------Main Function-------------------

25
int main()

int n,choice,i;

int arr[20];

clrscr();

printf("Enter no. of elements you want to sort :");

scanf("%d",&n);

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

printf("Enter %d Element: ",i+1);

scanf("%d",&arr[i]);

printf("Please select any option Given Below for Sorting :\n");

while(1)

printf("\nl. Bubble Sort\n2. Selection Sort\n3. Display Array \n4. Exit the Program\n");

printf("Enter your Choice: ");

scanf("%d",&choice);

switch(choice)

case 1:

bubble_sort(arr,n);

break;

case 2:

selection_sort(arr,n);

break;

26
case 3:

display(arr,n);

break;

case 4:

return 0;

default:

printf("\nPlease Select only 1-4 option --------\n")

getch();

return 0;

//-----------End of main function---------------

//-----------Display Function-------------------

void display(int arr[], int n)

int i;

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

printf("%d\t",arr[i]);

//---------------------Bubble Sort Function--------------

void bubble_sort(int arr[], int n)

int i,j,temp;

27
for(i=0;i<n;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;

printf("After Bubble sort Elements are: ");

display(arr,n);

//--------------Selection Sort Function-------

void selection_sort(int arr[], int n)

int i,j,temp;

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

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

if(arr[i]<arr[j])

temp=arr[i];

28
arr[i]=arr[j];

arr[j]=temp;

printf("After Selection sort Elements are: ");

display(arr,n);

OUTPUT:

29
30
7. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's
algorithm ( C programming)

#include <stdio.h>

#include <stdlib.h>

#define MAX_EDGES 1000

#define MAX_VERTICES 100

typedef struct {

int from;

int to;

int weight;

} Edge;

Edge edges[MAX_EDGES];

31
int parent[MAX_VERTICES];

int rank[MAX_VERTICES];

int num_vertices, num_edges;

void make_set(int vertex) {

parent[vertex] = vertex;

rank[vertex] = 0;

int find_set(int vertex) {

if (vertex != parent[vertex]) {

parent[vertex] = find_set(parent[vertex]);

return parent[vertex];

void union_set(int x, int y) {

int root_x = find_set(x);

int root_y = find_set(y);

if (root_x != root_y) {

if (rank[root_x] > rank[root_y]) {

parent[root_y] = root_x;

} else {

parent[root_x] = root_y;

if (rank[root_x] == rank[root_y]) {

rank[root_y]++;

32
}

int compare_edges(const void* a, const void* b) {

Edge* edge1 = (Edge*)a;

Edge* edge2 = (Edge*)b;

return edge1->weight - edge2->weight;

void kruskal() {

int i, total_weight = 0;

qsort(edges, num_edges, sizeof(Edge), compare_edges);

for (i = 0; i < num_vertices; i++) {

make_set(i);

for (i = 0; i < num_edges; i++) {

Edge edge = edges[i];

if (find_set(edge.from) != find_set(edge.to)) {

union_set(edge.from, edge.to);

printf("(%d, %d) -> %d\n", edge.from, edge.to, edge.weight);

total_weight += edge.weight;

printf("Total weight of MST: %d\n", total_weight);

int main() {

int i;

33
printf("Enter number of vertices: ");

scanf("%d", &num_vertices);

printf("Enter number of edges: ");

scanf("%d", &num_edges);

printf("Enter edges (from to weight):\n");

for (i = 0; i < num_edges; i++) {

scanf("%d %d %d", &edges[i].from, &edges[i].to, &edges[i].weight);

printf("Minimum Spanning Tree:\n");

kruskal();

return 0;

OUTPUT

Enter number of vertices: 6

Enter number of edges: 9

Enter edges (from to weight):

015

0 2 10

038

134

1 4 12

233

256

342

457

34
Minimum Spanning Tree:

(2, 3) -> 3

(3, 4) -> 2

(1, 3) -> 4

(0, 1) -> 5

(2, 5) -> 6

Total weight of MST: 20

8. From a given vertex in a weighted connected graph, find shortest paths to other
vertices Using Dijkstra's algorithm (C programming)
#include <stdio.h>

#include <stdlib.h>

#include <limits.h>

#define MAX_VERTICES 1000

typedef struct {

int dest;

int weight;

struct Node* next;

} Node;

typedef struct {

Node* head;

} List;

typedef struct {

int parent;

int distance;

int visited;

List* adj_list;

} Vertex;

35
typedef struct {

Vertex* vertices[MAX_VERTICES];

int num_vertices;

} Graph;

void add_edge(Graph* graph, int src, int dest, int weight) {

Node* new_node = (Node*) malloc(sizeof(Node));

new_node->dest = dest;

new_node->weight = weight;

new_node->next = graph->vertices[src]->adj_list->head;

graph->vertices[src]->adj_list->head = new_node;

void initialize_graph(Graph* graph, int num_vertices) {

int i;

graph->num_vertices = num_vertices;

for (i = 0; i < num_vertices; i++) {

Vertex* vertex = (Vertex*) malloc(sizeof(Vertex));

vertex->parent = -1;

vertex->distance = INT_MAX;

vertex->visited = 0;

vertex->adj_list = (List*) malloc(sizeof(List));

vertex->adj_list->head = NULL;

graph->vertices[i] = vertex;

void dijkstra(Graph* graph, int start) {

int i;

36
graph->vertices[start]->distance = 0;

for (i = 0; i < graph->num_vertices - 1; i++) {

int min_distance = INT_MAX;

int current_vertex = -1;

int j;

for (j = 0; j < graph->num_vertices; j++) {

if (!graph->vertices[j]->visited && graph->vertices[j]->distance < min_distance) {

min_distance = graph->vertices[j]->distance;

current_vertex = j;

if (current_vertex == -1) {

break;

graph->vertices[current_vertex]->visited = 1;

Node* current_adj_list = graph->vertices[current_vertex]->adj_list->head;

while (current_adj_list != NULL) {

int neighbor = current_adj_list->dest;

if (!graph->vertices[neighbor]->visited) {

int tentative_distance = graph->vertices[current_vertex]->distance + current_adj_list->weight;

if (tentative_distance < graph->vertices[neighbor]->distance) {

graph->vertices[neighbor]->distance = tentative_distance;

graph->vertices[neighbor]->parent = current_vertex;

current_adj_list = current_adj_list->next;

37
}

int main() {

int num_vertices, num_edges, i;

Graph graph;

printf("Enter the number of vertices and edges in the graph: ");

scanf("%d%d", &num_vertices, &num_edges);

initialize_graph(&graph, num_vertices);

printf("Enter the edges in the format <source> <destination> <weight>:\n");

for (i = 0; i < num_edges; i++) {

int src, dest, weight;

scanf("%d%d%d", &src, &dest, &weight);

add_edge(&graph, src, dest, weight);

add_edge(&graph, dest, src, weight);

int start_vertex;

printf("Enter the starting vertex: ");

OUTPUT:

Enter the number of vertices and edges in the graph: 5 7

Enter the edges in the format <source> <destination> <weight>:

012

024

121

133

38
231

242

345

Enter the starting vertex: 0

Shortest distances from vertex 0:

Vertex Distance Parent

0 0 -1

1 2 0

2 3 1

3 4 2

4 5 2

39
VIVA QUESTIONS

DATA STRUCTURES WITH ALGORITHMS

1.What is a data structure?

A data structure is a way of organizing and storing data in a computer so that it can be
accessed and manipulated efficiently.

2. What is the difference between an array and a linked list?

An array is a data structure that stores a fixed-size sequential collection of elements of the
same type, whereas a linked list is a data structure that consists of a sequence of nodes, where
each node contains data and a reference (link) to the next node in the sequence.

3. What is a stack?

A stack is a linear data structure in which elements are added and removed from the same
end, known as the top of the stack. The last element added to the stack is the first one to be
removed, a process known as Last In, First Out (LIFO).

4. What is a queue?

A queue is a linear data structure in which elements are added at the rear end and removed
from the front end, known as the head of the queue. The first element added to the queue is
the first one to be removed, a process known as First In, First Out (FIFO).

5. What is a binary tree?

A binary tree is a tree data structure in which each node has at most two children, referred to
as the left child and the right child. The left child is typically smaller than the parent, while
the right child is typically larger.

6. What is a hash table?

A hash table is a data structure that maps keys to values using a hash function, which takes
the key as input and returns an index into an array of buckets. Each bucket contains a linked
list of key-value pairs that have the same hash value.

40
7. What is the time complexity of searching an element in a binary search tree?

The time complexity of searching an element in a binary search tree is O(log n), where n is
the number of nodes in the tree.

8. What is the difference between a tree and a graph?

A tree is a connected acyclic graph with a unique node called the root, whereas a graph is a
collection of vertices (nodes) and edges that connect them.

9.What is the time complexity of inserting an element into a heap?

The time complexity of inserting an element into a heap is O(log n), where n is the number
of elements in the heap.

10.What is a trie?

A trie is a tree data structure that stores a collection of strings or sequences, where each node
represents a prefix of a string and the edges represent the characters of the string.

11.What is a binary search?

A binary search is an algorithm for finding the position of a target value within a sorted array.
It works by repeatedly dividing the array in half and comparing the middle element to the
target value, until the value is found or the search space is exhausted.

12.What is a heap?

A heap is a data structure that represents a nearly complete binary tree, where each node is
greater than or equal to (or less than or equal to) its children. It can be used to implement
priority queues.

13.What is a priority queue?

A priority queue is a data structure that allows elements to be inserted and removed in
arbitrary order, but always returns the element with the highest (or lowest) priority first.

14. What are the three types tree traversals?

Inorder , Preorder and Post order

41

You might also like