Cs3362 C Programming and Data Structures Lab Ece

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 105

EX.

NO: 1A) AREA OF THE CIRCLE

AIM:

To find the Area of the circle.

ALGORITHM:

Step 1: Start the program.

Step 2: Declare the variables of respective data type.

Area->integer

Radius->integer

Step 3: Get the radius.

Step 4: Calculate

area=3.14*radius*radius Step 5: Print the

area of the circle.

Step 6: Stop.

1
C PROGRAM:
/*Area of Circle*/
#include<stdio.h>
#include<conio.h
> void main()
{
float r,area;
clrscr();
printf("Enter the Radius of the circle:\n");
printf("\nRadius=");
scanf("%f",&r);
area=3.14*r*r;
printf("\n Area=%f",area);
getch();
}

OUTPUT :

Enter the Radius of the circle:

Radius=5

Area=78.500000

RESULT:

Thus the area of the circle using C program has been executed and verified successfully.

2
EX.NO 1B) TO FIND THE GIVEN NUMBER IS EVEN OR ODD

AIM:

To write a program to find the given number is even or odd

ALGORITHM:

Step 1: Start the program.


Step 2: Declare the variable of respective data type.
n->integer
Step 3: Get the value for a
Step 4: If (n%2= 0) print n is Even
Else print n is odd
Step 5: Stop.

3
C PROGRAM:
#include<stdio.h>
#include<conio.h
> void main()
{
int n;
clrscr();
printf("Enter the number:");
scanf("%d",&n); if(n
%2==0)
{
printf("\n The number %d is Even..!",n);
}
else
{
printf("\n The number %d is Odd..!",n);
}
getch();
}

4
OUTPUT:

Enter the number: 776


The number 776 is Even..!
Enter the number: 5
The number5 is Odd..!

RESULT:

Thus the given number is even or odd using C program has been executed and verified successfully.

5
EX.NO:1C) AVERAGE OF FIVE

MARKS AIM:

To write a C program to calculate the average of given five numbers.

ALGORITHM:

Step 1: Start the program.


Step 2: Declare the five variable to get the marks.
Step 3: Read the input of five marks
Step 4: calculate the sum of five numbers
Step 5:Divide the sum by 5
Step 6: Display the
average. Step 7:Stop

6
C PROGRAM:
#include<stdio.h>
#include<conio.h
> void main()
{
int m1,m2,m3,m4,m5;
clrscr();
floatavg,tot;
printf("Enter the 5 marks\n"); scanf("%d%d%d%d
%d",&m1,&m2,&m3,&m4,&m5);
tot=m1+m2+m3+m4+m5;
avg=tot/5;
printf("\n The average is %f\n",avg);
getch();
}

OUTPUT:

Enter the 5
marks 99
35
65
78
35
The average is 62.400002

RESULT:

Thus the average of five numbers using C program has been executed and verified successfully.

EX. NO: 1D) GENARATE FIBONACCI SERIES

AIM:
7
To write a program to generate fibonocci series

ALGORITHM:

Step 1: Start the program.


Step 2: Declare the variables of respective data type. n,a,b,c->integer
Step 3: Get the value for n
Step 4: set i=0
Step 5: if(i<n) then go to step 6 Else goto step 10
Step 6: calculate c=a+b
Step 7: print c
Step 8: Set a=b,b=c,i=i+1;
Step 9: goto step 5
Step 10: Stop.

C PROGRAM:

#include<stdio.h>
#include<conio.h>
8
void main()
{
intn,i,c;
int a=-1,b=1;
clrscr();
printf("Enter the number:\n");
scanf("%d",&n); printf("\
nFibonacci Series is :");
for(i=0;i<n;i++)
{ c=a+b;
a=b; b=c;
printf("\n%d",c);
} getch(); }

OUTPUT:
Enter the number: 6
Fibonacci Series is:
0
1
1
2
3
5

RESULT:
Thus the Fibonacci series is generated by using C program has been executed and verified
successfully

EX.NO:1E) SUM OF THE DIGITS

9
AIM:
To write a program to find sum of digits

ALGORITHM:

Step 1: Start the program.


Step 2: Declare the variables of respective data
type. n,r,sum->integer.
Step 3: Set sum=0
Step 4: If n>0 then
Step 5: Calculate r=n%10
Sum=sum+r
n=n/10
Step 6: Print sum
Step 7: Stop

C PROGRAM:

10
/*Sum of Digits*/
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
intn,r,sum=0;
clrscr();
printf("Enter the number:\
n"); scanf("%d",&n);
while(n >0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("\nSum of digits =%d",sum);
getch();
}

OUTPUT :

Enter the number:


76
Sum of digits=13

RESULT:

This sum of digits using C program has been executed and verified successfully.

EX.NO: 1F) SUM OF ARRAY ELEMENTS

11
AIM:
To write a program to find sum of Array elements

ALGORITHM:
Step1: Start the program
Step2: Declare an array with necessary size
Step3: Get the value for total number of elements
Step4: Read the inputs
Step5: Initialize the index value and sum value
Step6: Increment the index value by 1
Step7: Repeat the step 4 and 5 until account less than total number of elements
Step8: Printing of all elements of array
Step9: Print the Sum
Step10: Stop the Program

C PROGRAM:
#include<stdio.h>
12
void main()
{
inti,n,a[10],sum=0;
clrscr();
printf("Enter the total no. of elements\n");
scanf("%d", &n);
printf("Enter Array elements one by one\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
sum=sum+a[i];
printf("The sum of Array Elements is %d \n", sum);
getch();
}

OUTPUT:

Enter the total no. of elements


6
Enter Array elemets one by one
34
5
6
7
8
9
The sum of Array Elements is 69

RESULT: Thus the sum of array elements by using C program has been executed and verified
successfully.

EX.NO: 1G) MATRIX MULTIPLICATION

13
AIM:

To write a program to perform matrix multiplication.

ALGORITHM:

STEP 1: Start the program.


STEP 2: Declare the array variables of respective data type.
STEP 3: Get the number of rows and columns.
STEP 4: Get the element of matrix A.
STEP 5: Get the element of matrix B.
STEP 6: Multiply the rows of A with respective columns of B by taking the
corresponding element in A and B using for loop.
STEP 7: Print the resultant matrix.
STEP 8: Stop.

C PROGRAM:

