0% found this document useful (0 votes)
2 views61 pages

Data Sturcture and Algorithm Lab Manual

The document outlines a laboratory exercise on data structures and algorithms, detailing various implementations such as stacks, queues, lists, trees, and graphs using C programming. It includes specific exercises, algorithms, and sample programs for each data structure, demonstrating operations like insertion, deletion, and traversal. The document serves as a comprehensive guide for students to understand and implement fundamental data structures.

Uploaded by

prakashnaga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views61 pages

Data Sturcture and Algorithm Lab Manual

The document outlines a laboratory exercise on data structures and algorithms, detailing various implementations such as stacks, queues, lists, trees, and graphs using C programming. It includes specific exercises, algorithms, and sample programs for each data structure, demonstrating operations like insertion, deletion, and traversal. The document serves as a comprehensive guide for students to understand and implement fundamental data structures.

Uploaded by

prakashnaga
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

DATA STRUCTURES AND ALGORITHM LABORATORY

LIST OF EXERCISES

1. Array implementation of Stack and Queue ADTs


2. Array implementation of List ADT
3. Linked list implementation of List, Stack, and Queue ADTs
4. Applications of List, Stack, and Queue ADTs
5. To create a tree and implement traversal techniques(In-order, Preorder, Postorder)
6. To create a Graph and implement traversal techniques(BFS & DFS)
7. To implement Bubble, Selection, and Insertion sort.
8. To implement a Recursive Binary Search Tree

1
INDEX

Ex.No. Date Title Marks Staff Sign.

1a Stack-Array Implementation

1b Queue-Array Implementation

2 List-Array Implementation

3a List-Linked List Implementation

3b Stack-Linked List Implementation

3c Queue-Linked List Implementation

4a Polynomial Addition

4b Infix to Postfix Conversion

4c Evaluation Postfix Expression

5 Binary Tree

6 Linear & Binary Search

7a Bubble sort

7b Selection sort

7c Insertion sort

8 Recursive Binary Search Tree

2
Ex.No.-1a STACK – ARRAY IMPLEMENTATION

AIM:
To write a C program to implement the stack using arrays.

ALGORITHM:
(i) Push Operation:
o To push an element into the stack, check whether the top of the stack is
greater than or equal to the maximum size of the stack.
o If so, then return stack is full and element cannot be pushed into the stack.
o Else, increment the top by one and push the new element in the new position
of top.
(ii) Pop Operation:
o To pop an element from the stack, check whether the top of the stack is
equal to -1.
o If so, then return stack is empty and element cannot be popped from
the stack. o Else, decrement the top by one.

PROGRAM:

/*Stack Implementation using arrays*/

# include <stdio.h>
# include <conio.h>
# include
<stdlib.h> # define
size 5 struct stack
{
int s[size];
int top;
}st;

int stfull()
{
if(st.top>=size-1)
return 1;
else return 0;
}

void push(int item)


{
st.top++;
st.s[st.top] =item;
}
int stempty( )

3
{
if(st.top==-1)
return 1;
else return 0;
}

int pop()
{
int item;
item=st.s[st.top];
st.top--;
return(item);
}

void display()
{
int i;
if(stempty())
printf("Stack Is Empty!\n");
else
{
for(i=st.top;i>=0;i--)
printf("\n%d",st.s[i]);
}
}
void main(void)
{
int item,ch;
char ans;
st.top = -1;
clrscr();
printf("<-----Stack using Array- - - ->\n");
while(1)
{
printf("\n1.Push\n2.Pop\n3.Display\n4.exit\n");
printf("Enter Your Choice:\n");
scanf("%d",&ch); switch(ch)
{
case 1:
printf("Enter The item to be pushed:\n");
scanf("%d",&item);
if(stfull())
printf("Stack is Full!\n");
else
push(item);
break;

4
case 2:
if(stempty())
printf("Empty stack!\n");
else
{
item=pop();
printf("The popped element is %d\n",item);
}
break;
case 3:
display();
break;
case 4:
exit(0);
}
}
getch();
}

OUTPUT:

<-----Stack using Array- - - ->

1.Push
2.Pop
3.Display
4.exit
Enter Your Choice:
1
Enter The item to be pushed: 10

1.Push
2.Pop
3.Display
4.exit
Enter Your Choice:
1
Enter The item to be pushed: 20

1.Push
2.Pop
3.Display
4.exit
Enter Your Choice: 3

20
5
10

1.Push
2.Pop
3.Display
4.exit
Enter Your Choice: 2
The popped element is
20

1. Push
2.Pop
3.Display
4.exit
Enter Your Choice: 4

RESULT:
Thus a C program to implement the stack using arrays is written and executed
successfully.

6
Ex.No.-1b QUEUE – ARRAY IMPLEMENTATION

AIM:
To write a C program to implement the queue using arrays.

ALGORITHM:
Enqueue:

1. Check if queue is not full.


2. If it is full then return queue overflow and item cannot be inserted.
3. If not, check if rear value is -1, if so then increment rear and by 1; if not increment
front by 1.
4. Store the item in the new value of front.

