Professional Documents
Culture Documents
DS Record
DS Record
Date:
AIM
To write a C program to implement stack ADT using array
ALGORITHM
Step 1: Start the program.
Step 2: For Push operation, check for stack overflow
Step 3: If Top>=N then print stack overflow else increment Top and insert the
element.
Step 4: For Pop operation, check for underflow of the stack.
Step 5: If Top=0 then print stack underflow else decrement Top and delete the
element
Step 6: Stop the program.
1
PROGRAM
#include<stdio.h>
#define SIZE 5
int top = -1;
int stack[SIZE];
void push()
{
int item;
if(top == (SIZE-1))
printf("\nStack Overflow\n");
else
{
printf("\nEnter the item to be pushed in stack : ");
scanf("%d",&item);
top = top+1;
stack[top] = item;
}
}/*End of push()*/
void pop()
{
if(top == -1)
printf("\nStack Underflow\n");
else
{
printf("\nPopped element is : %d\n", stack[top]);
top = top-1;
}
}/*End of pop()*/
void display()
{
int i;
if(top == -1)
printf("\nStack is empty\n");
else
{
printf("\nStack elements :");
for(i = top; i >=0; i--)
printf(" %d", stack[i]);
printf("\n");
}
2
}/*End of display()*/
int main()
{
int choice;
while(1)
{
printf("\n1.Push\n");
printf("2.Pop\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
(1);
default:
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
return 0;
}/*End of main()*/
3
OUTPUT
1.Push
2.Pop
3.Display
4.Quit
Enter your choice : 1
Enter the item to be pushed in stack : 1
1.Push
2.Pop
3.Display
4.Quit
Enter your choice : 1
Enter the item to be pushed in stack : 2
1.Push
2.Pop
3.Display
4.Quit
Enter your choice : 1
Enter the item to be pushed in stack : 3
1.Push
2.Pop
3.Display
4.Quit
Enter your choice : 3
Stack elements : 3 2 1
1.Push
2.Pop
3.Display
4.Quit
Enter your choice : 2
Popped element is : 3
1.Push
2.Pop
3.Display
4.Quit
Enter your choice : 3
Stack elements : 2 1
1.Push
2.Pop
3.Display
4.Quit
4
RESULT
Thus the C program to implement stack ADT using array has been
implemented successfully.
5
Ex No: 1B
ARRAY IMPLEMENTATION OF QUEUE ADTS
Date:
AIM
ALGORITHM
6
PROGRAM
# include<stdio.h>
# define SIZE 5
int queue[SIZE];
int rear = -1;
int front = -1;
void enqueue()
{
int item;
if (rear == SIZE - 1)
printf("\nQueue Overflow\n");
else
{
if (front == -1) /*If queue is initially empty */
front = 0;
printf("\nEnter the element for adding in queue : ");
scanf("%d", &item);
rear = rear + 1;
queue[rear] = item ;
}
}/*End of insert()*/
void dequeue()
{
int i;
if (front == -1 || front > rear)
{
printf("\nQueue Underflow\n");
return ;
}
else
{
printf("\nElement deleted from queue is : %d\n", queue[front]);
if (rear > front)
{
for (i = front; i < rear; i++)
queue[i] = queue[i + 1];
rear = rear - 1;
}
else
{
front = -1;
7
rear = 1;
}
}
}/*End of del() */
void display()
{
int i;
if (front == -1)
printf("\nQueue is empty\n");
else
{
printf("\nQueue is :");
for(i = front; i <= rear; i++)
printf(" %d ",queue[i]);
printf("\n");
}
}/*End of display() */
int main()
{
int choice;
while(1)
{
printf("\n1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
enqueue();
break;
case 2 :
dequeue();
break;
case 3:
display();
break;
8
case 4:
exit(1);
default:
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
}/*End of main()*/
9
OUTPUT
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 1
Enter the element for adding in queue : 100
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 1
Enter the element for adding in queue : 200
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 1
Enter the element for adding in queue : 300
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 3
Queue is : 100 200 300
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 2
Element deleted from queue is : 100
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 3
Queue is : 200 300
1. Enqueue
2. Dequeue
3. Display
4. Quit
10
RESULT:
Thus the C program to implement Queue ADT using array has been
implemented successfully.
11
Ex No: 2
AIM:
ALGORITHM:
Step 1: Start.
Step 2: Declare the necessary functions for implementation.
Step 3: Get the input from the user and store it an array.
Step 4: In Insertion, half of the elements to be shifted upwards and in deletion half
of the
elements to be shifted downwards.
Step 5: Display the output using an array.
Step 6: Stop.
12
PROGRAM
# include<stdio.h>
# define MAX 10
int arr[MAX];
int n; /*Total number of elements in the list */
void input()
{
int i;
for(i = 0; i < n ; i++)
{
printf("Input value for element %d : ", i+1);
scanf("%d", &arr[i]);
}
}/*End of input()*/
int search(int item)
{
int i;
for(i = 0; i < n; i++)
{
if(item == arr[i])
return(i+1);
}
return(0); /* If element not found */
}/*End of search()*/
void insert()
{
int temp, item, position;
if(n == MAX)
{
printf("\nList overflow\n");
return;
}
printf("\nEnter position for insertion : ");
scanf("%d", &position);
printf("Enter the value : ");
scanf("%d", &item);
if (position > n+1)
{
printf("\nEnter position less than or equal to %d\n",n+1);
return;
}
13
if (position == n+1) /*Insertion at the end */
{
arr[n] = item;
n = n+1;
return;
}
/* Insertion in between */
temp = n - 1;
while (temp >= position-1)
{
arr[temp+1] = arr[temp]; /* shifting right */
temp--;
}
arr[position-1] = item;
n = n +1 ;
}/*End of insert()*/
void del()
{
int temp, position, item;
if(n == 0)
{
printf("\nList underflow\n");
return;
}
printf("\nEnter the element to be deleted : ");
scanf("%d",&item);
if(item == arr[n-1]) /*Deletion at the end*/
{
n = n - 1;
return;
}
position = search(item);
if(position == 0)
{
printf("\nElement not present in array\n");
return;
}
/*Deletion in between */
temp = position-1;
while (temp <= n-1)
{
arr[temp] = arr[temp+1]; /* Shifting left */
14
temp++;
}
n=n-1;
}/*End of del()*/
void display()
{
int i;
if(n == 0)
{
printf("\nList is empty\n");
return;
}
for(i = 0; i< n; i++)
printf("\nValue at position %2d : %d", i+1, arr[i]);
printf("\n");
}/*End of display()*/
int main()
{
int choice, item, pos;
while(1)
{
printf("\n1. Input list\n");
printf("2. Insert\n");
printf("3. Search\n");
printf("4. Delete\n");
printf("5. Display\n");
printf("6. Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the number of elements to be entered : ");
scanf("%d",&n);
input(n);
break;
case 2:
insert();
break;
case 3:
if (n > 0)
15
{
printf("\nEnter the element to be searched : ");
scanf("%d", &item);
pos = search(item);
if(pos >= 1)
printf("\nElement %d found at position %d\n",item,pos);
else
printf("\nElement %d not found\n", item);
}
else
printf("\nNothing can be searched in Empty List\n");
break;
case 4:
del();
break;
case 5:
display();
break;
case 6:
exit(1);
break;
default:
printf("\nWrong choice\n");
} /*End of switch */
}/*End of while */
return 0;
}/*End of main() */
16
OUTPUT
1. Input list
2. Insert
3. Search
4. Delete
5. Display
6. Quit
Enter your choice : 1
Enter the number of elements to be entered : 5
Input value for element 1 : 10
Input value for element 2 : 20
Input value for element 3 : 30
Input value for element 4 : 40
Input value for element 5 : 50
1. Input list
2. Insert
3. Search
4. Delete
5. Display
6. Quit
Enter your choice : 2
Enter position for insertion : 3
Enter the value : 300
1. Input list
2. Insert
3. Search
4. Delete
5. Display
6. Quit
Enter your choice : 4
Enter the element to be deleted : 10
1. Input list
2. Insert
3. Search
4. Delete
5. Display
6. Quit
Enter your choice : 5
Value at position 1 : 20
Value at position 2 : 300
17
Value at position 3 : 30
Value at position 4 : 40
Value at position 5 : 50
1. Input list
2. Insert
3. Search
4. Delete
5. Display
6. Quit
Enter your choice : 6
Exit
18
RESULT:
Thus the C program to implement the List ADT using arrays has been
executed successfully.
19
Ex No: 3A
Date: Linked list implementation of List(Singly Linked List)
AIM
ALGORITHM:
20
PROGRAM:
# include <stdio.h>
# include <malloc.h>
typedef struct node
{
int info;
struct node *link;
} nodeType;
nodeType *start;
void create_list(int data)
{
nodeType *q, *tmp;
tmp = malloc(sizeof(nodeType));
tmp->info = data;
tmp->link = NULL;
tmp = malloc(sizeof(nodeType) );
tmp->link = q->link;
tmp->info = data;
q->link = tmp;
}/*End of addafter()*/
void del(int data)
{
nodeType *tmp, *q;
if(start->info == data)
{
tmp = start;
start = start->link; /*First element deleted*/
free(tmp);
return;
}
q = start;
while(q->link->link != NULL)
{
if(q->link->info == data) /*Element deleted in between*/
{
tmp = q->link;
q->link = tmp->link;
free(tmp);
return;
}
q = q->link;
}/*End of while */
if(q->link->info == data) /*Last element deleted*/
{
tmp = q->link;
free(tmp);
q->link = NULL;
return;
}
22
printf("\nElement %d not found\n",data);
}/*End of del()*/
void display()
{
nodeType *q;
if(start == NULL)
{
printf("\nList is empty\n");
return;
}
q = start;
printf("\nList is :");
while(q != NULL)
{
printf(" %d ", q->info);
q = q->link;
}
printf("\n");
}/*End of display() */
void search(int data)
{
nodeType *ptr = start;
int pos = 1;
while (ptr != NULL)
{
if(ptr->info == data)
{
printf("\nItem %d found at position %d\n", data, pos);
return;
}
ptr = ptr->link;
pos++;
}
if (ptr == NULL)
printf("\nItem %d not found in list\n", data);
}/*End of search()*/
int main()
{
int choice, n, m, position, i;
start = NULL;
while(1)
{
23
printf("\n1. Create List\n");
printf("2. Add at begining\n");
printf("3. Add after \n");
printf("4. Delete\n");
printf("5. Display\n");
printf("6. Search\n");
printf("7. Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nHow many nodes you want : ");
scanf("%d",&n);
for(i = 0; i < n; i++)
{
printf("Enter the element : ");
scanf("%d", &m);
create_list(m);
}
break;
case 2:
printf("\nEnter the element : ");
scanf("%d", &m);
addatbeg(m);
break;
case 3:
printf("\nEnter the element : ");
scanf("%d", &m);
printf("Enter the position after which this element is inserted :
");
scanf("%d", &position);
addafter(m, position);
break;
case 4:
if(start == NULL)
{
printf("\nList is empty\n");
continue;
}
printf("\nEnter the element for deletion : ");
scanf("%d", &m);
24
del(m);
break;
case 5:
display();
break;
case 6:
if (start != NULL)
{
printf("\nEnter the element to be searched : ");
scanf("%d", &m);
search(m);
}
else
printf("\nNothing can be searched in Empy List\n");
break;
case 7:
exit(1);
default:
printf("\nWrong choice\n");
}/*End of switch */
}/*End of while */
return 0;
}/*End of main()*/
25
OUTPUT
1. Create List
2. Add at begining
3. Add after
4. Delete
5. Display
6. Search
7. Quit
Enter your choice : 1
How many nodes you want : 5
Enter the element : 11
Enter the element : 22
Enter the element : 33
Enter the element : 44
Enter the element : 55
1. Create List
2. Add at begining
3. Add after
4. Delete
5. Display
6. Search
7. Quit
Enter your choice : 2
Enter the element : 00
1. Create List
2. Add at begining
3. Add after
4. Delete
5. Display
6. Search
7. Quit
Enter your choice : 3
Enter the element : 66
Enter the position after which this element is inserted : 6
1. Create List
2. Add at begining
3. Add after
4. Delete
5. Display
6. Search
26
7. Quit
Enter your choice : 4
Enter the element for deletion : 22
1. Create List
2. Add at begining
3. Add after
4. Delete
5. Display
6. Search
7. Quit
Enter your choice : 5
List is : 0 11 33 44 55 66
1. Create List
2. Add at begining
3. Add after
4. Delete
5. Display
6. Search
7. Quit
Enter your choice : 5
List is : 0 11 33 44 55 66
1. Create List
2. Add at begining
3. Add after
4. Delete
5. Display
6. Search
7. Quit
Enter your choice : 6
Enter the element to be searched : 50
27
RESULT:
Thus the C program for singly linked list using list has been executed successfully.
28
Ex No: 3B
Implementation of Stack Using Linked List
Date:
AIM
ALGORITHM
29
PROGRAM
# include<stdio.h>
# include<malloc.h>
typedef struct node
{
int info;
struct node *link;
} nodeType;
nodeType *top = NULL;
void push()
{
nodeType *tmp;
int item;
tmp = (nodeType *)malloc(sizeof(nodeType));
printf("\nEnter the item to be pushed in stack : ");
scanf("%d",&item);
tmp->info = item;
tmp->link = top;
top = tmp;
}/*End of push()*/
void pop()
{
nodeType *tmp;
if(top == NULL)
printf("\nStack is empty\n");
else
{ tmp = top;
printf("\nPopped element is : %d\n",tmp->info);
top = top->link;
free(tmp);
}}/*End of pop()*/
void display()
{
nodeType *ptr;
ptr = top;
if(top == NULL)
printf("\nStack is empty\n");
else
{
printf("\nStack elements :");
while(ptr!= NULL)
30
{
printf("%d ", ptr->info);
ptr = ptr->link;
}/*End of while */
printf("\n");
}/*End of else*/
}/*End of display()*/
int main()
{
int choice;
while(1)
{ printf("\n1.Push\n");
printf("2.Pop\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice : ") ;
scanf("%d", &choice);
switch(choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(1);
default :
printf("Wrong choice\n");
}/*End of switch */
}/*End of while */
return 0;
}/*End of main() */
OUTPUT
1.Push
2.Pop
3.Display
31
4.Quit
Enter your choice : 1
Enter the item to be pushed in stack : 222
1.Push
2.Pop
3.Display
4.Quit
Enter your choice : 1
Enter the item to be pushed in stack : 333
1.Push
2.Pop
3.Display
4.Quit
Enter your choice : 3
Stack elements :333 222
1.Push
2.Pop
3.Display
4.Quit
Enter your choice : 2
Popped element is : 333
1.Push
2.Pop
3.Display
4.Quit
Enter your choice : 3
Stack elements :222
1.Push
2.Pop
3.Display
4.Quit
Enter your choice : 4
32
RESULT
Thus a C program is written to implement stack using linked list and executed
Successfully
33
Ex No: 3C
Implementation of Queue using Linked List
Date:
AIM:
To write a C program to implement queue using linked list
ALGORITHM:
34
PROGRAM
# include<stdio.h>
# include<malloc.h>
typedef struct node
{
int info;
struct node *link;
}nodeType;
nodeType *front = NULL, *rear = NULL;
void enqueue()
{
nodeType *tmp;
int item;
tmp = (nodeType *)malloc(sizeof(nodeType));
printf("\nEnter the element for adding in queue : ");
scanf("%d", &item);
tmp->info = item;
tmp->link = NULL;
if(front == NULL) /*If Queue is empty*/
front = tmp;
else
rear->link = tmp;
rear = tmp;
}/*End of insert()*/
void dequeue()
{
nodeType *tmp;
if(front == NULL)
printf("\nQueue Underflow\n");
else
{
tmp=front;
printf("\nDeleted element is %d\n", tmp->info);
front = front->link;
free(tmp);
}}/*End of del()*/
void display()
{
nodeType *ptr;
ptr = front;
if(front == NULL)
35
printf("\nQueue is empty\n");
else
{
printf("\nQueue elements :");
while(ptr != NULL)
{
printf(" %d", ptr->info);
ptr = ptr->link;
}
printf("\n");
}}/*End of display()*/
int main()
{
int choice;
while(1)
{
printf("\n1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Display\n");
printf("4. Quit\n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1: enqueue();
break;
case 2: dequeue();
break;
case 3: display();
break;
case 4: exit(1);
default : printf("Wrong choice\n");
}}/*End of while*/
return 0;
}/*End of main()*/
36
OUTPUT
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 1
Enter the element for adding in queue : 10
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 1
Enter the element for adding in queue : 20
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 3
Queue elements : 10 20
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 2
Deleted element is 10
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 3
Queue elements : 20
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice : 4
37
RESULT:
Thus the C program to implement queue using linked list has been executed
successfully.
38
Ex No: 4A
APPLICATION OF LIST (POLYNOMIAL MULTIPLIATION)
Date:
AIM:
To write a C program to implement the polynomial multiplication.
ALGORITHM:
39
PROGRAM
#include<math.h>
#include<stdio.h>
#include<stdlib.h>
#define MAX 17
typedef struct node
{
int coeff;
struct node *next;
}node;
node * init();
void read(node *h1);
void print(node *h1);
node * add(node *h1,node *h2);
node * multiply(node *h1,node *h2);
void main()
{
node *h1=NULL,*h2=NULL,*h3=NULL;
int option;
do
{
printf("\n1 : create 1’st polynomial");
printf("\n2 : create 2’nd polynomial");
printf("\n3 : Add polynomials");
printf("\n4 : Multiply polynomials");
printf("\n5 : Quit");
printf("\nEnter your choice :");
scanf("%d",&option);
switch(option)
{
case 1:h1=init();read(h1);break;
case 2:h2=init();read(h2);break;
case 3:h3=add(h1,h2);
printf("\n1’st polynomial -> ");
print(h1);
printf("\n2’nd polynomial -> ");
print(h2);
printf("\n Sum = ");
print(h3);
break;
case 4:h3=multiply(h1,h2);
40
printf("\n1’st polynomial -> ");
print(h1);
printf("\n2’nd polynomial -> ");
print(h2);
printf("\n Product = ");
print(h3);
break;
}
}while(option!=5);
}
void read(node *h)
{
int n,i,j,power,coeff;
node *p;
p=init();
printf("\n Enter number of terms :");
scanf("%d",&n);
/* read n terms */
for (i=0;i<n;i++)
{ printf("\nenter a term(power coeff.)");
scanf("%d%d",&power,&coeff);
for(p=h,j=0;j<power;j++)
p=p->next;
p->coeff=coeff;
}
}
void print(node *p)
{
int i;
for(i=0;p!=NULL;i++,p=p->next)
if(p->coeff!=0)
printf("%dX^%d ",p->coeff,i);
}
node * add(node *h1, node *h2)
{
node *h3,*p;
h3=init();
p=h3;
while(h1!=NULL)
{
h3->coeff=h1->coeff+h2->coeff;
h1=h1->next;
41
h2=h2->next;
h3=h3->next;
}
return(p);
}
node * multiply(node *h1, node *h2)
{
node *h3,*p,*q,*r;
int i,j,k,coeff,power;
h3=init();
for(p=h1,i=0;p!=NULL;p=p->next,i++)
for(q=h2,j=0;q!=NULL;q=q->next,j++)
{
coeff=p->coeff * q->coeff;
power=i+j;
for(r=h3,k=0;k<power;k++)
r=r->next;
r->coeff=r->coeff+coeff;
}
return(h3);
}
node * init()
{
int i;
node *h=NULL,*p;
for(i=0;i<MAX;i++)
{
p=(node*)malloc(sizeof(node));
p->next=h;
p->coeff=0;
h=p;
}
return(h);
}
42
OUTPUT:
44
RESULT:
Thus the program to implement the polynomial addition has been executed
successfully.
45
Ex No: 4B
Date: APPLICATION OF STACK (INFIX TO POSTFIX)
AIM:
To write a C program to convert the infix expression into postfix expression
using stack.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the infix expression as input.
Step 3: Read the input from left to right.
Step 4: If the input is operand then place it in the postfix expression.
Step 5: Else if the input symbol is an operator then check for the operator type and
also the precedence, pop entries from the stack and place them in the postfix
expression until the lowest priority operator is encountered.
Step 6: „(„symbol will be popped from stack only when we get a „)‟ symbol.
Step 7: When the input is completely read then pop the elements in stack until it
becomes empty.
Step 8: Display the postfix expression.
Step 9: Stop the program.
46
PROGRAM
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define SIZE 50
typedef struct stacktype
{
char stk[SIZE];
int top;
} Stack;
typedef Stack* stackType;
void push (stackType, char); /* To Push the Operators in to Opearator Stack */
char pop (stackType); /* To Pop the Operators from Operator
Stack */
char peek (stackType); /* To Get the Top Element without Pop */
int isoperand (char); /* To Check whether the character is
Operand */
int isp (char); /* To Evaluate In-Stack Priority */
int icp (char); /* To Evaluate In-Coming Priority */
int empty(stackType); /* To Check Whether Stack is Empty */
void postfix(char [], char []);
void main()
{
char ifx[SIZE], pfx[SIZE];
int i;
postfix(ifx, pfx);
s = (stackType)malloc(sizeof(Stack));
s->top = -1;
j = 0;
for (i = 0; (symb = ifx[i]) != '\0'; i++)
{
if (isoperand(symb))
pfx[j++] = symb;
else
{
if (symb != ')')
{
while ((icp(symb) <= isp(ch = peek(s))) && !empty(s))
{
pfx[j++] = pop(s);
}
push(s, symb);
}
else
49
{
while (((ch = peek(s)) != '(') && !empty(s))
{
pfx[j++] = pop(s);
}
if (ch == '(')
ch = pop(s);
}
}
}
while (!empty(s))
pfx[j++] = pop(s);
pfx[j] = '\0';
}
OUTPUT
50
RESULT:
Thus the program to convert the infix expression into postfix expression
using stack has been implemented successfully.
51
Ex No: 4C
Date: APPLICATION OF STACK (Balancing Parenthesis)
AIM:
To write a C program to implement balancing parenthesis using stack.
ALGORITHM:
52
PROGRAM
#include <stdio.h>
#define SIZE 64
int top = -1;
char stack[SIZE];
void push_stack(char token)
{
top = top + 1;
stack[top] = token;
}
void pop_stack()
{
top = top - 1;
}
int emptystack()
{
return (top == -1);
}
/* End of Stack ADT */
int balanced_paranthesis(char str[])
{
int i, balanced;
i = 0;
balanced = 1;
while((str[i] != '\0') && balanced)
{
if (str[i] == '(')
push_stack(str[i]);
if (str[i] == ')')
if (!emptystack())
pop_stack();
else
{
balanced = 0;
break;
}
i++;
}
if (balanced && !emptystack())
balanced = 0;
if (!balanced)
53
return 0;
else
return 1;
}
int main()
{
char expr[64];
printf("\nEnter a Paranthesised Expression: ");
gets(expr);
printf("\nGiven Expression: ");
puts(expr);
if (balanced_paranthesis(expr))
printf("\nParanthesis are Balanced");
else
printf("\nParanthesis are NOT Balanced");
getch();
return 0;
}
OUTPUT
54
RESULT
Thus the program to implement balancing parenthesis using stack has
been implemented successfully.
55
Ex No: 4D APPLICATION OF STACK (EVALUATING POSTFIX
EXPRESSION)
Date:
AIM:
To write a C program to evaluate postfix expression using stack.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the string as input.
Step3: Scan the infix expression from left to right.
step4. If the scanned character is an operand, output it.
step5. Else,
…..5.1 If the precedence of the scanned operator is greater than the precedence of
the operator in the stack(or the stack is empty), push it.
…..5.2 Else, Pop the operator from the stack until the precedence of the scanned
operator is less-equal to the precedence of the operator residing on the top of the
stack. Push the scanned operator to the stack.
step 6: If the scanned character is an ‘(‘, push it to the stack.
step7: If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘
is encountered.
step 8: Repeat steps 4-8 until infix expression is scanned.
step 9: Pop and output from the stack until it is not empty.
56
PROGRAM
#include <stdio.h>
#include <math.h>
#define SIZE 64
/* Array Implementation of Stack ADT */
int top = -1;
float stack[SIZE];
void push_stack(float operand)
{
top = top + 1;
stack[top] = operand;
}
float pop_stack()
{
float operand;
operand = stack[top];
top = top - 1;
return operand;
}
int emptystack()
{
return (top == -1);
}
float evaluate_postfix(char postfix[])
{
float opnd1, opnd2, temp, result;
int i;
for(i=0; postfix[i]!='\0'; i++)
{
if(postfix[i] <= '9' && postfix[i] >= '0')
push_stack(postfix[i]-48);
else
{
opnd2 = pop_stack();
opnd1 = pop_stack();
switch(postfix[i])
{
case '+': temp = opnd1 + opnd2;
break;
case '-': temp = opnd1 - opnd2;
57
break;
case '*': temp = opnd1 * opnd2;
break;
case '/': temp = opnd1 / opnd2;
break;
case '^': temp = pow(opnd1, opnd2);
}
push_stack(temp);
}
}
result = pop_stack();
return result;
}
int main()
{
char expr[64];
float value;
printf("\nEnter a Valid Postfix Expression: ");
gets(expr);
printf("\nGiven Postfix Expression: ");
puts(expr);
value = evaluate_postfix(expr);
printf("\nValue of given Postfix Expression: %0.2f", value);
getch();
return 0;
}
/*End of main()*/
OUTPUT
58
RESULT
Thus the program to evaluate postfix expression using stack has been
implemented successfully.
59
Ex No: 4E
APPLICATION OF QUEUE (FCFS SCHEDULING)
Date:
AIM
ALGORITHM
Step5. Start with the first process from it’s initial position let other process to be in
queue
60
PROGRAM
#include<stdio.h>
main()
{
int n,a[10],b[10],t[10],w[10],g[10],i,m;
float att=0,awt=0;
for(i=0;i<10;i++)
{
a[i]=0; b[i]=0; w[i]=0; g[i]=0;
}
printf("enter the number of process");
scanf("%d",&n);
printf("enter the burst times");
for(i=0;i<n;i++)
scanf("%d",&b[i]);
printf("\nenter the arrival times");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
g[0]=0;
for(i=0;i<10;i++)
g[i+1]=g[i]+b[i];
for(i=0;i<n;i++)
{
w[i]=g[i]-a[i];
t[i]=g[i+1]-a[i];
awt=awt+w[i];
att=att+t[i];
}
awt =awt/n;
att=att/n;
printf("\n\tprocess\twaiting time\tturn arround time\n");
for(i=0;i<n;i++)
{
printf("\tp%d\t\t%d\t\t%d\n",i,w[i],t[i]);
}
printf("the average waiting time is %f\n",awt);
printf("the average turn around time is %f\n",att);
}
61
OUTPUT:
62
RESULT:
Thus the program to implement the FCFS scheduling algorithm has been
implemented successfully.
63
Ex No: 5
Date: Implementation of Binary Trees and operations of Binary Trees
AIM:
To write a C program to implement Binary Trees and operations of Binary
Trees.
ALGORITHM:
64
Step 5: Deletion of binary tree
Check first if root node is non-NULL, then
Call deltree() function recursively while there is non-NULL left node
Call deltree() function recursively while there is non-NULL right node
Delete the node.
Step 6: In-order display
Call print_inorder() function recursively while there is non-NULL left node
Display value of root node.
Call print_inorder() function recursively while there is non-NULL right
node
PROGRAM
#include<stdlib.h>
#include<stdio.h>
#define TRUE 1
#define FALSE 0
struct btreenode {
struct btreenode *lchild;
int data;
struct btreenode *rchild;
};
void insert(struct btreenode **, int);
void delete(struct btreenode **, int);
void search(struct btreenode **, int, struct btreenode **, struct btreenode **, int *);
void inorder(struct btreenode *);
main()
{
struct btreenode *bt;
int req, i = 0, num;
int a[] = {10, 7, 11, 5, 8, 12, 16, 15, 6};
bt = NULL;
while(i <= 8) {
insert(&bt, a[i]);
i++;
}
printf("\nBinary tree before deletion:\n");
inorder(bt);
65
delete(&bt, 11);
printf("\nBinary tree after deletion:\n");
inorder(bt);
delete(&bt, 10);
printf("\nBinary tree after deletion:\n");
inorder(bt);
delete(&bt, 6);
printf("\nBinary tree after deletion:\n");
inorder(bt);
delete(&bt, 16);
printf("\nBinary tree after deletion:\n");
inorder(bt);
getch();
return 0;
}
void insert(struct btreenode **sr, int num)
{
if (*sr == NULL) {
*sr = malloc(sizeof(struct btreenode));
(*sr)->lchild = NULL;
(*sr)->data = num;
(*sr)->rchild = NULL;
}
else {
if (num < (*sr)->data)
insert(&((*sr)->lchild), num);
else
insert(&((*sr)->rchild), num);
}
}
void delete(struct btreenode **root, int num)
{
int found;
struct btreenode *parent, *x, *xsucc;
if (*root == NULL) {
printf("\nTree is empty\n");
return;
}
parent = x = NULL;
search(root, num, &parent, &x, &found);
if (found == FALSE) {
printf("\nData to be deleted , NOT found\n");
66
return;
}
if (x->lchild != NULL && x->rchild != NULL) {
parent = x;
xsucc = x->rchild;
while (xsucc->lchild != NULL) {
parent = xsucc;
xsucc = xsucc->lchild;
}
x->data = xsucc->data;
x = xsucc;
}
if (x->lchild == NULL && x->rchild == NULL) {
if (parent->rchild == x)
parent->rchild = NULL;
else
parent->lchild = NULL;
free(x);
return;
}
if (x->lchild == NULL && x->rchild != NULL) {
if (parent->lchild == x)
parent->lchild = x->rchild;
else
parent->rchild = x->rchild;
free(x);
return;
}
if (x->lchild != NULL && x->rchild == NULL) {
if (parent->lchild == x)
parent->lchild = x->lchild;
else
parent->rchild = x->lchild;
free(x);
return;
}
}
void search(struct btreenode **root, int num, struct btreenode **par, struct
btreenode **x, int *found)
{
struct btreenode *q;
q = *root;
67
*found = FALSE;
*par = NULL;
while (q != NULL) {
if (q->data == num) {
*found = TRUE;
*x = q;
return;
}
*par = q;
if (q->data > num)
q = q->lchild;
else
q = q->rchild;
}
}
void inorder(struct btreenode *sr)
{
if (sr != NULL) {
inorder(sr->lchild);
printf("%d\t", sr->data);
inorder(sr->rchild);
}
}
68
OUTPUT
69
RESULT
70
Ex No: 6
Implementation of Binary Search Trees
Date:
AIM:
ALGORITHM:
72
PROGRAM
# include <stdio.h>
# include <malloc.h>
typedef struct node
{
int info;
struct node *lchild;
struct node *rchild;
} nodeType;
nodeType *root;
void find(int item, nodeType **par, nodeType **loc)
{
nodeType *ptr,*ptrsave;
while(ptr != NULL)
{
if(item == ptr->info)
{ *loc = ptr;
*par = ptrsave;
return;
}
ptrsave = ptr;
if(item < ptr->info)
73
ptr = ptr->lchild;
else
ptr = ptr->rchild;
}/*End of while */
*loc = NULL; /*item not found*/
*par = ptrsave;
}/*End of find()*/
void insert(int item)
{ nodeType *tmp, *parent, *location;
find(item, &parent, &location);
if(location != NULL)
{
printf("Item already present");
return;
}
tmp = (nodeType *)malloc(sizeof(nodeType));
tmp->info = item;
tmp->lchild = NULL;
tmp->rchild = NULL;
if(parent == NULL)
root = tmp;
else
if(item < parent->info)
parent->lchild = tmp;
else
parent->rchild = tmp;
}/*End of insert()*/
void del_a(nodeType *par, nodeType *loc )
/* To Delete Leaf Node */
{
if(par == NULL) /*item to be deleted is root node*/
root = NULL;
else
if(loc == par->lchild)
par->lchild = NULL;
else
par->rchild = NULL;
}/*End of del_a()*/
void del_b(nodeType *par, nodeType *loc)
/* To Delete Node with 1 Child */
{
nodeType *child;
74
/*Initialize child*/
if(loc->lchild != NULL) /*item to be deleted has lchild */
child = loc->lchild;
else /*item to be deleted has rchild */
child = loc->rchild;
int main()
{
int choice,num;
//clrscr();
root=NULL;
do
{
printf("\n BST Menu\n");
printf(" 1. Insert\n");
printf(" 2. Delete\n");
77
printf(" 3. Traversal\n");
printf(" 4. Quit\n");
printf(" Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the number to be inserted : ");
scanf("%d",&num);
insert(num);
break;
case 2:
printf("Enter the number to be deleted : ");
scanf("%d",&num);
del(num);
break;
case 3:
printf("\n Inorder Traversal: ");
inorder(root);
printf("\n");
printf("\n Preorder Traversal: ");
preorder(root);
printf("\n");
printf("\n Postorder Traversal: ");
postorder(root);
printf("\n");
break;
case 4:
break;
default:
printf("Wrong choice\n");
}/*End of switch */
}
while (choice != 4);
return 0;
}
78
OUTPUT
BST Menu
1. Insert
2. Delete
3. Traversal
4. Quit
Enter your choice : 1
Enter the number to be inserted : 3
BST Menu
1. Insert
2. Delete
3. Traversal
4. Quit
Enter your choice : 1
Enter the number to be inserted : 4
BST Menu
1. Insert
2. Delete
3. Traversal
4. Quit
Enter your choice : 1
Enter the number to be inserted : 2
BST Menu
1. Insert
2. Delete
3. Traversal
4. Quit
Enter your choice : 1
Enter the number to be inserted : 9
BST Menu
1. Insert
2. Delete
3. Traversal
4. Quit
Enter your choice : 3
Inorder Traversal: 2 3 4 9
Preorder Traversal: 3 2 4 9
Postorder Traversal: 2 9 4 3
BST Menu
1. Insert
79
2. Delete
3. Traversal
4. Quit
Enter your choice : 2
Enter the number to be deleted : 4
BST Menu
1. Insert
2. Delete
3. Traversal
4. Quit
Enter your choice : 3
Inorder Traversal: 2 3 9
Preorder Traversal: 3 2 9
Postorder Traversal: 2 9 3
BST Menu
1. Insert
2. Delete
3. Traversal
4. Quit
Enter your choice : 4
80
RESULT
Thus the program to construct a binary search tree and perform various
operations has been executed successfully.
81
Ex No: 7
Implementation of AVL Trees
Date:
AIM:
To write a C program for the implementation of AVL trees.
ALGORITHM:
82
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<math.h>
typedef struct node
{
int data;
struct node *left,*right;
int ht;
}node;
node *insert(node *,int);
node *Delete(node *,int);
void preorder(node *);
void inorder(node *);
int height( node *);
node *rotateright(node *);
node *rotateleft(node *);
node *RR(node *);
node *LL(node *);
node *LR(node *);
node *RL(node *);
int BF(node *);
main()
{
node *root=NULL;
int x,n,i,op;
do
{
printf("\n1)Create:");
printf("\n2)Insert:");
printf("\n3)Delete:");
printf("\n4)Print:");
printf("\n5)Quit:");
printf("\n\nEnter Your Choice:");
scanf("%d",&op);
switch(op)
{
case 1: printf("\nEnter no. of elements:");
scanf("%d",&n);
printf("\nEnter tree data:");
root=NULL;
83
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
break;
case 2: printf("\nEnter a data:");
scanf("%d",&x);
root=insert(root,x);
break;
case 3: printf("\nEnter a data:");
scanf("%d",&x);
root=Delete(root,x);
break;
case 4: printf("\nPreorder sequence:\n");
preorder(root);
printf("\n\nInorder sequence:\n");
inorder(root);
printf("\n");
break;
}
}while(op!=5);
getch();
return 0;
}
node * insert(node *T,int x)
{
if(T==NULL)
{
T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);
else
84
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x < T->left->data)
T=LL(T);
else
T=LR(T);
}
T->ht=height(T);
return(T);
}
node * Delete(node *T,int x)
{
node *p;
if(T==NULL)
{
return NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=Delete(T->right,x);
if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
if(x<T->data)
{
T->left=Delete(T->left,x);
if(BF(T)==-2) //Rebalance during windup
if(BF(T->right)<=0)
T=RR(T);
else
T=RL(T);
}
85
else
{
if(T->right!=NULL)
{ //delete its inorder succesor
p=T->right;
while(p->left!= NULL)
p=p->left;
T->data=p->data;
T->right=Delete(T->right,p->data);
if(BF(T)==2)//Rebalance during windup
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);\
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}
int height(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
if(lh>rh)
return(lh);
return(rh);
}
node * rotateright(node *x)
{
node *y;
y=x->left;
86
x->left=y->right;
y->right=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}
node * rotateleft(node *x)
{
node *y;
y=x->right;
x->right=y->left;
y->left=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}
node * RR(node *T)
{
T=rotateleft(T);
return(T);
}
node * LL(node *T)
{
T=rotateright(T);
return(T);
}
node * LR(node *T)
{
T->left=rotateleft(T->left);
T=rotateright(T);
return(T);
}
node * RL(node *T)
{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}
int BF(node *T)
{
int lh,rh;
if(T==NULL)
87
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
return(lh-rh);
}
void preorder(node *T)
{
if(T!=NULL)
{
printf("%d(Bf=%d)",T->data,BF(T));
preorder(T->left);
preorder(T->right);
}
}
void inorder(node *T)
{
if(T!=NULL)
{
inorder(T->left);
printf("%d(Bf=%d)",T->data,BF(T));
inorder(T->right);
}
}
88
OUTPUT
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:1
Enter no. of elements:5
Enter tree data:1 2 3 4 5
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:2
Enter a data:8
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:4
Preorder sequence:
4(Bf=0)2(Bf=0)1(Bf=0)3(Bf=0)5(Bf=-1)8(Bf=0)
Inorder sequence:
1(Bf=0)2(Bf=0)3(Bf=0)4(Bf=0)5(Bf=-1)8(Bf=0)
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:3
Enter a data:5
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:4
Preorder sequence:
4(Bf=1)2(Bf=0)1(Bf=0)3(Bf=0)8(Bf=0)
89
Inorder sequence:
1(Bf=0)2(Bf=0)3(Bf=0)4(Bf=1)8(Bf=0)
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter Your Choice:5
90
RESULT:
Thus the program to implement AVL tree operations has been executed
successfully.
91
Ex No: 8
AIM
To write a C program for the implementation of heaps using priority queues.
ALGORITHM:
92
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define MAX 100/*Declaring the maximum size of the queue*/
void swap(int*,int*);
main()
{
int choice,num,n,a[MAX],data,s;
void display(int[],int);
void insert(int[],int,int,int);
int del_hi_priori(int[],int,int);
int lb=0;/*Lower bound of the array is initialized to 0*/
clrscr();
n=0;
while(1)
{
printf(".....MAIN MENU.....\n");
printf("\n1.Insert\n");
printf("2.Delete\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter data to be inserted : ");
scanf("%d",&data);
insert(a,n,data,lb);
n++;
break;
case 2: s=del_hi_priori(a,n+1,lb);
if(s!=0)
printf("\nThe deleted value is : %d \n",s);
if(n>0)
n--;
break;
case 3: printf("\n");
display(a,n);
break;
case 4: return;
default: printf("Invalid choice.n");
93
}
printf("\n\n");
}
}
void insert(int a[],int heapsize,int data,int lb)
{
int i,p;
int parent(int);
if(heapsize==MAX)
{
printf("Queue Is Full!!\n");
return;
}
i=lb+heapsize;
a[i]=data;
while(i>lb&&a[p=parent(i)]<a[i])
{
swap(&a[p],&a[i]);
i=p;
}
}
/*This function deletes an element from the queue*/
int del_hi_priori(int a[],int heapsize,int lb)
{
int data,i,l,r,max_child,t;
int left(int);
int right(int);
if(heapsize==1)
{
printf("Queue Is Empty!!\n");
return 0;
}
t=a[lb];
swap(&a[lb],&a[heapsize-1]);
i=lb;
heapsize--;
while(1)
{
if((l=left(i))>=heapsize)
break;
if((r=right(i))>=heapsize)
max_child=l;
94
else
max_child=(a[l]>a[r])?l:r;
if(a[i]>=a[max_child])
break;
swap(&a[i],&a[max_child]);
i=max_child;
}
return t;
}
int parent(int i)
{
float p;
p=((float)i/2.0)-1.0;
return ceil(p);
}
/*Returns leftchild index*/
int left(int i)
{
return 2*i+1;
}
/*Returns rightchild index*/
int right(int i)
{
return 2*i+2;
}
void display(int a[],int n)
{
int i;
if(n==0)
{
printf("Queue Is Empty!!\n");
return;
}
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
void swap(int*p,int*q)
{
int temp;
temp=*p;
*p=*q;
95
*q=temp;
}
OUTPUT
MAIN MENU.....
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 1
Enter data to be inserted : 12
.....MAIN MENU.....
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 1
Enter data to be inserted : 32
.....MAIN MENU.....
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 1
Enter data to be inserted : 2
......MAIN MENU.....
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 3
32 12 2
.....MAIN MENU.....
1.Insert
2.Delete
3.Display
4.Quit
96
Enter your choice : 2
The deleted value is : 32
....MAIN MENU.....
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 1 4 3
12 4 2
.....MAIN MENU.....
1.Insert
2.Delete
3.Display
4.Quit
97
RESULT:
Thus the program for the implementation of heaps using priority queues has
been executed successfully.
98
Ex No: 9A
AIM:
To write a C program to implement graph representation(Adjacency matrix)
ALGORITHM:
99
PROGRAM
#include<stdio.h>
#include<malloc.h>
struct node
{
char vertex;
struct node *next;
};
struct node *gnode;
void displayGraph(struct node *adj[],int no_of_nodes);
void deleteGrapgh(struct node *adj[],int no_of_nodes);
void createGraph(struct node *adj[],int no_of_nodes);
void createGraph(struct node *adj[],int no_of_nodes)
{
struct node *newnode,*last;
int i,j,n,val;
for(i=0;i<no_of_nodes;i++)
{
last=NULL;
printf("Enter the number of neighbours of %d:",i);
scanf("%d",&n);
for(j=1;j<=n;j++)
{
printf("\n Enter the neighbour %d of %d:",j,i);
scanf("%d",&val);
newnode=(struct node *)malloc(sizeof(struct node));
newnode->vertex=val;
newnode->next=NULL;
if(adj[i]==NULL)
adj[i]=newnode;
else
last->next=newnode;
last=newnode;
}
}
}
void displayGraph(struct node *adj[],int no_of_nodes)
{
struct node *ptr;
int i;
for(i=0;i<no_of_nodes;i++)
100
{
ptr=adj[i];
printf("\n The neighbours of node %d are:",i);
while(ptr!=NULL)
{
printf("%d\t",ptr->vertex);
ptr=ptr->next;
}
}
}
void deleteGraph(struct node *adj[],int no_of_nodes)
{
int i;
struct node *temp,*ptr;
for(i=0;i<=no_of_nodes;i++)
{
ptr=adj[i];
while(ptr!=NULL)
{
temp=ptr;
ptr=ptr->next;
free(temp);
}
adj[i]=NULL;
}
}
void main()
{
struct node *adj[10];
int i,no_of_nodes;
printf("\n Enter the number of nodes in G:");
scanf("%d",&no_of_nodes);
for(i=0;i<no_of_nodes;i++)
adj[i]=NULL;
createGraph(adj,no_of_nodes);
printf("\n The graph is:");
displayGraph(adj,no_of_nodes);
deleteGraph(adj,no_of_nodes);
getch();
}
101
OUTPUT
102
RESULT:
Thus the program for the implementation of graphs has been executed
successfully.
103
Ex No: 9B
AIM:
To write a C program to implement graph traversal algorithm(DFS).
ALGORITHM:
The DFS algorithm works as follows:
Step 1:Start by putting any one of the graph's vertices on top of a stack.
Step 2:Take the top item of the stack and add it to the visited list.
Step 3:Create a list of that vertex's adjacent nodes. Add the ones which aren't
in the visited list to the top of stack.
Step 4:Keep repeating steps 2 and 3 until the stack is empty.
104
PROGRAM
#include<stdio.h>
void DFS(int);
int G[10][10],visited[10],n;
main()
{
int i,j;
printf("Enter number of vertices:");
scanf("%d",&n);
//read the adjecency 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);
getch();
return 0;
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}
105
OUTPUT
Enter number of vertices:4
Enter adjecency matrix of the graph:0 1 1 0
1011
1100
1110
0
1
2
106
RESULT:
Thus the program for the implementation of graph traversal(DFS) has been
executed successfully.
107
Ex No: 9C
Graph Traversal algorithms(Breadth First Search)
Date:
AIM:
To write a C program to implement graph traversal algorithm(BFS).
ALGORITHM:
The BFS algorithm works as follows:
Step 1:Start by putting any one of the graph's vertices at the back of a queue.
Step 2:Take the front item of the queue and add it to the visited list.
Step 3:Create a list of that vertex's adjacent nodes. Add the ones which aren't
in the visited list to the back of the queue.
Step 4:Keep repeating steps 2 and 3 until the queue is empty.
108
PROGRAM
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
#define initial 1
#define waiting 2
#define visited 3
int n;
int adj[MAX][MAX];
int state[MAX];
void create_graph();
void BF_Traversal();
void BFS(int v);
int queue[MAX], front = -1,rear = -1;
void insert_queue(int vertex);
int delete_queue();
int isEmpty_queue();
int main()
{
create_graph();
BF_Traversal();
return 0;
}
void BF_Traversal()
{
int v;
for(v=0; v<n; v++)
state[v] = initial;
printf("Enter Start Vertex for BFS: \n");
scanf("%d", &v);
BFS(v);
}
void BFS(int v)
{
int i;
insert_queue(v);
state[v] = waiting;
while(!isEmpty_queue())
{
v = delete_queue( );
printf("%d ",v);
state[v] = visited;
109
for(i=0; i<n; i++)
{
if(adj[v][i] == 1 && state[i] == initial)
{
insert_queue(i);
state[i] = waiting;
}
}
}
printf("\n");
}
void insert_queue(int vertex)
{
if(rear == MAX-1)
printf("Queue Overflow\n");
else
{
if(front == -1)
front = 0;
rear = rear+1;
queue[rear] = vertex ;
}
}
int isEmpty_queue()
{
if(front == -1 || front > rear)
return 1;
else
return 0;
}
int delete_queue()
{
int delete_item;
if(front == -1 || front > rear)
{
printf("Queue Underflow\n");
exit(1);
}
delete_item = queue[front];
110
front = front+1;
return delete_item;
}
void create_graph()
{
int count,max_edge,origin,destin;
111
RESULT:
Thus the program for the implementation of graph traversal(BFS) has been
executed successfully.
112
Ex No: 10
AIM:
ALGORITHM:
STEP1: Include all the header files.
STEP2: Get the number of vertices.
STEP3: Get the edge weights for each vertex.
STEP 4: Sort all the edges in non-decreasing order of their weight.
STEP 5:Pick the smallest edge. Check if it forms a cycle with the spanning tree
formed so far. If cycle is not formed, include this edge. Else, discard it.
STEP 6: Repeat step#2 until there are (V-1) edges in the spanning tree.
STEP7: stop the program
113
PROGRAM
#include<stdio.h>
#define MAX 10
int adj[MAX][MAX],tree[MAX][MAX],n;
void readmatrix()
{
int i,j;
printf("\n Enter the number of nodes in the graph:");
scanf("%d",&n);
printf("\n Enter the adjacency matrix of the graph");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&adj[i][j]);
}
int spanningtree(int src)
{
int visited[MAX],d[MAX],parent[MAX];
int i,j,k,min,u,v,cost;
for(i=1;i<=n;i++)
{
d[i]=adj[src][i];
visited[i]=0;
parent[i]=src;
}
visited[src]=1;
cost=0;
k=1;
for(i=1;i<=n;i++)
{
min=9999;
for(j=1;j<=n;j++)
{
if(visited[j]==0 && d[j]<min)
{
min=d[j];
u=j;
cost+=d[u];
}
}
visited[u]=1;
tree[k][1]=parent[u];
tree[k++][2]=u;
114
for(v=1;v<=n;v++)
if(visited[v]==0 && (adj[u][v]<d[v]))
{
d[v]=adj[u][v];
parent[v]=u;
}
}
return cost;
}
void display(int cost)
{
int i;
printf("\n The edges of the minimum spanning tree are");
for(i=1;i<n;i++)
printf("%d %d \n ",tree[i][1],tree[i][2]);
printf("\n The total cost of the minimum spanning tree is :%d",cost);
}
void main()
{
int source,treecost;
readmatrix();
printf("\n Enter the source:");
scanf("%d",&source);
treecost=spanningtree(source);
display(treecost);
}
115
OUTPUT
116
RESULT:
Thus the C program to implement minimum spanning tree has been
executed successfully.
117
Ex No: 11A
Date: SEARCHING-LINEAR SEARCH
AIM
To write a C program to implement linear searching.
ALGORITHM
118
PROGRAM
# include<stdio.h>
# define SIZE 05
main()
{
int i = 0;
int j;
int num_list[SIZE]; /* array declaration */
/* enter elements in the following loop */
printf("Enter any 5 numbers: \n");
for(i = 0;i < SIZE; i++)
{
printf("Element no. %2d Value of the element = ",i+1);
scanf("%d",&num_list[i]);
}
printf ("Enter the element to be searched: ");
scanf ("%d",&j);
for(i = 0;i < SIZE; i++)
{
if(j == num_list[i])
{
printf("Element %d exists in the list at position: %d\n",j,i+1);
break;
}
}
if (i == SIZE)
printf("Element %d does not exist in the list\n",j);
getch();}
OUT PUT
Enter any 10 numbers in ASCENDING order:
Element no. 1 Value of the element = 12
Element no. 2 Value of the element = 23
Element no. 3 Value of the element = 34
Element no. 4 Value of the element = 45
Element no. 5 Value of the element = 56
Element no. 6 Value of the element = 67
Element no. 7 Value of the element = 78
Element no. 8 Value of the element = 89
Element no. 9 Value of the element = 90
Element no. 10 Value of the element = 111
120
Ex No: 11B
AIM
To write a C program to implement binary searching.
ALGORITHM
121
PROGRAM
# include<stdio.h>
# define SIZE 10
main()
{
int i = 0;
int j, low, high, mid;
int num_list[SIZE]; /* array declaration */
/* enter elements in the following loop */
printf("Enter any %d numbers in ASCENDING order: \n", SIZE);
for(i = 0; i < SIZE; i++)
{
printf("Element no. %2d Value of the element = ",i+1);
scanf("%d",&num_list[i]);
}
printf ("Enter the element to be searched: ");
scanf ("%d",&j);
/* search using binary search */
low = 0;
high = SIZE - 1;
while (low <= high)
{
mid = (low + high) / 2;
if (j == num_list[mid])
{
printf("Element %d exists in the list at position: %d\n",j,mid+1);
break;
}
else if (j > num_list[mid])
low = mid + 1;
else
high = mid - 1;
}
if (low > high)
printf("Element %d does not exist in the list\n", j);
getch();
}
122
OUTPUT
Enter any 5 numbers:
Element no. 1 Value of the element = 23
Element no. 2 Value of the element = 2
Element no. 3 Value of the element = 44
Element no. 4 Value of the element = 1
Element no. 5 Value of the element = 89
Enter the element to be searched: 44
Element 44 exists in the list at position: 3
123
RESULT:
Thus the program to implement binary searching has been implemented
successfully.
124
Ex No: 11C
SORTING (INSERTION, SELECTION, BUBBLE, SHELL,
Date: RADIX SORT)
INSERTION SORT
AIM:
ALGORITHM:
125
PROGRAM:
/* Write a program to sort a list of elements using the Insertion sort method */
#include <stdio.h>
void InsertionSort(int [], int);
#define MAX 20
main()
{
int arr[MAX],i,j,Tmp,n;
printf("Enter the number of elements : ");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
printf("Enter element %d : ",i+1);
scanf("%d", &arr[i]);
}
printf("Unsorted list is :\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
InsertionSort(arr, n);
printf("Sorted list is :\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
getch();
}
126
OUTPUT
Enter the number of elements : 5
Enter element 1 : 100
Enter element 2 : 50
Enter element 3 : 25
Enter element 4 : 75
Enter element 5 : 5
Unsorted list is :
100 50 25 75 5
Sorted list is :
5 25 50 75 100
127
SELECTION SORT
AIM:
To write a C program for sorting an array of N numbers using selection sort.
ALGORITHM:
1. Start the program
2. Initialize a[max],i,j,n
3. Read the number of elements from the user
4. Read the elements
5. Display the unsorted elements to the user
6. Invoke function call selectionsort(a,n)
6.1 In function block, using for loop for(i=0;i<n-1;i++)
6.2 index=i;
6.3 using for loop, for(j=i+1;j<n;j++)
6.4 Check the condition,if(a[j]<a[index]), if it is true go to next step else go to step
6.6
6.5 index=j;
6.6 Calculate
smallno=a[index];
a[index]=a[i];
a[i]=smallno;
6.7Return back to main function
7. Display sorted list to the user
8. Stop the program
128
PROGRAM:
/* Write a program to sort a list of elements using the Selection sort method */
#include <stdio.h>
void SelectionSort(int [], int);
#define MAX 20
main()
{
int arr[MAX],i,j,Tmp,n;
printf("Enter the number of elements : ");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
printf("Enter element %d : ",i+1);
scanf("%d", &arr[i]);
}
printf("Unsorted list is :\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
SelectionSort(arr, n);
printf("Sorted list is :\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
getch();
}
129
OUTPUT
Enter the number of elements : 7
Enter element 1 : 5
Enter element 2 : 1
Enter element 3 : 8
Enter element 4 : 3
Enter element 5 : 6
Enter element 6 : 10
Enter element 7 : 0
Unsorted list is :
5183680
Sorted list is :
0 1 3 5 6 8 10
130
BUBBLE SORT
AIM:
To write a C program for sorting an array of N numbers using bubble sort.
ALGORITHM:
1. Start the program
2. Initialize i,j,n,temp,a[max]
3. Read the number of elements from the user
4. Read the elements
5. Display the unsorted elements to the user
6. Invoke function call bubblesort(a,n)
6.1Using for loop, for(i=0;i<n-1;i++)
6.2Using for loop,for(j=0;j<n-1-i;j++)
6.3Check the condition, if(a[j]>a[j+1]), if it is true perform the following
6.3.1 Calculate
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
6.4Return back to main function
7. Display sorted list to the user
8. Stop the program
131
PROGRAM:
/* Write a program to sort a list of elements using the Bubble sort method */
#include <stdio.h>
//#include <conio.h>
void BubbleSort(int [], int);
#define MAX 20
main()
{
int arr[MAX],i,j,Tmp,n;
printf("Enter the number of elements : ");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
printf("Enter element %d : ",i+1);
scanf("%d", &arr[i]);
}
printf("Unsorted list is :\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
BubbleSort(arr, n);
printf("Sorted list is :\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
getch();
}
132
OUTPUT
133
SHELL SORTING
AIM:
To write a C program for sorting an array of N numbers using shell sort.
ALGORITHM:
Step 1 − Initialize the value of h
Step 2 − Divide the list into smaller sub-list of equal interval h
Step 3 − Sort these sub-lists using insertion sort
Step 3 − Repeat until complete list is sorted
134
PROGRAM
/* Write a program to sort a list of elements using the Shell sort method */
#include <stdio.h>
void ShellSort(int [], int);
#define MAX 20
main()
{
int arr[MAX],i,j,Tmp,n;
printf("Enter the number of elements : ");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
printf("Enter element %d : ",i+1);
scanf("%d", &arr[i]);
}
printf("Unsorted list is :\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
ShellSort(arr, n);
printf("Sorted list is :\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
getch();
}
136
RADIX SORT
AIM
To write a C program to implement Radix sort
ALGORITHM:
137
PROGRAM
/* Write a program to sort a list of elements using the Radix sort method */
#include <stdio.h>
#include <stdlib.h>
void RadixSort(int [], int);
#define MAX 20
main()
{
int arr[MAX],i,j,Tmp,n;
printf("Enter the number of elements : ");
scanf("%d",&n);
for (i = 0; i < n; i++)
{
printf("Enter element %d : ",i+1);
scanf("%d", &arr[i]);
}
printf("Unsorted list is :\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
RadixSort(arr, n);
printf("Sorted list is :\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
getch();
}
OUTPUT
Enter the number of elements : 10
Enter element 1 : 23
Enter element 2 : 43
Enter element 3 : 35
Enter element 4 : 88
Enter element 5 : 2
Enter element 6 : 45
Enter element 7 : 54
Enter element 8 : 12
Enter element 9 : 9
Enter element 10 : 10
Unsorted list is :
23 43 35 88 2 45 54 12 9 10
Sorted list is :
2 9 10 12 23 35 43 45 54 88
139
RESULT:
Thus the C program to implement sorting has been implemented
successfully.
140
Ex No: 12
HASHING (LINEAR AND QUADRIC PROBING)
Date:
AIM
To write a C program to implement hashing
ALGORITHM
Step 1: Start the program
Step 2: Get the number of elements and elements to be stored in array.
Step 3: If Linear probing, use formula,
h(k,i)=(h’(k)+i)mod n, where h’(k)=k mod n and store the elements.
Else if quadrating probing, use formula,
h(k,i)=(h’(k)+c1i+c2i2)mod n, where h’(k)=k mod n, c1 & c2 are
constants.
Step4: Exit.
141
PROGRAM
#include <stdio.h>
#include <conio.h>
int tsize;
//-------LINEAR PROBING-------
int rehashl(int key)
{
int i ;
i = (key+1)%tsize ;
return i ;
}
//-------QUADRATIC PROBING-------
int rehashq(int key, int j)
{
int i ;
i = (key+(j*j))%tsize ;
return i ;
}
void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;
clrscr() ;
printf ("Enter the size of the hash table: ");
scanf ("%d",&tsize);
printf ("\nEnter the number of elements: ");
scanf ("%d",&n);
for (i=0;i<tsize;i++)
hash[i]=-1 ;
printf ("Enter Elements: ");
for (i=0;i<n;i++)
{
scanf("%d",&arr[i]);
142
}
do
{
printf("\n\n1.Linear Probing\n2.Quadratic Probing \n3.Exit \nEnter your option:
");
scanf("%d",&op);
switch(op)
{
case 1:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashl(i);
}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
case 2:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
j=1;
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashq(i,j);
j++ ;
}
hash[i]=key ;
143
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
}
}while(op!=3);
getch() ;
OUTPUT
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 1
1.Linear Probing
2.Quadratic Probing
144
3.Exit
Enter your option: 2
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 3
145
RESULT:
Thus the C program to implement hashing has been implemented
successfully.
146