14
#include<stdio.h>
#include<conio.h
> void main()
{
int a[5][5], b[5][5], c[5][5], r1, r2, c1, c2, i, j, k;
clrscr();
printf("\n Enter the size of matrix A:");
scanf("%d%d", &r1, &c1);
printf("\n Enter the size of matrix B:");
scanf("%d%d", &r2, &c2);
if(c1==r2)
{
printf("\n Enter the elements of matrix A:\n");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d", &a[i][j]);
printf("\n Enter the elements of matrix B:\n");
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf("%d", &b[i][j]);
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{ c[i]
[j]=0;
for(k=0;k<c1;k++) c[i][j]=c[i][j]+a[i]
[k]*b[k][j];
}}
printf("\n The resultant matrix is:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t", c[i][j]);
}
printf("\n");
}}
getch();
}

OUTPUT:
Enter the size of matrix A:2
15
2
Enter the size of matrix B:2
2
Enter the elements of matrix A:
9
7
4
5
Enter the elements of matrix B:
6
7
4
6
The resultant matrix is:
82 105
44 58

RESULT:

Thus the multiplication of matrix using C program has been executed and verified successfully.

16
EX.NO:2A) STRING PALINDROME CHECKING

AIM:
To find the string palindrome checking by “C” program

ALGORITHM:

STEP 1: Start the program.


STEP 2: Declare the variable with respect data type char s[20],s1[20]
STEP 3: Enter the String
STEP 4: Copy the string using strcpy(S1,S).
STEP 5: Reverse the string using
strrev(S1). STEP 6: Calculate
n=strcmp(S,S1).
STEP 7: If (n==0) then “The given string is a PALINDROME”.
STEP 8: Else “The given string is not a PALINDROME”.
STEP 9: Stop.

17
C PROGRAM:

#include<stdio.h>
#include<string.h>
void main()
{
char s[20],s1[20];
clrscr();
printf("enter a string \
n"); scanf("%s",s);
strcpy(s1,s);
strrev(s1);
if (strcmp(s,s1)==0)
printf("given string is palindrome \
n"); else
printf("the given string is not palindrome \n");
getch();}

OUTPUT:

Enter a string
DAD
Given string is palindrome
Enter a string
MOM
Given string is not a palindrome

RESULT:

Thus the string palindrome using C program has been executed and verified successfully.

EX.NO:2B) STRING CONCATENATION


18
AIM:

To concatenate the two strings using “C” program

ALGORITHM:

STEP 1: Start the program.


STEP 2: Declare the variable with respect data type char s1[20],s2[20]
STEP 3: Enter the String 1
STEP 4: Enter the String 2
STEP 5: Concatenate the two strings using strcat(s1,s2).
STEP 6: Display the concatenated string.
STEP 7: Stop

C PROGRAM:
19
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[20],s1[20];
clrscr();
printf("Enter the string 1:\n");
scanf("%s",&s);
printf("Enter the string 2:\n");
scanf("%s",&s1);
strcat(s, s1);
printf("The concatenated string is %s\n",s);
getch();
}

OUTPUT:

Enter the string 1:


C
Enter the string 2:
PROGRAM
The Concatenated string is CPROGRAM

RESULT:

Thus the string concatenation by using C program has been executed and verified successfully.

20
EX.NO:3A) STUDENT RESULTS CALCULATION USING STRUCTURES

AIM:

To write a C program to calculate the student’s results using structures.

ALGORITHM:

Step 1: Start the program.


Step 2: Create a structure named stud and initialize the variables.
Step 3: Obtain the student’s name and his marks.
Step 4: Create the conditions for changing it to grade.
Step 5: Obtain the result.
Step 6: Stop.

C PROGRAM:
21
#include<stdio.h>
#include<conio.h
> struct student
{
introllno;
char name[10];
int m1,m2,m3;
};
void main()
{
struct student s[10];
inttotal,i,n;
floatavg;
clrscr();
printf("Enter the number of students:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Student detail:\n");
printf("\nRoll no:\t");
scanf("%d",&s[i].rollno); printf("\
nName:\t"); scanf("%s",s[i].name);
printf("\nFirst subject mark:\t");
scanf("%d",&s[i].m1); printf("\
nSecond subject mark:\t");
scanf("%d",&s[i].m2); printf("\
nThird subject mark:\t");
scanf("%d",&s[i].m3);
total=s[i].m1+s[i].m2+s[i].m3;
avg=(s[i].m1+s[i].m2+s[i].m3)/3; printf("\nTOTAL=%d\
nAVERAGE=%f",total,avg);
if((s[i].m1>=50)&&(s[i].m2>=50)&&(s[i].m3>=50))
{
if(avg>=75)
{
printf("\n DISTINCTION");
}
else if((avg>=60)&&(avg<75))
{
printf("\n FIRST CLASS");
}
else if((avg>=50)&&(avg<60))
{
printf("\n SECOND CLASS");

22
}
}
else
{
printf("\n FAIL");
}
}
getch();
}

OUTPUT:
Enter the number of students:
1
Enter the Student details:
Roll no: 1416103
Name: RAVI
First subject mark: 92
Second subject mark: 93
Third subject mark: 94

Total=279
Average=93.000000
DISTINCTION

RESULT:

Thus the student result calculation using student result calculation using structure in
c program has been executed and verified successfully

EX.NO:3B) EMPLOYEE NET SALARY CALCULATION USING UNION


23
AIM:

To write a program to find employee net salary calculation Using union

ALGORITHM:

STEP 1: Start the program.


STEP 2: Create a union that include employee name, employee id no, basic
pay. STEP 3: Declare the variables HRA, DA, NETSALRY of respective data
type. STEP 4: Get the values for employee name, employee id no, basic pay.
STEP 5: Calculate the HRA,DA AND NETSALARY.
STEP 7: Print the values of employee name, employee id no, basic pay, HRA,DA &
NETSALARY respectively.
STEP 8: Stop

24
C PROGRAM:
#include<stdio.h>
#include<conio.h>

union employee
{
intempno;
char name[10];
float BP;
};
void main()
{
union employee E1;
floatHRA,DA,netsalary;
clrscr();
printf("enter the employee details:\
n"); printf("enter the employee
number:"); scanf("%d",&E1.empno);
printf("enter the employee name:");
scanf("%s",&E1.name); printf("\
nenter the basic pay:");
scanf("%f",&E1.BP);
HRA=E1.BP*0.2;
DA=E1.BP*0.5;
netsalary=HRA+DA+E1.BP;
printf("\nHRA=%f\nDA=%f\n Netsalary=%f",HRA,DA,netsalary);
getch();
}

OUTPUT:
25
enter the employee details:
enter the employee number:1416103
enter the employee name:RAVI
enter the basic pay:9000
HRA=1000.000000
DA=4500.000000
Netsalary-15300.000000

RESULT:
Thus the employee net salary calculation using union in C program as been executed and verified
successfully.

26
EX.NO:3C) TO FIND MAXIMUM NUMBER USING POINTER