Dequeue:

1. Check if queue is not empty.


2. If it is empty, return queue underflow and dequeue operation cannot be done.
3. If queue is not empty , check if rear and front are equal.
 If so assign -1 to front and rear.
 If not decrement front by 1.

PROGRAM:

/*Queue using Array*/


# include <stdio.h>
# include <conio.h>
# define MAX 10
int queue[MAX],front = -1,rear = -1;

void insert_element( );
void delete_element(
); void display_queue(
);

int main( )
{
int option;
printf(">>> c program to implement queue operations
<<<"); do
{
printf("\n\n 1.Enqueue an element");
printf("\n 2.Dequeue an element");
printf("\n 3.Display queue");
7
printf("\n 4.Exit");

8
printf("\n Enter your choice: ");
scanf("%d",&option);
switch(option)
{
case 1:
insert_element();
break;
case 2:
delete_element();
break;
case 3:
display_queue();
break;
case 4:
return 0;
}
}while(option!=4);
}

void insert_element( )
{
int num;
printf("\n Enter the number to be Enqueued: ");
scanf("%d",&num);
if(front==0 && rear==MAX-1)
printf("\n Queue OverFlow Occured");
else if(front==-1&&rear==-1)
{
front=rear=0;
queue[rear]=num;
}
else if(rear==MAX-1 && front!=0)
{
rear=0;
queue[rear]=num;
}
else
{
rear++;
queue[rear]=num;
}
}

void delete_element( )
{
int element;
if(front==-1)

9
{
printf("\n Underflow");
}
element=queue[front];
if(front==rear)
front=rear=-1;
else
{
if(front==MAX-1)
front=0;
else front++;
printf("\n The dequeued element is: %d",element);
}

void display_queue( )
{
int i;
if(front==-1)
printf("\n No elements to display");
else
{
printf("\n The queue elements are:\n ");
for(i=front;i<=rear;i++)
{
printf("\t %d",queue[i]);
}
}
}

OUTPUT:

>>> c program to implement queue operations

<<< 1.Enqueue an element


2. Dequeue an element
3. Display queue
4.Exit
Enter your choice: 1

Enter the number to be Enqueued: 10

1.Enqueue an element
2.Dequeue an element

10
3.Display queue
4.Exit
Enter your choice: 1

Enter the number to be Enqueued: 20


1.Enqueue an element
2.Dequeue an element
3.Display queue
4.Exit
Enter your choice: 3

The queue elements are: 10 20

1.Enqueue an element
2.Dequeue an element
3.Display queue
4.Exit
Enter your choice: 2

The dequeued element is: 10

1. Enqueue an element
2.Dequeue an
element 3.Display
queue 4.Exit
Enter your choice: 4

RESULT:
Thus a C program to implement the queue using arrays is written and executed
successfully.

11
Ex.No.-2 LIST – ARRAY IMPLEMENTATION

AIM:
To write a C program to implement the List using arrays.

ALGORITHM:

1. Start the program.


2. Read the number of elements in the list and create the list.
3. Read the position and element to be inserted.
4. Adjust the position and insert the element.
5. Read the position and element to be deleted.
6. Remove the element from the list and adjust the position.
7. Read the element to be searched.
8. Compare the elements in the list with searching element.
9. If element is found, display it else display element is not found.
10. Display all the elements in the list.
11. Stop the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define MAX 10

void create( );
void insert( );
void deletion( );
void search( );
void display ();
int a,b[20], n, p, e, f, i, pos;

void main( )
{
int ch;
char g='y';
do
{

12
printf("\n Main Menu");
printf("\n 1.Create \n 2.Delete \n 3.Search \n 4.Insert \n 5.Display\n 6.Exit \n");
printf("\n Enter your Choice:");
scanf("%d", &ch);
switch(ch)
{
case 1:
create();
break;
case 2:
deletion();
break;
case 3:
search();
break;
case 4:
insert();
break;
case 5:
display();
break;
case 6:
exit();
break;

default:
printf("\n Enter the correct choice:");
}
printf("\n Do u want to continue:");
scanf("\n%c", &g);
}
while(g=='y'||g=='Y');
getch();
}

void create( )
{
printf("\n Enter the number of nodes:");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n Enter the Element:",i+1);
scanf("%d", &b[i]);
}

}
13
void deletion( )
{
printf("\n Enter the position u want to
delete:"); scanf("%d", &pos);
if(pos>=n)
{
printf("\n Invalid Location:");
}
else
{
for(i=pos+1;i<n;i++)
{
b[i-1]=b[i];
}
n--;
}
printf("\n The Elements after deletion:");
for(i=0;i<n;i++)
{
printf("\t%d", b[i]);
}
}

void search()
{
printf("\n Enter the Element to be searched:");
scanf("%d", &e);

for(i=0;i<n;i++)
{
if(b[i]==e)
{
printf("Value is in the %d Position", i);
}
else
{
printf("Value %d is not in the list:", e);
continue;
}
}
}

void insert()
{
14
printf("\n Enter the position u need to insert:");
scanf("%d", &pos);

if(pos>=n)
{
printf("\n invalid Location:");
}
else
{
for(i=MAX-1;i>=pos-1;i--)
{
b[i+1]=b[i];
}
printf("\n Enter the element to insert:");
scanf("%d",&p);
b[pos]=p;
n++;
}
printf("\n The list after insertion:");

display();
}

void display()
{
printf("\n The Elements of The list ADT
are:"); for(i=0;i<n;i++)
{
printf("\n\n%d", b[i]);
}
}

OUTPUT:

Main Menu
1.Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
Enter your Choice:1

Enter the number of nodes:4


Enter the Element: 11
Enter the Element: 22
15
Enter the Element: 33
Enter the Element: 44

Do u want to continue:y

Main Menu
1.Create
2.De ete
3.Search
4.Ins rt
5.Display
6.Exi
Enter your Choice:2
Enter the position u want to delete:2
Elements after deletion: 11 33 44

Do u want to continue:y
Main Menu
1.Create
2.De ete
3.Search
4.Ins rt
5.Display
6.Exi
Enter your Choice:3

Enter the Element to be searched:44


Value is in the 3 Position

Do u want to continue:y

Main Menu
1.Create
2.De ete
3.Search
4.Insert
5.Display
6.Exi
Enter your Choice:4
Enter the position u need to insert:2
Enter the element to insert:25
The l st after insertion: 11 25 33 44

16
Do u want to continue:y

Main Menu
1. Create
2. Delete
3.Search
4.Insert
5.Display
6.Exit
Enter your Choice:5

The Elements of The list ADT are: 11 25 33 44

Do u want to continue:y

Main Menu
1. Create
2.Delete
3.Search
4.Insert
5.Display
6.Exit
Enter your Choice:6

RESULT:
Thus a C program to implement the List using array is written and executed
successfully.
17
Ex.No.-3a LIST – LINKED LIST IMPLEMENTATION

AIM:
To write a C program to implement the List ADT using linked list.

ALGORITHM:

1. Start the program.


2. Create a node using structure
3. Dynamically allocate memory to node
4. Create and add nodes to linked list.
5. Read the element to be inserted.
6. Insert the elements into the list.
7. Read the element to be deleted.
8. Remove that element and node from the list.
9. Adjust the pointers.
10. Display the elements in the list.
11. Stop the program.

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
/*declaring a structure to create a node*/
struct node
{
int data;
struct node *next;
};
struct node *start;
/* inserting nodes into the list*/
/*function to insert values from beginning of the the single
linked list*/ void insertbeg(void)
{
struct node *nn;
int a;
/*allocating implicit memory to the node*/
nn=(struct node *)malloc(sizeof(struct node));
18
printf("enter data:");
scanf("%d",&nn->data);
a=nn->data;
if(start==NULL)
/*checking if List is empty*/
{
nn->next=NULL;
start=nn;
}
else
{
nn->next=start;
start=nn;
}
printf("%d succ. inserted\n",a);
return;
}
/*function to insert values from the end of the linked list*/
void insertend(void)
{
struct node *nn,*lp;
int b;
nn=(struct node *)malloc(sizeof(struct node));
printf("enter data:");
scanf("%d",&nn->data);
b=nn->data;
if(start==NULL)
{
nn->next=NULL;
start=nn;
}
else
{
lp=start;
while(lp->next!=NULL)
{
lp=lp->next;
}
lp->next=nn;
nn->next=NULL;
}
printf("%d is succ. inserted\n",b);
return;
}
/*function to insert values from the middle of the linked list*/
void insertmid(void)
{
19
struct node *nn,*temp,*ptemp;
int x,v;
nn=(struct node *)malloc(sizeof(struct node));
if(start==NULL)
{
printf("sll is empty\n");
return;
}
printf("enter data before which no. is to be inserted:\n");
scanf("%d",&x);
if(x==start->data)
{
insertbeg();
return;
}
ptemp=start;
temp=start->next;
while(temp!=NULL&&temp->data!=x)
{
ptemp=temp;
temp=temp->next;
}
if(temp==NULL)
{
printf("%d data does not exist\n",x);
}
else
{
printf("enter data:");
scanf("%d",&nn->data);
v=nn->data;
ptemp->next=nn;
nn->next=temp;
printf("%d succ. inserted\n",v);
}
return;
}
void deletion(void)
{
struct node *pt,*t;
int x;
if(start==NULL)
{
printf("sll is empty\n");
return;
}
printf("enter data to be deleted:");
20
scanf("%d",&x);
if(x==start->data)
{
t=start;
/* assigning first node pointer to next node pointer to delete a
data from the starting of the node*/
start=start->next;
free(t);
printf("%d is succ. deleted\n",x);
return;
}
pt=start;
t=start->next;
while(t!=NULL&&t->data!=x)
{
pt=t;t=t->next;
}
if(t==NULL)
{
printf("%d does not exist\n",x);
return;
}
else
{
pt->next=t->next;
}
printf("%d is succ. deleted\n",x);
free(t);
return;
}
void display(void)
{
struct node *temp;
if(start==NULL)
{
printf("sll is empty\n");
return;
}
printf("elements are:\n");
temp=start; while(temp!
=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
return;
}
21
/* main program*/
int main( )
{
int c,a;
start=NULL;
do
{
printf("1:insert\n2:delete\n3:display\n4:exit\nenter choice:");
scanf("%d",&c);
switch(c)
{
case 1:
printf("1:insertbeg\n2:insert end\n3:insert mid\nenter choice:");
scanf("%d",&a);
switch(a)
{
case 1:insertbeg(); break;
case 2:insertend(); break;
case 3:insertmid(); break;
} break;
case 2:deletion(); break;
case 3:display(); break;
case 4:printf("program ends\n");break;
default:printf("wrong choice\n"); break;
}
}while(c!=4);
return 0;
}

22
OUTPUT:

RESULT:
Thus a C program to implement the List ADT using linked list is written and
executed successfully.

23
Ex.No.-3b STACK – LINKED LIST IMPLEMENTATION

AIM:
To write a C program to implement the stack using linked list.

ALGORITHM:
A) Push Operation:
1. To push an element into the stack, copy the element to be inserted in the data field
of the new node.
2. Assign the reference field of the new node as NULL.
3. Check if top is not NULL, if so, then assign the value of top in the reference field
of new node.
4. Assign the address of the new node to the top.

B) Pop Operation:
1. To pop an element from the stack, check whether the top of the stack is NULL.
2. If so, then return stack is empty and element cannot be popped from the stack.
3. Else, assign the top value to a temporary node.
4. Now assign the value in the reference field of the node pointed by top to the top value.
5. Return the value in the data field of the temporary node as the element
deleted and delete the temporary node.
PROGRAM:

/*Stack Implementation using Linked List*/

# include <stdio.h>
void push( );
void pop( );
void display( );
main( )
{
int n;
printf("STACK USING LINKED LIST\n1.PUSH\n 2.POP\n 3.DISPLAY\n 4.
EXIT \n");
do
{
printf("\nEnter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
push();
break;
24
case 2:
pop();
break;
case 3:
display( );
break;
case 4:
break;
default:
printf("Invalid choice\n");
break;
}
}while(n!=4);
}

typedef struct node


{
int data;
struct node *link;
}n;
n *top=NULL;

void push()
{
int item; n *temp;
printf("Enter the item\n");
scanf("%d",&item);
temp=(n*)malloc(sizeof(n));
temp->data=item;
temp->link=top;
top=temp;
}

void pop()
{
n *temp;
if(top==NULL)
printf("Stack is empty\n");
else
{
temp=top;
printf("The element deleted = %d\n",temp->data);
free(temp);
top=top->link;
}
}
void display()
25
{
n *save;
if(top==NULL)
printf("Stack is empty\n");
else
{
save=top;
printf("The elements of the stack are :");
while(save!=NULL)
{
printf("%d\t",save->data);
save=save->link;
}
printf("\nTopmost element = %d\n",top->data);
}
}

OUTPUT:

STACK USING LINKED LIST


1.PUSH
2. POP
3. DISPLAY
4. EXIT

Enter your choice


1 Enter the item 10

Enter your choice


1 Enter the item 20

Enter your choice 3


The elements of the stack are :20 10
Topmost element = 20

Enter your choice 2


The element deleted = 20

Enter your choice 4

RESULT:
Thus a C program to implement the stack using linked list is written and executed
successfully.
26
Ex.No.-3c QUEUE – LINKED LIST IMPLEMENTATION

AIM:
To write a C program to implement the queue using linked list.

ALGORITHM:
Enqueue:
1. Create a new node and allocate memory space for the new node.
2. Assign the element to be inserted in the data field of the new node.
3. Assign NULL to the address field of the new node.
4. Check if rear and front pointers are NULL.
5. If so, then make the front and rear pointers to point to new node.
6. If not, then assign address of the new node as the rear
pointer value. Dequeue:
1. Check if queue is not empty.
2. If it is empty, return queue underflow and dequeue operation cannot be done.
3. If not, assign the front->next value as the new front pointer and free the deleted node.

PROGRAM:

//Queue using linked list


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
}*rear, *front;

void dequeue()
{
struct node *temp, *var=rear;
if(var==rear)
{
rear = rear->next;
free(var);
}
else
27
printf("\nQueue Empty");
}

void enqueue(int value)


{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct
node)); temp->data=value;
if (front == NULL)
{
front=temp; front-
>next=NULL;
rear=front;
}
else
{
front->next=temp; front=temp;
front->next=NULL;
}
}

void display()
{
struct node *var=rear;
if(var!=NULL)
{
printf("\nElements in Queue: ");
while(var!=NULL)
{
printf("\t%d",var->data);
var=var->next;
}
printf("\n");
}
else
printf("\nQueue is Empty");
}

int main( )
{
int ch;
clrscr();
front=NULL;
printf("<-----Queue using Linked List----->\n");
printf(" \n1. Enqueue an element");
printf(" \n2. Dequeue an element");
28
printf(" \n3. Display Queue");
printf(" \n4. Exit\n");
while(1)
{
printf(" \nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
int value;
printf("\nEnter a value to Enqueue: ");
scanf("%d",&value);
enqueue(value);
display( );
break;
}
case 2:
{
dequeue( );
display( );
break;
}
case 3:
{
display( );
break;
}
case 4:
{
exit(0);
}
default:
{
printf("\nwrong choice for operation");
}
}
}
}

OUTPUT:

<-----Queue using Linked List----->

1. Enqueue an element
2. Dequeue an element
3. Display Queue
29
4. Exit
Enter your choice: 1

Enter a value to Enqueue: 10

Elements in Queue: 10

Enter your choice: 1

Enter a value to Enqueue: 20

Elements in Queue: 10 20

Enter your choice: 1

Enter a value to Enqueue: 30