AIM:

To write a C program to find the maximum number between two numbers using a pointer.

ALGORITHM:

STEP 1: Start the program.


STEP 2: Declare the variables fno,sno,*ptr1,*ptr2.
STEP 3: Get the values for first number and second number.
STEP 4: Compare two pointer values
STEP 5: Print the maximum number values.
STEP 7: Stop

C PROGRAM:

27
#include <stdio.h>
#include
<stdlib.h> void
main()
{
int fno,sno,*ptr1=&fno,*ptr2=&sno;
printf("\n\n Pointer : Find the maximum number between two numbers :\n");
printf(" Input the first number : ");
scanf("%d", ptr1);
printf(" Input the second number : ");
scanf("%d", ptr2);
if (*ptr1>*ptr2)
{
printf("\n\n %d is the maximum number.\n\n",*ptr1);
}
else
{
printf("\n\n %d is the maximum number.\n\n",*ptr2);
}
}

OUTPUT:

Pointer: Find the maximum number between two numbers:


Input the first number: 5
Input the second number: 6
6 is the maximum number.

RESULT:
Thus the maximum number using pointer in C program has been executed and verified
successfully.

28
EX.NO:3D) REVERSE A STRING USING POINTER

29
AIM:

To write a C program to print a string in reverse using a pointer.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the variables str1,revstr,*stptr,*rvptr,i..
STEP 3: Get the string for str1.
STEP 4: Reverse the string
STEP 5: Print the reversed string.
STEP 7: Stop

C PROGRAM:
30
#include <stdio.h>
int main()
{
char str1[50];
char revstr[50];
char *stptr =
str1;
char *rvptr = revstr;
int i=-1;
printf("\n\n Pointer : Print a string in reverse order :\n");
printf(" Input a string : ");
scanf("%s",str1);
while(*stptr)
{
stptr++;
i++;
}
while(i>=0)
{
stptr--;
*rvptr = *stptr;
rvptr++;
--i;
} *rvptr='\0';
printf(" Reverse of the string is : %s\n\n",revstr);
return 0;
}

OUTPUT:
Pointer: Print a string in reverse order:
Input a string: w3resource
Reverse of the string is: ecruoser3w

RESULT:
Thus the C program to print a string in reverse using a pointer has been executed and verified
successfully.

31
EX.NO:4) LARGEST NUMBERS USING DYNAMIC MEMORY ALLOCATION

AIM:

To write a C program to find the largest element using Dynamic Memory Allocation.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the variables I,n,*element
STEP 3: Get the value for total number of elements.
STEP 4: Allocate the memory for all elements
STEP 5: Display the result.
STEP 7: Stop

C PROGRAM:
32
#include <stdio.h>
#include
<stdlib.h> int
main()
{
int i,n;
float *element;
printf("\n\n Pointer : Find the largest element using Dynamic Memory Allocation :\n");
printf(" Input total number of elements(1 to 100): ");
scanf("%d",&n);
element=(float*)calloc(n,sizeof(float)); // Memory is allocated for 'n' elements
if(element==NULL)
{ printf(" No memory is allocated.");
exit(0);
} printf("\n");
for(i=0;i<n;++i) {
printf(" Number %d:
",i+1);
scanf("%f",element+i);
} for(i=1;i<n;++i) {
if(*element<*(element+i))
*element=*(element+i);
} printf(" The Largest element is : %.2f \n\n",*element);
return 0;
}

OUTPUT:
Pointer: Find the largest element using Dynamic Memory Allocation:
Input total number of elements (1 to 100): 5
Number 1: 5
Number 2: 7
Number 3: 2
Number 4: 9
Number 5: 8
The Largest element is: 9.00

RESULT: Thus the C program to find the largest element using Dynamic Memory Allocation
has been executed and verified successfully

33
EX.NO:5A) ARRAY IMPLEMENTATION OF

STACK AIM:

To write a C Program using array based implementation of stack.

ALGORITHM:
Step 1: Define a stack size.
Step 2: Read the stack operation.
Step 3: Read the stack element.
Step 4: Check the stack operation is Enqueue or Dequeue.
Step 5: If operation is enqueue then check the stack status.
 If stack status is over flow we can’t enqueue the element in to stack.
 Otherwise we can add the data into stack.
 Move top to next position.

PROGRAM:
34
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// A structure to represent a stack
struct Stack
{
int top;
unsigned capacity;
int* array;
};
// function to create a stack of given capacity. It initializes size of
// stack as 0
struct Stack* createStack(unsigned capacity)
{
struct Stack* stack = (struct Stack*) malloc(sizeof(struct
Stack)); stack->capacity = capacity;
stack->top = -1;
stack->array = (int*) malloc(stack->capacity * sizeof(int));
return stack;
}
// Stack is full when top is equal to the last index
int isFull(struct Stack* stack)
{ return stack->top == stack->capacity - 1; }

// Stack is empty when top is equal to -1


int isEmpty(struct Stack* stack)
{ return stack->top == -1; }

// Function to add an item to stack. It increases top by 1


void push(struct Stack* stack, int item)
{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}

// Function to remove an item from stack. It decreases top by


1 int pop(struct Stack* stack)
{
if (isEmpty(stack))
return INT_MIN;
return stack->array[stack->top--];
}
// Driver program to test above functions
int main()
{
struct Stack* stack = createStack(100);
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("%d popped from stack\n", pop(stack));
35
return 0;
}

OUTPUT:

10 pushed to
stack 20 pushed
to stack 30
pushed to stack
30 popped from
stack Top item is 20

RESULT:

Thus a C Program using array based implementation of stack was created and executed
successfully.

36
EX.NO:5B) ARRAY IMPLEMENTATION OF

QUEUE AIM:

To write a C Program using array based implementation of queue.


ALGORITHM:
Step 1: Initialize the queue variables front =0 and rear = -1
Step 2: Read the queue operation type.
Step 3: Check the queue operations status.
i). If it is Insertion then do the following steps
1. Check rear < queue_size is true increment the rear by one and read the queue element and
also display queue. otherwise display the queue is full.
2. Go to step2.
ii). If it is deletion then do the following steps
1. Check rear< front is true then display the queue is empty.
2. Move the elements to one step forward (i.e. move to previous index ).
3. Decreases the rear value by one (rear=rear-1).
4. Display queue
5. Go to step2.

37
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// A structure to represent a queue
struct Queue
{
int front, rear,
size; unsigned
capacity; int*
array;
};
// function to create a queue of given capacity.
// It initializes size of queue as 0
struct Queue* createQueue(unsigned capacity)
{
struct Queue* queue = (struct Queue*) malloc(sizeof(struct
Queue)); queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1; // This is important, see the
enqueue queue->array = (int*) malloc(queue->capacity *
sizeof(int)); return queue;
}
// Queue is full when size becomes equal to the capacity
int isFull(struct Queue* queue)
{ return (queue->size == queue->capacity); }
// Queue is empty when size is 0
int isEmpty(struct Queue*
queue)
{ return (queue->size == 0); }

void enqueue(struct Queue* queue, int item)


{
if (isFull(queue))
return;
queue->rear = (queue->rear + 1)%queue-
>capacity; queue->array[queue->rear] = item;
queue->size = queue->size + 1;
printf("%d enqueued to queue\n",
item);
}
int dequeue(struct Queue* queue)
{
if (isEmpty(queue))
return INT_MIN;
int item = queue->array[queue->front];
queue->front = (queue->front + 1)%queue-
>capacity; queue->size = queue->size - 1;
return item;
}
int front(struct Queue* queue)
{
if (isEmpty(queue))
38
return INT_MIN;
return queue->array[queue->front];
}

39
int rear(struct Queue* queue)
{
if (isEmpty(queue))
return INT_MIN;
return queue->array[queue->rear];
}
int main()
{
struct Queue* queue = createQueue(1000);
enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);
enqueue(queue, 40);
printf("%d dequeued from queue\n",
dequeue(queue)); printf("Front item is %d\n",
front(queue)); printf("Rear item is %d\n",
rear(queue));
return 0;
}

OUTPUT:
10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
40 enqueued to queue
10 dequeued from
queue Front item is 20
Rear item is 40

RESULT:
Thus the C program for array based implementation of Queue has been executed and verified
successfully

40
6. LINKED LIST IMPLEMENTATION OF STACK AND QUEUE

41
EX.NO:6A) LINKED LIST IMPLEMENTATION OF

STACK AIM:

To write a C Program using linked list implementation of stack.

ALGORITHM:
Step 1: create a list.
i) Create a new empty node top.
ii) Read the stack element and store it in top's data area.
iii) Assign top's link part as NULL (i.e. top->link=NULL).
iv) Assign temp as top (i.e.
temp=top). Step 2: Read next stack operation.
i) If it is Create then go to step1.
ii) If it is push then it process following steps
a) Check Main memory for node creation.
b) Create a new node top.
c) Read the stack element and store it in top's data area.
d) Assign top's link part as temp (i.e. top->link=temp).
e) Assign temp as top (i.e. temp=top).
iii) If it is pop then it process following steps
a) If top is NULL then display stack is empty.
b) Otherwise assign top as temp (i.e. top=temp, bring the top to top position)
c) Assign temp as temp's link. (i.e. temp=temp->link, bring the temp to top's
previous position).
d) Delete top from memory.
iv) If it is traverse then process the following steps
a) Bring the top to stack’s top position(i.e. top=temp)
b) Repeat until top becomes NULL
i) Display the top's data.
ii) Assign top as top's link (top=top->link).

42
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// A structure to represent a stack
struct StackNode
{
int data;
struct StackNode* next;
};

struct StackNode* newNode(int data)


{
struct StackNode* stackNode =
(struct StackNode*) malloc(sizeof(struct
StackNode)); stackNode->data = data;
stackNode->next =
NULL; return stackNode;
}
int isEmpty(struct StackNode *root)
{
return !root;
}
void push(struct StackNode** root, int data)
{
struct StackNode* stackNode =
newNode(data); stackNode->next = *root;
*root = stackNode;
printf("%d pushed to stack\n", data);
}
int pop(struct StackNode** root)
{
if (isEmpty(*root))
return INT_MIN;
struct StackNode* temp = *root;
*root = (*root)->next;
int popped = temp->data;
free(temp);
return popped;
}
int peek(struct StackNode* root)
{
if (isEmpty(root))
return INT_MIN;
return root->data;
}

int main()
{
struct StackNode* root = NULL;
push(&root, 10);
push(&root, 20);
push(&root, 30);
43
printf("%d popped from stack\n", pop(&root));
printf("Top element is %d\n", peek(root));
return 0;
}

OUTPUT:
10 pushed to
stack 20 pushed
to stack 30
pushed to stack
30 popped from
stack Top element is
20

RESULT:
Thus the C program for linked list based implementation of Stack has been executed and verified
successfully.

44
EX.NO:6B) LINKED LIST IMPLEMENTATION OF QUEUE

45
AIM:
To write a C Program using Linked List based implementation of Queue.

ALGORITHM:
Step 1: Initialize the queue variables front =0 and rear = -1
Step 2: Read the queue operation type.
Step 3: Check the queue operations status.
i). If it is Insertion then do the following steps
1. Check rear not equal to null is true increment the rear by one and read the queue
element and also display queue. otherwise display the queue is full.
2. Go to step2.
ii). If it is deletion then do the following steps
1. Check rear< front is true then display the queue is empty.
2. Move the elements to one step forward (i.e. move to previous index ).
3. Decreases the rear value by one (rear=rear-1).
4. Display queue
5. Go to step2.

46
PROGRAM:
#include <stdlib.h>
#include <stdio.h>

struct QNode
{
int key;
struct QNode *next;
};

struct Queue
{
struct QNode *front, *rear;
};

struct QNode* newNode(int k)


{
struct QNode *temp = (struct QNode*)malloc(sizeof(struct
QNode)); temp->key = k;
temp->next = NULL;
return temp;
}

struct Queue *createQueue()


{
struct Queue *q = (struct Queue*)malloc(sizeof(struct
Queue)); q->front = q->rear = NULL;
return q;
}

// The function to add a key k to q


void enQueue(struct Queue *q, int k)
{
// Create a new LL node
struct QNode *temp = newNode(k);

// If queue is empty, then new node is front and rear both


if (q->rear == NULL)
{
q->front = q->rear = temp;
return;
}

// Add the new node at the end of queue and change


rear q->rear->next = temp;
q->rear = temp;
}
// Function to remove a key from given queue q
struct QNode *deQueue(struct Queue *q)
{
// If queue is empty, return NULL.
if (q->front == NULL)
return NULL;
47
struct QNode *temp = q-
>front; q->front = q->front-
>next;
if (q->front ==
NULL) q->rear =
NULL;
return temp;
}
int main()
{
struct Queue *q = createQueue();
enQueue(q, 10);
enQueue(q, 20);
deQueue(q);
deQueue(q);
enQueue(q, 30);
enQueue(q, 40);
enQueue(q, 50);
struct QNode *n =
deQueue(q); if (n != NULL)
printf("Dequeued item is %d", n->key);
return 0;
}

OUTPUT:
Dequeued item is 30

RESULT:
Thus the C program for linked list based implementation of queue has been executed and verified
successfully.

48
EX.NO:7A) CHECKING BALANCED PARENTHESES IN AN EXPRESSION USING
STACK

AIM:
To write a C Program to check balanced parentheses in an expression using stack

ALGORITHM:
Step1: Start
Step 2: Declare a character stack S.
Step 3: Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and
if the popped character is the matching starting bracket then fine else parenthesis are not
balanced.
Step 4: After complete traversal, if there is some starting bracket left in stack then “not
balanced”

PROGRAM:
49
#include<stdio.h>
#include<stdlib.h
> #define bool int

/* structure of a stack node */


struct sNode
{
char data;
struct sNode *next;
};

/* Function to push an item to stack*/


void push(struct sNode** top_ref, int new_data);

/* Function to pop an item from stack*/


int pop(struct sNode** top_ref);

/* Returns 1 if character1 and character2 are matching left


and right Parenthesis */
bool isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}

/*Return 1 if expression has balanced Parenthesis */


bool areParenthesisBalanced(char exp[])
{
int i = 0;

/* Declare an empty character stack */


struct sNode *stack = NULL;

/* Traverse the given expression to check matching parenthesis */


while (exp[i])
{
/*If the exp[i] is a starting parenthesis then push it*/
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);

50
/* If exp[i] is an ending parenthesis then pop from stack and
check if the popped parenthesis is a matching pair*/
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{

/*If we see an ending parenthesis without a pair then return false*/


if (stack == NULL)
return 0;

/* Pop the top element from stack, if it is not a pair


parenthesis of character then there is a mismatch.
This happens for expressions like {(}) */
else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
}
i++;
}

/* If there is something left in expression then there is a starting


parenthesis without a closing parenthesis */
if (stack == NULL)
return 1; /*balanced*/
else
return 0; /*not balanced*/
}

/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
char exp[100] = "{()}[]";
if (areParenthesisBalanced(exp))
printf("Balanced \n");
else
printf("Not Balanced \n");
return 0;
}
void push(struct sNode** top_ref, int new_data)
{
struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow
n"); getchar();
exit(0);
}
51
new_node->data = new_data;
new_node->next =
(*top_ref); (*top_ref) =
new_node;
}
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
if (*top_ref == NULL)
{
printf("Stack overflow
n"); getchar();
exit(0);
}
else
{
top = *top_ref;
res = top-
>data;
*top_ref = top->next;
free(top);
return res;
}
}

OUTPUT:
Balanced

RESULT:
Thus the C program for checking balanced parentheses in an expression using stack has been
executed and verified successfully.
52
EX.NO:7B) INFIX TO POSTFIX CONVERSION USING STACK

53
AIM:
To write a ‘C’ program to implement stack and use it to convert infix to postfix expression.

ALGORITHM:
1. Start the program
2. Scan the Infix string from left to right.
3. Initialise an empty stack.
4. If the scannned character is an operand, add it to the Postfix string. If the scanned
character is an operator and if the stack is empty Push the character to stack.
 If the scanned character is an Operand and the stack is not empty,
compare the precedence of the character with the element on top of the
stack (topStack). If topStack has higher precedence over the scanned
character Pop the stack else Push the scanned character to stack. Repeat
this step as long as stack is not empty and topStack has precedence over
the character.
Repeat this step till all the characters are scanned.
5. (After all characters are scanned, we have to add any character that the stack may have
to the Postfix string.) If stack is not empty add topStack to Postfix string and Pop the
stack. Repeat this step as long as stack is not empty.
6. Return the Postfix string.
7. Terminate the program.

PROGRAM:

54
#include<stdio.h>
#include<string.h>
#define size 10
char stack[size];
int tos=0,ele;
void push();
char pop();
void show();
int isempty();
int isfull();
char infix[30],output[30];
int prec(char);
int main()
{
int i=0,j=0,k=0,length;
char temp;
printf("\nEnter an infix expression:");
scanf("%s",infix);
printf("\nThe infix expresson is %s",infix);
length=strlen(infix);
for(i=0;i<length;i++)
{
//Numbers are added to the out put QUE
if(infix[i]!='+' && infix[i]!='-' && infix[i]!='*' && infix[i]!='/' && infix[i]!='^' &&
infix[i]!=')' && infix[i]!='(' )
{
output[j++]=infix[i];
printf("\nThe element added to Q is:%c",infix[i]);
} else
{ if(tos==0) //If there are no elements in the stack, the operator is added to it
{
push(infix[i]);
printf("\nThe pushed element is:%c",infix[i]);
} else
{ //Operators or pushed or poped based on the order of
precedence if(infix[i]!=')' && infix[i]!='(')
{ if( prec(infix[i]) <= prec(stack[tos-1]) )
{
temp=pop();
printf("\n the poped element is :%c",temp);
output[j++]=temp;
push(infix[i]);
printf("\n The pushed element is :%c",infix[i]);
show();
}
else
{
push(infix[i]);
printf("\nThe pushed element is:%c",infix[i]);
show();
}
}
else
55
{
if(infix[i]=='(')
{
push(infix[i]);
printf("\nThe pushed-- element is:%c",infix[i]);
}
if(infix[i]==')')
{
temp=pop();
while(temp!='(')
{output[j++]=temp;
printf("\nThe element added to Q is:%c",temp);
//temp=pop();
printf("\n the poped element is :%c",temp);
temp=pop();}
}}}}
printf("\nthe infix expression is: %s",output);
}
while(tos!=0)
{
output[j++]=pop();
}
printf("the infix expression is: %s\n",output);
}void push(int ele)
{ stack[tos]=ele;
tos++;
}
char pop()
{
tos--;
return(stack[tos]);
}
void show()
{
int x=tos;
printf("--The Stack elements are....");
while(x!=0)
printf("%c, ",stack[--x]);
}
//Function to get the precedence of an operator
int prec(char symbol)
{
if(symbol== '(')
return 0;
if(symbol== ')')
return 0;
if(symbol=='+' || symbol=='-')
return 1;
if(symbol=='*' || symbol=='/')
return 2;
if(symbol=='^')
return 3;
return 0;
56
}

Output:

RESULT:

Thus the C program for infix to postfix conversion has been executed successfully.

57
EX.NO:8A) IMPLEMENTATION OF TREE

AIM:

To write a C program to implement tree.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the structure for node
STEP 3: Declare all variables
STEP 4: Recursively create new nodes
STEP 5: Display the order of nodes
STEP 7: Stop

C PROGRAM:
58
#include <stdio.h>
#include
<stdlib.h> struct
node {
int data;
struct node* left;
struct node*
right;
};
struct node* createNode(value){
struct node* newNode = malloc(sizeof(struct
node)); newNode->data = value;
newNode->left = NULL;
newNode->right =
NULL; return
newNode; }
struct node* insertLeft(struct node *root, int value)
{ root->left = createNode(value);
return root->left; }
struct node* insertRight(struct node *root, int value)
{ root->right = createNode(value);
return root->right; }
int main(){
struct node *root = createNode(1);
insertLeft(root, 2);
insertRight(root, 3);
printf("The elements of tree are %d %d %d", root->data, root->left->data, root->right->data);
}

OUTPUT:
123

RESULT:
Thus the C program for implementation of tree has been executed successfully.

59
EX.NO:8B) IMPLEMENTATION OF TREE TRAVERSAL

AIM:

To write a C program to implement tree traversal..

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the structure for node
STEP 3: Declare all variables
STEP 4: Recursively apply pre-order, post-order and in-order
STEP 5: Display the nodes
STEP 7: Stop

60
C PROGRAM:
#include <stdio.h>
#include
<stdlib.h> struct
node
{
int data;
struct node* left;
struct node*
right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct
node)); node->data = data;
node->left = NULL;
node->right =
NULL; return(node);
}
void printPostorder(struct node* node)
{
if (node ==
NULL) return;
// first recur on left
subtree
printPostorder(node->left);
// then recur on right
subtree printPostorder(node-
>right);
// now deal with the node
printf("%d ", node->data);
}

void printInorder(struct node* node)


{
if (node ==
NULL) return;

/* first recur on left child */


printInorder(node->left);

printf("%d ", node->data);

/* now recur on right child


*/ printInorder(node->right);
}

/* Given a binary tree, print its nodes in preorder*/


void printPreorder(struct node* node)
{
if (node ==
NULL) return;

61
/* first print data of node */
printf("%d ", node->data);

62
/* then recur on left sutree
*/ printPreorder(node->left);

/* now recur on right subtree


*/ printPreorder(node->right);
}

/* Driver program to test above functions*/


int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("\nPreorder traversal of binary tree is \n");
printPreorder(root);
printf("\nInorder traversal of binary tree is \n");
printInorder(root);
printf("\nPostorder traversal of binary tree is \n");
printPostorder(root);
getchar();
return 0;
}

OUTPUT:
Preorder traversal of binary tree is
12453
Inorder traversal of binary tree is
42513
Postorder traversal of binary tree is
45231

RESULT:

Thus the C program for implementation of tree traversal has been executed successfully.

63
EX.NO:9) IMPLEMENTATION OF BINARY SEARCH TREE

AIM:

To write a C program to perform Insert, Delete, Search an element into a binary search tree.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the structure for node
STEP 3: Declare all variables
STEP 4: Recursively apply pre-order, post-order and in-order
STEP 5: Display the nodes
STEP 7: Stop

C PROGRAM:
64
#include<stdio.h>
#include<stdlib.h
> struct node
{
int data;
struct node* left;
struct node*
right;
};
struct node* createNode(value){
struct node* newNode = malloc(sizeof(struct
node)); newNode->data = value;
newNode->left = NULL;
newNode->right =
NULL;

return newNode;
}
struct node* insert(struct node* root, int data)
{
if (root == NULL) return createNode(data);

if (data < root->data)


root->left = insert(root->left, data);
else if (data > root->data)
root->right = insert(root->right, data);
return root;
}

void inorder(struct node* root)


{ if(root == NULL) return;
inorder(root->left);
printf("%d ->", root->data);
inorder(root->right);
}
int main(){
struct node *root =
NULL; root = insert(root,
8); insert(root, 3);
insert(root, 1);
insert(root, 6);
insert(root, 7);
insert(root, 10);
insert(root, 14);
insert(root, 4);
65
inorder(root);
}

66
OUTPUT:

1 ->3 ->4 ->6 ->7 ->8 ->10 ->14 ->

RESULT:

Thus the C program for implementation of binary search tree has been executed
successfully.

67
EX.NO:10A) IMPLEMENTATION OF LINEAR SEARCH

AIM:

To write a C program to perform linear search in one dimensional array.

ALGORITHM:
Step 1 Initialization Set i =1.
Step 2 Loop, Comparison
while ( i < = N)
{
if (k = ki) then
{
message : ‗‗successful search‘‘
display (k) go to step 4
}
else
Set i =i + 1
}
End of
loop.
Step 3 If no match
If (k = ki) then
message : "unsuccessful search".
Step 4 Finish Exit.

68
C PROGRAM:

69
#include<stdio.h>
#include<conio.h
> void main()
{
int a[10],i,n,m,c=0;
clrscr();
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array:
"); for(i=0;i<=n-1;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++)
{
if(a[i]==m)
{
c=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
else
printf("The number is found");
getch();
}

Output:

70
RESULT:

Thus the program has been executed successfully.

EX.NO:10B) IMPLEMENTATION OF BINARY SEARCH

AIM:
71
To Write a C program to perform Binary Search in one dimensional array.

ALGORITHM:
Step 1 Initialization. Set l = 1, u = N.
Step 2 Middle key, loop.
while (u > = l)
{
Set m=1.
if (K = km) then
{
Message : "successful
search". display (K).
}
else if (K > km)
Set l =m + 1.
else
Set u = m – 1.
}
End of loop.
Step 3 Return at the point of call.Return.

C PROGRAM:

72
#include<stdio.h>
#include<conio.h
> void main(){

int a[10],i,n,m,c=0,l,u,mid;
clrscr();

printf("Enter the size of an array: ");


scanf("%d",&n);

printf("Enter the elements in ascending order: ");


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

printf("Enter the number to be search: ");


scanf("%d",&m);

l=0,u=n-1;
while(l<=u){
mid=(l+u)/2;
if(m==a[mid]){
c=1;
break;
}
else if(m<a[mid]){
u=mid-1;
}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");

getch();
}

OUTPUT:

73
RESULT:

Thus the program has been executed successfully.

74
EX.NO:11A) BUBBLE SORT

AIM:

To write a C program to perform bubble sort for the given numbers.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the variables of respective datatype.
list[20],num,min,temp,i,j;=>int.
Step 3: Enter the number of elements(max.20).
Step 4: Read the value of num.
Step 5: Display enter the elements.
Step 6: for(i=0;i<num;i++) read the value of list[i].
Step 7:for(i=0;i<num-1;i++)then for(j=0;j<num-1-i;j++).if(list[j]>list[j+1]).
Step 8:do temp=list[j]. list[j]=list[j+1]. List[j+1]=temp.
Step 9:Display “after sorting elements are” for(i=0;i<num;i++)
Step 10:Display the elements present in the list[i].

75
PROGRAM:

#include<stdio.h>
#include<conio.h
> void main()
{
int list[20],num,min,temp,i,j;
clrscr();
printf("\n enter the number of elements(max.20) \t");
scanf("%d",&num);
printf("\n enter the
elements:"); for(i=0;i<num;i+
+) scanf("%d",&list[i]);
for(i=0;i<num-1;i++)
for(j=0;j<num-1-i;j++)
if(list[j]>list[j+1])
{
temp=list[j];
list[j]=list[j+1];
list[j+1]=temp;
}
printf("\n after sorting elements are:");
for(i=0;i<num;i++)
printf("%d \n",list[i]);
getch();
}
OUTPUT:

76
RESULT:

Thus a C program to perform the bubble sort for the given numbers is executed and verified
successfully.

EX.NO:11B) INSERTION SORT


77
AIM:

To write a program to implement insertion sort.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the structure for node
STEP 3: Declare all variables
STEP 4: Recursively apply pre-order, post-order and in-order
STEP 5: Display the nodes
STEP 7: Stop

78
PROGRAM:

#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++) {
scanf("%d", &array[c]);
}

for (c = 1 ; c <= n - 1; c++) {


d = c;
while ( d > 0 && array[d-1] > array[d])
{t = array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}

printf("Sorted list in ascending order:\n");


for (c = 0; c <= n - 1; c++) { printf("%d\
n", array[c]);
}
return 0;
}

OUTPUT:

79
RESULT:

Thus a C program to perform the insertion sort for the given numbers is executed and verified
successfully.

EX.NO:11C) QUICK SORT


80
AIM:

To write a program to implement quick sort.

ALGORITHM:
1. If n < = 1, then return.
2. Pick any element V in a[]. This is called the pivot.
3. Rearrange elements of the array by moving all elements xi > V right of V and all
elements xi < = V left of V. If the place of the V after re-arrangement is j, all elements with
value less than V, appear in a[0], a[1]........a[j – 1] and all those with value greater than V
appear in a[j + 1]........a[n – 1].
4. Apply quick sort recursively to a[0] . . . . a[j – 1] and to a[j + 1]........a[n – 1].

PROGRAM:

81
#include <stdio.h>
void quick_sort(int[],int,int);
int partition(int[],int,int);

int main()
{
int a[50],n,i;
printf("How many elements?");
scanf("%d",&n);
printf("\nEnter array
elements:"); for(i=0;i<n;i++)
scanf("%d",&a[i]);
quick_sort(a,0,n-1); printf("\
nArray after sorting:");

for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}

void quick_sort(int a[],int l,int u)


{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
}
}

int partition(int a[],int l,int u)


{
int v,i,j,temp;
v=a[l];
i=l;
j=u+1;

do
{
do
i++;

while(a[i]<v&&i<=u);

do
j--;
while(v<a[j]);

if(i<j)
{
temp=a[i];
a[i]=a[j];
74
a[j]=temp;
}
}while(i<j);

a[l]=a[j];
a[j]=v;
return(j);
}

OUTPUT:

RESULT:

Thus a C program to perform the quick sort for the given numbers is executed and verified
successfully.

EX.NO:11D) MERGE SORT

75
AIM:

To write a program to implement merge sort.

ALGORITHM:
1. If n < = 1, then return.
2. Pick any element V in a[]. This is called the pivot.
3. Rearrange elements of the array by moving all elements xi > V right of V and all
elements xi < = V left of V. If the place of the V after re-arrangement is j, all elements with
value less than V, appear in a[0], a[1]........a[j – 1] and all those with value greater than V
appear in a[j + 1]........a[n – 1].
4. Apply quick sort recursively to a[0] . . . . a[j – 1] and to a[j + 1]........a[n – 1].

76
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 5
void merge_sort(int, int);
void merge_array(int, int, int, int);
int arr_sort[MAX_SIZE];
int main() {
int i;
printf("Simple Merge Sort Example - Functions and Array\n");
printf("\nEnter %d Elements for Sorting\n", MAX_SIZE);
for (i = 0; i < MAX_SIZE; i++)
scanf("%d", &arr_sort[i]);

printf("\nYour Data :");


for (i = 0; i < MAX_SIZE; i++) {
printf("\t%d", arr_sort[i]);
}
merge_sort(0, MAX_SIZE - 1);
printf("\n\nSorted Data :");
for (i = 0; i < MAX_SIZE; i++) {
printf("\t%d", arr_sort[i]);
}
getch();
}

void merge_sort(int i, int j) {


int m;

if (i < j) {
m = (i + j) / 2;
merge_sort(i, m);
merge_sort(m + 1,
j);
// Merging two arrays
merge_array(i, m, m + 1, j);
}
}

void merge_array(int a, int b, int c, int d) {


int t[50];
int i = a, j = c, k = 0;

while (i <= b && j <= d) {


if (arr_sort[i] <
arr_sort[j]) t[k++] =
arr_sort[i++]; else
t[k++] = arr_sort[j++];
}

//collect remaining elements


while (i <= b)
t[k++] = arr_sort[i++];
77
while (j <= d)
t[k++] = arr_sort[j++];

for (i = a, j = 0; i <= d; i++, j++)


arr_sort[i] = t[j];
}

OUTPUT:

Enter 5 Elements for Sorting


67
57
45
32
13

Your Data : 67 57 45 32 13

Sorted Data : 13 32 45 57 67

RESULT:

Thus a C program to perform the merge sort for the given numbers is executed and verified
successfully.

EX.NO:12) IMPLEMENT HASHING WITH LINEAR PROBING


78
AIM:

To write a program to implement Hashing with Linear Probing.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the structure for node
STEP 3: Declare all variables
STEP 4: Recursively apply pre-order, post-order and in-order
STEP 5: Display the nodes
STEP 7: Stop

79
PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
void main()
{
int a[MAX],num,key,i;
char ans;
int create(int);
void linear_prob(int [],int,int),display(int []);
clrscr();
printf("\n Collision Handling By Linear Probing");
for(i=0;i<MAX;i++)
a[i]=-1;
do
{
printf("\n Enter the Number ");
scanf("%d",&num);
key=create(num);
linear_prob(a,key,num);
printf("\n Do U Wish to Contiue?(Y/N");
ans=getch();
}
while(ans=='y');
display(a);
getch();
}
int create(int num)
{
int key;
key=num%10;
return key;
}
void linear_prob(int a[MAX],int key,int num)
{
int flag,i,count=0;
void display(int a[]);
flag=0;
if(a[key]==-1)
a[key]=num;
else
{ i=
0;
while(i<MAX)

80
{
if(a[i]!=-1)
count++;
i++;
}
if(count==MAX)
{ printf("\n\n Hash Table is Fu;;");
display(a);
getch();
exit(1);
}
for(i=key+1;i<MAX;i+
+) if(a[i]==-1)
{ a[i]=num;
flag=1;
break;
}
for(i=0;i<key&&flag==0;i++)
if(a[i]==-1)
{
a[i]=num;
flag=1;
break;
}}}
void display(int a[MAX])
{ int i;
printf("\n\n The HAsh Table is....\n");
for(i=0;i<MAX;i++)
printf("\n %d %d",i,a[i]);
}

OUTPUT:
81
RESULT: Thus the program has been executed successfully.

82
Ex. No. 13) Implementation of AVL tree

Aim:
To Implement Insertion in AVL Trees

Algorithm:
Step 1: Create a class AVL tree and declare all its member variables and functions
Step 2: Get the user option if tge choice is 1, create a binary tree, with the values and
considering the Balance factor
Step 3:The balance factor=no of left child-no of right child
Step4:If the balance factor is not equal to 1, 0,-1 then we have to rotate the tree one time left or
right or Double rotate
Step5:If the option is 2, display the tree contents in preorder and postorder formats
Step 6:If the option is 3, get the element to be searched and display whether the element is
present or Not.
Step 7: If the option is 4, exit the program

Program:
#include<conio.h>
#include<stdio.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 *);

83
node *RL(node *);

int BF(node *);


void 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("\
nEnter Your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1:printf("\nEnter no.of elements :");
scanf("%d",&n);
printf("\n Enter tree data
:"); root=NULL;
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("\nInorder sequence :\
n"); inorder(root);
break;
}

}while(op!=5);

84
}
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
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);
85
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);
}
else
{
//data to be deleted is found
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);
86
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;
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)
{
87
T->left=rotateleft(T->left);
T=rotateright(T);

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

OUTPUT:
89
1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:

Enter Your Choice:1

Enter no. of elements:4

Enter tree data:7 12 4 9

1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:

Enter Your Choice:4

Preorder sequence:
7(Bf=-1)4(Bf=0)12(Bf=1)9(Bf=0)

Inorder sequence:
4(Bf=0)7(Bf=-1)9(Bf=0)12(Bf=1)

1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:

Enter Your Choice:3

Enter a data:7

1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:

Enter Your Choice:4

Preorder sequence:
9(Bf=0)4(Bf=0)12(Bf=0)

Inorder sequence:
4(Bf=0)9(Bf=0)12(Bf=0)

90
1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:

Enter Your Choice:5

RESULT:
Thus the C program To Implement Insertion in AVL Trees was written and verified.

91
Ex. No. 14 IMPLEMENTATION OF MINIMUM SPANNING TREE USING

PRIM’S ALGORITHM

Aim:
To Implement Prim’s algorithm using priority queues to find MST of an undirected graph

Algorithm:
Step 1: Create the class prim with all its member variables and member functions.

Step 2: Get the total number of nodes in the graph

Step 3: Get the cost for every edges between the vertices of the graph

Step 4: Assign the lowest cost edges, to form a path from the first nodes to the last vertex

Of the graph

Step 5: Display the minimum cost spanning tree for the graph with the path

Step 6: Produce the total minimum cost.

92
Program:
/*prims alg prg*/

#include<iostream.h>

#include<conio.h>

#include<process.h>

float lcost[100],a[100][100];

int closest[100],i,j,k,min,n;

int v1,v2,wt,c=0;

class prim

public:

void get_mat()

cout<<"Enter the No of Vertices:";

cin>>n;

cout<<"enter 1000 for no path \n";

cout<<"enter weighted

matrix"<<endl; for(i=1;i<=n;i++)

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

cout<<"cost between the edge\t"<<i<<","<<j<<":\t";

cin>>a[i][j];

}//inner for

}//outer for

}//fn

void prim1()

93
for(i=2;i<=n;i++)

lcost[i]=a[1][i];

closest[i]=1;

cout<<"minimum cost spanning tree edges are"<<endl;

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

min=lcost[2];

k=2;

for(j=3;j<=n;j++)

if(lcost[j]<min)

min=lcost[j];

k=j;

c=c+min; cout<<"("<<closest[k]<<","<<k<<")"<<"\

t"<<"cost="<<min<<"\t"; lcost[k]=2000;

for(j=2;j<=n;j++) if((a[k]

[j]<lcost[j])&&(lcost[j]<2000))

lcost[j]=a[k][j];

closest[j]=k;

cout<<"\n";

94
}//outer for

cout<<"\n\nWeight of minimum cost spanning tree :"<<c;

getch();

};

void main()

clrscr();

int ch;

prim p;

do

cout<<"\n1.get\n2.find path with minimum cost\n3.exit\nenter ur choice\n";

cin>>ch;

switch(ch)

case 1:

p.get_mat();

break;

case 2:

p.prim1();

break;

case 3:

exit(0);

break;

}//switch

}while(ch<=3);//do

getch();

95
}//main

OUTPUT:

1. Insert

2. Path with minimum cost

3. Exit

Enter the Choice:

Enter the no of vertices: 5

Enter the cost between the edge 1,1:1000

Enter the cost between the edge 1,2:1

Enter the cost between the edge 1,3:2

Enter the cost between the edge 1,4:2

Enter the cost between the edge 1,5:1000

Enter the cost between the edge 2,1:1

Enter the cost between the edge 2,2:1000

Enter the cost between the edge 2,3:1000

Enter the cost between the edge 2,4:3

Enter the cost between the edge 2,5:1000

Enter the cost between the edge 3,1:2

Enter the cost between the edge 3,2:1000

Enter the cost between the edge 3,3:1000

Enter the cost between the edge 3,4:5

Enter the cost between the edge 3,5:6

Enter the cost between the edge 4,1:2

Enter the cost between the edge 4,2:3

Enter the cost between the edge 4,3:5

96
Enter the cost between the edge 4,4:1000

Enter the cost between the edge 4,5:4

Enter the cost between the edge 5,1:1000

Enter the cost between the edge 5,2:1000

Enter the cost between the edge 5,3:6

Enter the cost between the edge 5,4:4

Enter the cost between the edge 5,5:1000

Enter your

choice:2 Edges are

(1,1) cost=1

(1,3) cost=2

(1,4) cost=2

(4,5) cost=4

weight of minimum spanning tree:9

RESULT:

Thus the C program To Implement Prim’s algorithm using priority queues to find MST of
an undirected graph was written and executed successfully.

97

You might also like