Elements in Queue: 10 20 30

Enter your choice: 2

Elements in Queue: 20 30

Enter your choice: 4

RESULT:
Thus a C program to implement the queue using linked list is written and executed
successfully.
30
31
Ex.No.-4a POLYNOMIAL ADDITION

AIM:
To write a C program to perform polynomial addition using linked list.

ALGORITHM:

1. Start the program.


2. Declare the node as link.
3. Allocate memory space for pol1, pol2 and poly.
4. Read pol1 and pol2.
5. Call the function polyadd.
6. Add the co-efficients of poly1 and poly2 having the equal power and store it in poly.
7. If there is no co-efficient having equal power in poly1 and poly2, then add it to poly.
8. Display the poly1, poly2 and poly.
9. Stop the program.

PROGRAM:

# include <stdio.h>
# include <malloc.h>
# include <conio.h>

struct link
{
int coeff,pow;
struct link *next;
}*poly1=NULL, *poly2=NULL,*poly=NULL;

void create(struct link *node)


{
char ch;
do
{
printf(“\n Enter Coeff:”);
scanf(“%d”,&node->coeff);
printf(“\n Enter Power:”);
scanf(“%d”,&node->pow);
node->next=(struct link *) malloc(sizeof(struct link));
node=node->next;
node->next=NULL;
31
printf(“\n\n Continue(y/n):”);
ch=getch();
}while(ch==‟y‟ || ch ==‟Y‟);
}

void display(struct link *node)


{
while(node->next!=NULL)
{
printf(“%dx^%d”,node->coeff,node->pow);
node=node->next;
if(node->next!=NULL)
printf(“+”);
}
}

void polyadd(struct link *poly1, struct link *poly2, struct link *poly)
{
while(poly1->next && poly2->next)
{
if(poly1->pow > poly2->pow)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
else if(poly1->pow < poly2->pow)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly2=poly2->next;
}
else
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff + poly2->coeff;
poly1=poly1->next;
poly2=poly2->next;

}
poly->next=(struct link *) malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
while(poly1->next || poly2->next)
{
if(poly1->next)

32
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
if(poly2->next)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
poly->next=(struct link *) malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
}
void main(
)
{ poly1=(struct link *)malloc(sizeof(struct link));
poly2=(struct link *)malloc(sizeof(struct link));
poly=(struct link *)malloc(sizeof(struct link));
clrscr();
printf(“\n Enter the First Polynomial:”);
create(poly1);
printf(“\n Enter the Second Polynomial:”);
create(poly2);
polyadd(poly1,poly2,poly);
printf(“\n\t First Polynomial:”);
display(poly1);
printf(“\n\t Second Polynomial:”);
display(poly2);
printf(“\n\t Addition of two Polynomials:”);
display(poly);
getch();

OUTPUT:
Enter the First Polynomial:
Enter Coeff:3
Enter Power:3
Continue(y/n):y

Enter Coeff:6
Enter Power:2
Continue(y/n):y

33
Enter Coeff:9

34
Enter Power:1
Continue(y/n):y

Enter Coeff:8
Enter Power:0
Continue(y/n):n

Enter the Second Polynomial:


Enter Coeff:76
Enter Power:3
Continue(y/n):y

Enter Coeff:43
Enter Power:2
Continue(y/n):y

Enter Coeff:23
Enter Power:1
Continue(y/n):y

Enter Coeff:24
Enter Power:0
Continue(y/n):n

First Polynomial: 3x^3+6x^2+9x^1+8x^0


Second Polynomial: 76^3+43x^2+23x^1+24x^0
Addition of two Polynomials: 79^3+49x^2+32x^1+32x^0

RESULT:
Thus a C program to perform polynomial addition using linked list is written and
executed successfully.
35
Ex.No.-4b INFIX TO POSTFIX CONVERSION

AIM:
To write a C program to perform infix to postfix conversion using stack.

ALGORITHM:

1. Define a stack
2. Go through each character in the string
3. If it is between 0 to 9, append it to output string.
4. If it is left brace push to stack
5. If it is operator *+-/ then
a. If the stack is empty push it to the stack
b. If the stack is not empty then start a loop:
i. If the top of the stack has higher precedence
ii. Then pop and append to output string
iii. Else break
iv. Push to the stack
6. If it is right brace then
a. While stack not empty and top not equal to left brace
b. Pop from stack and append to output string
c. Finally pop out the left brace.
7. If there is any input in the stack pop and append to the output string.

PROGRAM:

/*Stack application - Infix to Postfix Conversion*/

# define SIZE 50
# include <ctype.h>

char s[SIZE];
int top = -1;
push(char elem)
{
s[++top] = elem;
35
}

char pop()
{
return (s[top--]);
}

int pr(char elem)


{
switch (elem)
{
case '#':
return 0;
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
}
}

main(
)
{ char infx[50], pofx[50], ch, elem;
int i = 0, k = 0;
printf("<-----Stack Application: Infix to Postfix Conversion-----
>\n"); printf("\n\nRead the Infix Expression ?
"); scanf("%s", infx);
push('#');
while ((ch = infx[i++]) != '\0')
{
if (ch == '(')
push(ch);
else if
(isalnum(ch))
pofx[k++] = ch;
else if (ch == ' )' )
{
while (s[top] != ' ( ' )
pofx[k++] = pop( );
elem = pop( );
}
else
{
36
while (pr(s[top]) >= pr(ch))

37
pofx[k++] = pop( );
push(ch);
}
}
while (s[top] != '#')
pofx[k++] = pop( );
pofx[k] = '\0';
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n", infx, pofx);
}

OUTPUT:

<-----Stack Application: Infix to Postfix Conversion----->

Read the Infix Expression ? a+b*c-d

Given Infix Expn: a+b*c-d Postfix Expn: abc*+d-

RESULT:
Thus a C program to convert the expression in infix to postfix is written and executed
successfully.

38
Ex.No.-4c EVALUATING POSTFIX EXPRESSION

AIM:
To write a C program to evaluate postfix expression using stack.

ALGORITHM:
1. Start the program.
2. Scan the Postfix string from left to right.
3. Initialise an empty stack.
4. If the scannned character is an operand, add it to the stack. If the scanned character
is an operator, there will be atleast two operands in the stack.
5. If the scanned character is an Operator, then we store the top most element of the
stack(topStack) in a variable temp. Pop the stack. Now evaluate
topStack(Operator)temp. Pop the stack and Push result into the stack.
6. Repeat this step till all the characters are scanned.
7. After all characters are scanned, we will have only one element in the stack. Return
topStack.
8. Stop the program.

PROGRAM:
# define SIZE 50
# include <ctype.h>

int s[SIZE];
int top=-1;

push(int elem)
{
s[++top]=elem;
}

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

main( )
{
39
char pofx[50],ch;
int i=0,op1,op2;
printf("<-----Stack Application: Evaluating Postfix Expression----->\n");
printf("\n\nRead the Postfix Expression ?
"); scanf("%s",pofx);
while( (ch=pofx[i++]) != '\0')
{
if(isdigit(ch))
push(ch-'0');
else
{
op2=pop( );
op1=pop( );
switch(ch)
{
case '+':
push(op1+op2);
break;
case '-':
push(op1-op2);
break;
case '*':
push(op1*op2);
break;
case '/':
push(op1/op2);
break;
}
}
}
printf("\n Given Postfix Expn: %s\n",pofx);
printf("\n Result after Evaluation: %d\n",s[top]);
}

OUTPUT:

<-----Stack Application: Evaluating Postfix Expression- - - ->

Read the Postfix Expression ? 456*+7-

Given Postfix Expn: 456*+7-

Result after Evaluation: 27

RESULT:
Thus a C program to evaluate the postfix expression is written and executed
successfully.
40
Ex.No.-5 BINARY TREE

AIM:
To write a C program to implement binary tree and its traversals.

ALGORITHM:
1. Start the program.
2. Declare the node.
3. Create the binary tree by inserting elements into it.
4. Traverse the binary tree by inorder and display the nodes.
5. Traverse the binary tree by preorder and display the nodes.
6. Traverse the binary tree by postorder and display the nodes.
7. Stop the program.

PROGRAM:
# include <stdio.h>
# include <alloc.h>
# include
<conio.h>

typedef struct bin


{
int data;
struct bin *left;
struct bin *right;
}node;

void insert(node *,node *);


void inorder(node *);
void preorder(node *);
void postorder(node *);
node *getnode();

void main( )
{
int choice;
char ans='n';
node *newnode,*root;
root=NULL;
clrscr ( ) ;
do
40
{
printf("\n\t Program for Binary Tree
Travesal"); printf("\n\t 1.Create");
printf("\n\t 2.Inorder");
printf("\n\t 3.Preorder");
printf("\n\t 4.Postorder");
printf("\n\t 5.Exit");
printf("\n\t Enter your Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
root=NULL;
do
{
newnode=getnode(); printf("\n\
tEnter the element:");
scanf("%d",&newnode->data);
if(root==NULL)
root=newnode;
else
insert(root,newnode);
printf("\n\tDo u want to enter more elements?(y/n):
"); ans=getche();
}while(ans=='y' || ans=='Y');
clrscr();
break;

case 2:
if(root==NULL)
printf("\n\t Tree is not created.");
else
inorder(root);
break;
case 3:
if(root==NULL)
printf("\n\t Tree is not created.");
else
preorder(root);
break;
case 4:
if(root==NULL)
printf("\n\t Tree is not created.");
else
postorder(root);
break;

41
}
}while(choice!=5);
}

node *getnode()
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->left=NULL;
temp->right=NULL;
return temp;
}

void insert(node *root, node *newnode)


{
char ch;
printf("\n\t Where to insert LEFT/RIGHT of %d: ",root->data);
ch=getche();
if((ch=='r')||(ch=='R'))
{
if(root->right==NULL)
{
root->right=newnode;
}
else
insert(root->right,newnode);;
}
else
{

if(root->left==NULL)
{
root->left=newnode;
}
else
insert(root->left,newnode);
}
}

void inorder(node *temp)


{
if(temp!=NULL)
{
42
inorder(temp->left);
printf(" %d",temp->data);
inorder(temp->right);
}

43
}

void preorder(node *temp)


{
if(temp!=NULL)
{
printf(" %d",temp->data);
preorder(temp->left);
preorder(temp->right);
}
}

void postorder(node *temp)


{
if(temp!=NULL)
{
postorder(temp->left);
postorder(temp->right);
printf(" %d",temp->data);

}
}

OUTPUT:

Program for Binary Tree Travesal


1.Create
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your Choice:1
Enter the element:10
Do u want to enter more elements?(y/n):y

Enter the element:12


Where to insert LEFT/RIGHT of 10: l
Do u want to enter more
elements?(y/n):y

Enter the element:17


Where to insert LEFT/RIGHT of 10: r
Do u want to enter more
elements?(y/n):y

Enter the element:8


44
Where to insert LEFT/RIGHT of 10: l
Where to insert LEFT/RIGHT of 12: r

45
Do u want to enter more elements?(y/n):n

Program for Binary Tree Travesal


1.Create
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your Choice:2
12 8 10 17

Program for Binary Tree Travesal


1.Create
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your Choice:3
10 12 8 17

Program for Binary Tree Travesal


1.Create
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter your Choice:4
8 12 17 10

Program for Binary Tree Travesal


1.Create
2. Inorder
3.Preorder
4.Postorder
5.Exit
Enter your Choice:5

RESULT:
Thus a C program to implement the tree and tree traversals is written and executed
successfully.

46
Ex.No.-6 GRAPH TRAVERSAL

AIM:
To write a C program to implement graph traversals by Breadth First Search and
Depth First Search.

ALGORITHM:
Breadth First Search:
1. Start the program.
2. Read the number of vertices and adjacency matrix.
3. Read the vertex from which to traverse the graph.
4. Initialize the visited array to 1 and insert the visited vertex in the queue.
5. Visit the vertex which is at the front of the queue.
6. Delete it from the queue and place its adjacent nodes in the queue.
7. Repeat the steps 5 & 6 , till the queue is not empty.
8. Display the traversal path.
9. Stop the program.
Depth First Search:
1. Start the program.
2. Read the number of vertices and adjacency matrix.
3. Initialize the visited array to 1.
4. Traverse the path one by one and push the visited vertex in the stack.
5. When there is no vertex further, we traverse back and search for unvisited vertex.
6. Display the traversal path.
7. Stop the program.

a) Breadth First

Search PROGRAM:

#include<stdio.h>
int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1;
void bfs(int v) {
62
for(i = 1; i <= n; i++)
if(a[v][i] && !
visited[i]) q[++r] = i;
if(f <= r) {
visited[q[f]] = 1;
bfs(q[f++]);
}
}
void main() {
int v;
printf("\n Enter the number of vertices:");
scanf("%d", &n);

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


{ q[i] = 0;
visited[i] = 0;
}

printf("\n Enter graph data in matrix form:\n");


for(i=1; i<=n; i++) {
for(j=1;j<=n;j++) {
scanf("%d", &a[i][j]);
}
}

printf("\n Enter the starting vertex:");


scanf("%d", &v);
bfs(v);
printf("\n The nodes which are reachable are:\n");

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


if(visited[i])
printf("%d\t", i);
else {
printf("\n Bfs is not possible. Not all nodes
reachable");
are break;
}
}
}

63
OUTPUT:
Enter the number of vertices : 4

Enter graph data in matrix

form:

1 1 1 1

0 1 0 0

0 0 1 0

0 0 0 1

Enter the starting vertex: 1

The nodes which are reachable are:

1 2 3 4

b) Depth First Search


PROGRAM:

#include<stdio.h>

void DFS(int);
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]);

//visited is initialized to zero


for(i=0;i<n;i++)
visited[i]=0;

DFS(0);
}
64
void DFS(int i)

65
{
int j; printf("\n
%d",i);
visited[i]=1;

for(j=0;j<n;j++) if(!
visited[j]&&G[i][j]==1)
DFS(j);
}

OUTPUT:
Enter number of vertices : 8
Enter adjacency matrix of the graph :
0 1 1 1 1 0 0 0
1 0 0 0 0 1 0 0
1 0 0 0 0 1 0 0
1 0 0 0 0 0 1 0
1 0 0 0 0 0 1 0
0 1 1 0 0 0 0 1
0 0 0 1 1 0 0 1
0 0 0 0 0 1 1 0
0
1
5
2
7
6
3
4

RESULT:
Thus a C program to implement graph traversals by Breadth First Search and
Depth First Search is written and executed successfully.

66
Ex.No.-7 SORTING

AIM:
To write a C program to perform insertion sort, selection sort, and bubble sort.

ALGORITHM:
Insertion Sort
1. Get the n elements to be sorted.
2. The ith element is compared from (i-1)th to 0th element and placed in proper
position according to ascending value.
3. Repeat the above step until the last
element.
Selection sort:

1. Begin with the first element of the array (or list).


2. Search the unsorted portion of the array to find the smallest element.
3. Swap this smallest element with the first element of the unsorted portion of the array. The first element
is now sorted.

4. Move the starting position of the unsorted portion of the array one step to the right.
5. Repeat steps 2 through 4 for the remainder of the unsorted portion of the array.
6. Continue this process until the entire array is sorted.

Bubble Sort
1. Get the n elements to be sorted.
2. Compare the first two elements of the array and swap if necessary.
3. Then, again second and third elements are compared and swapped if it is necessary
and continue this process until last and second last element is compared and swapped.
4. Repeat the above two steps n-1 times and print the result.
PROGRAM:

72
SELECTION SORT:
#include <stdio.h>

void selectionSort(int arr[], int n) {


int i, j, minIdx, temp;
for (i = 0; i < n - 1; i++) {
minIdx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
// Swap the found minimum element with the first element
temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
}

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

73
INSERTION SORT:

#include <stdio.h>

void insertionSort(int arr[], int n) {


int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
// Move elements of arr[0..i-1], that are greater than key,
// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

BUBBLE SORT:

#include <stdio.h>

void bubbleSort(int arr[], int n) {


int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap the elements
74
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

RESULT:
Thus a C program to perform insertion sort, selection sort, and bubble sort is written
and executed successfully.
75
Ex.No.-8 RECURSIVE BINARY SEARCH TREE

AIM:
To write a C program to implement Recursive Binary Search Tree.

ALGORITHM:
1. Start the program.
2. Declare the node.
3. Read the elements to be inserted.
4. Create the binary search tree.
5. Read the element to be searched.
6. Visit the nodes by inorder.
7. Find the searching node and display if it is present with parent node.
8. Read the element to be removed from BST.
9. Delete that node from BST.
10. Display the binary search tree by inorder.
11. Stop the program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a tree node
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;

// Function to create a new tree node


TreeNode* createNode(int data) {
TreeNode *newNode = (TreeNode*)malloc(sizeof(TreeNode));
if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL; 76
return newNode;
}
// Function to insert a node into the binary search tree recursively
TreeNode* insertNode(TreeNode *root, int data) {
if (root == NULL) {
return createNode(data);
}

if (data < root->data) {


root->left = insertNode(root->left, data);
} else if (data > root->data) {
root->right = insertNode(root->right, data);
}
// If data is equal, do nothing (no duplicates in this example)

return root;
}

// Function to search for a value in the binary search tree recursively


TreeNode* searchNode(TreeNode *root, int data) {
if (root == NULL || root->data == data) {
return root;
}

if (data < root->data) {


return searchNode(root->left, data);
} else {
return searchNode(root->right, data);
}
}

// Function to perform an in-order traversal of the tree


void inOrderTraversal(TreeNode *root) {
if (root != NULL) {
inOrderTraversal(root->left);
printf("%d ", root->data);
inOrderTraversal(root->right);
}
}
// Function to free the tree nodes recursively
void freeTree(TreeNode *root) {
if (root != NULL) {
77
freeTree(root->left);
freeTree(root->right);
free(root);
}
}

// Main function to demonstrate the usage


int main() {
TreeNode *root = NULL;

// Insert nodes into the binary search tree


root = insertNode(root, 50);
insertNode(root, 30);
insertNode(root, 20);
insertNode(root, 40);
insertNode(root, 70);
insertNode(root, 60);
insertNode(root, 80);

// Perform in-order traversal


printf("In-order traversal: ");
inOrderTraversal(root);
printf("\n");

// Search for a value in the tree


int searchValue = 40;
TreeNode *result = searchNode(root, searchValue);
if (result != NULL) {
printf("Value %d found in the tree.\n", searchValue);
} else {
printf("Value %d not found in the tree.\n", searchValue);
}

// Free the allocated memory


freeTree(root);

return 0;
}

78
RESULT:
Thus a C program to implement recursive binary search tree is written and executed
successfully.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy