DS LAB Manual
DS LAB Manual
(Autonomous)
(Approved by AICTE, New Delhi, Permanently Affiliated to JNTU Kakinada,
Accredited by NBA & Accredited by NAAC with A grade)
Course Objectives:
The objectives of Data Structures are
Course Outcomes:
By the end of the lab, the student,
Able to implement the code for all basic algorithms like searching, sorting etc
Able to write code for linear data structures like stacks, queues and linked list
Able to design and develop non-linear data structures like trees and graphs
Able to develop efficient modular programming
Exercise 1: Write recursive program which computes the nth Fibonacci number, for appropriate
values of n. Analyze behavior of the program Obtain the frequency count of the statement for
various values of n.
Exercise 2: Write recursive program for the following
a) Write recursive and non-recursive C program for calculation of Factorial of an integer
b) Write recursive and non-recursive C program for calculation of GCD (n, m)
c) Write recursive and non-recursive C program for Towers of Hanoi : N disks are to be
transferred from peg S to peg D with Peg I as the intermediate peg.
Exercise 3:
a) Write C program that use both recursive and non-recursive functions to perform Linear
search for a Key value in a given list.
b) Write C program that use both recursive and non-recursive functions to perform Binary
search for a Key value in a given list.
c) Write C program that use both recursive and non-recursive functions to perform Fibonacci
search for a Key value in a given list.
Exercise 4
a) Write C program that implement Bubble sort, to sort a given list of integers in ascending
order
b) Write C program that implement Quick sort, to sort a given list of integers in ascending
order
c) Write C program that implement Insertion sort, to sort a given list of integers in ascending
order
Exercise 5:
a) Write C program that implement heap sort, to sort a given list of integers in ascending order
b) Write C program that implement radix sort, to sort a given list of integers in ascending order
c) Write C program that implement merge sort, to sort a given list of integers in ascending
order
Exercise 6:
a) Write C program that implement stack (its operations) using arrays
b) Write C program that implement stack (its operations) using Linked list
Exercise 7:
a) Write a C program that uses Stack operations to Convert infix expression into postfix
expression a) Write C program that implement Queue (its operations) using arrays.
b) Write C program that implement Queue (its operations) using linked lists
Exercise 8:
a) Write a C program that uses functions to create a singly linked list
b) Write a C program that uses functions to perform insertion operation on a singly linked list
c) Write a C program that uses functions to perform deletion operation on a singly linked list
Exercise 9: a) Adding two large integers which are represented in linked list fashion.
b) Write a C program to reverse elements of a single linked list.
c) Write a C program to store a polynomial expression in memory using linked list
d) Write a C program to representation the given Sparse matrix using arrays.
e) Write a C program to representation the given Sparse matrix using linked list
Exercise10:
a) Write a C program to Create a Binary Tree of integers
b) Write a recursive C program for Traversing a binary tree in preorder, inorder and postorder.
c) Write a non-recursive C program for Traversing a binary tree in preorder, inorder and post-
order.
d) Program to check balance property of a tree.
Exercise 11:
a) Write a C program to Create a BST
b) Write a C program to insert a node into a BST.
c) Write a C program to delete a node from a BST.
Ex. No: 1 FIBONACCI NUMBER USING RECURSION
Aim: Write recursive programme which computes the nth Fibonacci number, for appropriate
values of n.
Analyze behavior of the programme Obtain the frequency count of the statement for various
values of n.
Algorithm:
/* Fibonacci_series */
Input: Read n value
Output: Prints the nth Fibonacci term
Step1: Start
Step2: Read n value for computing nth term in Fibonacci series
Step3: call sub-routine Fibonacci (n)
Step4: Print the nth term
Step5: End
Program:
/* Finding nth Fibonacci number using recursion */
#include <stdio.h>
#include <conio.h>
int Fibonacci(int n)
{
if(n==0)
return 0;
if(n==1)
return 1;
else
return Fibonacci(n-1)+Fibonacci(n-2);
}
void main()
{
int n;
clrscr();
printf("\n Enter a number :");
scanf("%d",&n);
printf("\n nth Fibonacci value=%d",Fibonacci(n));
getch();
}
OUTPUT:
Ex. No: 2(a) FACTORIAL USING RECURSION
Aim: Write recursive C programme for calculation of Factorial of an integer
Algorithm:
/* factorial_recursive */
Input: integer n
Output: factorial of given number
Step 1: Start
Step 2: read n
Step 3: call sub-routine fact_rec(n)
Step 4: print factorial
Step 5: Stop
Algorithm for sub routine fact_rec(int n)
Step 1: begin
Step 2: f 1
Step 3: if n = 0 go to step 4 else go to step 5
Step 4: return 1
Step 5: f n* fact_rec(n-1)
Step 6: return f
Program:
#include <stdio.h>
#include <conio.h>
/* compute n! recursively */
int fact_rec(int n)
{
/* error check */
if (n < 0)
return(-1);
/* base case */
if (n == 0)
return(1);
/* recursion */
return(n * fact_rec(n-1));
}
void main()
{
int n;
clrscr();
printf("\n Enter a number :");
scanf("%d",&n);
printf("\n Factorial value=%d",fact_rec(n));
getch();
}
Output:
EX. NO: 2(B) GCD USING RECURSION
Output:
EX. NO: 2(C) TOWERS OF HANOI USING RECURSION
Aim: Write recursive C programme for Towers of Hanoi: N disks are to be transferred from
peg S to peg D with Peg I as the intermediate peg.
Algorithm:
/* Towers of Hanoi recursive */
Input: integer n
Output:
Step 1: Start
Step 2: read n value as the no. of disks
Step 3: call sub-routine toh (n, S, D, I)
Step 4: Stop
Algorithm for sub routine toh (n, source, dest, aux)
Step 1: begin
Step 2: if n = 1 then
Step 3: Move the single disk from source to dest and stop
Step 4: else
Step 5: Move the top n-1 disks from S to I, using D as auxiliary
Call sub routine toh (n-1, source, aux, dest)
Step 6: Move the remaining disk from S to D
Step 7: Move the n-1 disks from I to D, using S as auxiliary
Call sub routine toh (n-1, aux, dest, source)
Step 8: end
Program:
#include<stdio.h>
#include<conio.h>
/* source peg----s, destination peg --- d
Intermediate peg----t */
void tower(int n,char s,char d, char t)
{
if(n==1)
{
printf("\nMove disk %d from %c to %c",n,s,d);
return;
}
else
/* Move top n-1 disks from S to I, using D as auxiliary */
tower(n-1,s,t,d);
/* Move remaining disk from S to D */
printf("\nMove disk %d from %c to %c",n,s,d);
/* Move n-1 disk from I to D usiong S as auxiliary */
tower(n-1,t,d,s);
}
void main()
{
int n;
clrscr();
printf("Enter number of disks ");
scanf("%d",&n);
tower(n,'S','D','I');
getch();
}
Output:
EX. NO: 3(A) Linear Search Using Recursive & Non- Recursive Functions
Aim: Write C programs that use both recursive and non recursive functions to perform
Linear search for a Key value in a given list.
Algorithm:
/* Linear_ Search */
Input: n, ser_val, a[50]
Output: found = true and loc = position of item if the search is successful;
otherwise, found is false.
Step 1: Start
Step 2: read n // no of elements
Step 3: repeat step 4 until for i: 0 to n
Step 4: read a[i]
Step 5: read ser_val // search value
Step 6: read the choice to use the either recursive or non-recursive function
Step 7: if ch=1 then do the following otherwise go to step8
Step7.1: res call sub routine Linear_search(a, n, ser_val)
Step7.2: if res! = -1
Step7.3: print ‘ser_val found at by non recursive function = res’
Step 7.4: else
Step 7.5: print ‘not found in list’
Step8: if ch=2 then do the following otherwise go to step9
Step 8.1: res call sub routine Linear_search_rec(a, n, ser_val)
Step 8.2: if res! = -1
Step 8.3: print ‘ser_val found at by recursive function = res’
Step 8.4: else
Step 8.5: print ‘not found in list’
Step 9: print ‘invalid choice’
Step10: Stop
Algorithm for sub-routine Linear_search(int a[], int n, int ser_val)
Step 1: begin
Step 2: repeat steps 3 to 7 until for i: 0 to n
Step 3: if a[i] = ser_val then go to step4 else go to step6
Step 4: return (i)
Step 5: break and goto step7
Step 6: return (-1)
Step 7: end
Algorithm for sub-routine Linear_search_rec(int a[], int n, int ser_val)
Step 1: begin
Step 2: if n==0 then go to step3 else go to step4
Step 3: return -1
Step 4: if a[n-1] = ser_val then go to step5 else go to step6
Step 5: return (n-1)
Step 6: return (Linear_search_rec(a, n1, ser_val)
Program:
/* Linear search using recursive and non-recursive functions */
#include<stdio.h>
#include<conio.h>
int Linear_search( int array[], int length, int value);
int Linear_search_rec( int array[], int length, int value);
int main()
{
int a[20],i,n,x,xloc=-1,ch;
clrscr();
printf("Enter array size\n");
scanf("%d",&n);
printf("Enter any %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the element you want to search for\n");
scanf("%d",&x);
printf("Which function you want to use\n");
printf("1. Non-recursive\n2. recursive\n");
printf("Enter the choice\t:");
scanf("%d",&ch);
switch(ch)
{
case 1:
xloc = Linear_search(a,n,x);
if(xloc!=-1)
printf("%d is found at %d location by non recursive function\n",x, xloc+1);
else
printf("%d is not found in list",x);
break;
case 2:
xloc = Linear_search_rec(a,n,x);
if(xloc!=-1)
printf("%d is found at %d location by recursive function.\n",x, xloc+1);
else
printf("%d is not found in list",x);
break;
default:printf("Invalid choice.");
}
getch();
}
Output:
Ex. No: 3(B) Binary Search Using Recursive & Non- Recursive Functions
Aim: Write C programs that use both recursive and non recursive functions to perform
Binary search for a Key value in a given list.
Algorithm:
/* Binary_ Search */
Input: n, ser_val, a[50]
Output: found = true and loc = position of item if the search is successful;
otherwise, found is false.
Step 1: Start
Step 2: read n // no of elements
Step 3: repeat step 4 until for i: 0 to n
Step 4: read a[i]
Step 5: read ser_val // search value
Step 6: low0, highn-1
Step 7: read the choice to use either recursive or non-recursive functions
Step 8: if ch=1 then do the following otherwise go to step8
Step8.1: res call sub routine Binary_search(a, low, high, ser_val)
Step 8.2: if res ! = -1
Step 8.3: print ‘ser_val found at by non recursive function = res’
Step 8.4: else
Step 8.5: print ‘not found in list’
Step9: if ch=2 then do the following otherwise go to step9
Step9.1: res call sub routine Binary_search_rec(a, low, high, ser_val)
Step 9.2: if res != -1
Step 9.3: print ‘ser_val found at by recursive function = res’
Step 9.4: else
Step 9.5: print ‘not found in list’
Step 10: print ‘invalid choice’
Step 11: Stop
Algorithm for sub-routine Binary_search(int a[], int low, int high, int ser_val)
Step 1: begin
Step 2: repeat steps 3 to 10 until low <= high
Step 3: mid(low+high)/2
Step 4: if a[mid] = ser_val then go to step5 else go to step7
Step 5: locmid
Step 6: return loc and break
Step 7: if ser_val < a[mid] then go to step8 else go to step9
Step 8: highmid-1 and go to step 10
Step 9: lowmid+1
Step 10: end
Algorithm for sub-routine binary_search_rec(int a[], int lo, int high, int ser_val)
Step 1: begin
Step 2: if high<low then go to step3 else go to step4
Step 3: return -1;
Step 4: midlow + ((high-low)/2);
Step 5: if a[mid] > ser_val then go to step6 else go to step7
Step 6: return Binary_search_rec (a, low, mid-1, ser_val)
Step 7: if a[mid] < ser_val then go to step8 else go to step10
Step 8: return Binary_search_rec (a, mid+1, high, ser_val)
Step 9: return mid;
Step 10: end
Program:
#include<stdio.h>
#include<conio.h>
int Binary_search(int a[], int low, int high, int x);
int Binary_search_rec(int a[], int low, int high, int x);
void main()
{
int a[20],i,n,x,xloc=-1;
int low,high,ch;
clrscr();
printf("Enter array size\n");
scanf("%d",&n);
printf("Enter any %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the element you want to search for\n");
scanf("%d",&x);
low = 0;high = n-1;
printf("Which function you want to use\n");
printf("1. Non-recursive\n2. recursive\n");
printf("Enter the choice\t:");
scanf("%d",&ch);
switch(ch)
{
case 1:
xloc = Binary_search(a,low,high,x);
if(xloc!=-1)
printf("%d is found at location %d by non recursive function\n",x, xloc+1);
else
printf("%d is not found in list",x);
break;
case 2:
xloc = Binary_search_rec(a,low,high,x);
if(xloc!=-1)
printf("%d is found at location %d by recursive function.\n",x, xloc+1);
else
printf("%d is not found in list",x);
break;
default:printf("Invalid choice.");
}
getch();
}
Aim: Write C programs that use both recursive and non recursive functions to perform Fibonacci
search for a Key value in a given list.
Algorithm: /* Fibonacci search recursive and non-recursive */
Program:
#include<process.h>
#include<stdio.h>
#include<conio.h>
int a[100];
int l[100];
void non_recurs();
void recurs();
void Fibsearch(int, int, int, int, int);
void main()
{
int ch;
printf("enter your choice for reursive(1) or non-recursive(2) for fibonaci search");
scanf("%d",&ch) ;
switch(ch)
{
case 1: recurs();break;
case 2: non_recurs();break;
}
}
/*fibonacii search non-recurcive*/
void non_recurs()
{
int n,i,k,p,q,r,m,t,f0=0,f1=1,f2=1,item, found=0;
/*keep first 3 elements of the fibonacii series in array a*/
a[0]=0;
a[1]=1;
a[2]=1;
k=2;
/*scan the size of the new list 'n'*/
printf("\nit is a non-recursive program for fibonacii search");
printf("\nEnter the size of the array");
scanf("%d",&n);
a[0]=0;
a[1]=1;
a[2]=1;
k=2;
printf("it is a recursive program for fibonacii search");
printf("Enter the size of the array");
scanf("%d",&n);
printf("\nEnter the elements of the array ");
for(i=0; i<n; i++)
scanf("%d",&l[i]);
printf("\nEnter the item to be searched");
scanf("%d",&item);
while(a[k]<n)
{
f0=f1;
f1=f2;
f2=f1+f0;
k++;
a[k]=f2;
}
p=a[k-1];
q=a[k-2];
r=a[k-3];
m=item+1-(p+q);
if(item > l[p])
p=p+m;
Fibsearch(n,item,p,q,r);
}
Output:
EX. NO: 4(A) BUBBLE SORT
Aim: Write C programs that implement Bubble sort, to sort a given list of integers in
ascending order
Algorithm:
/* Bubble_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array
Step 1: Start
Step 2: read no of elements n
Step 3: repeat step 4 for i: from 0 to n-1
Step 4: read a[i]
Step 5: repeat step 6 for i: from 0 to n-1
Step 6: repeat step 7 for j: from 0 to n-1-i
Step 7: if a[j+1] < a[j] perform steps 8 to 10
Step 8: temp a[j+1]
Step 9: a[j+1] a[j]
Step 10: a[j] temp
Step 11: repeat step 12 for i: from 0 to n-1
Step 12: print a[i]
Step 13: Stop
Program:
Output:
EX. NO: 4 (B) QUICK SORT
Aim:
Write C programs that implement Quick sort, to sort a given list of integers in ascending order
Algorithm:
/* Quick_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array
Step 1: Start
Step 2: read n // n number of elements
Step 3: repeat step4 for i: from 0 to n-1
Step 4: read a[i]
Step 5: call sub routine quick_sort(a, 0, n-1)
Step 6: repeat step7 for i: from 0 to n-1
Step 7: print a[i]
Step 8: Stop
#include<stdio.h>
#include<conio.h>
int i,j,n,pivot,a[20];
void quick(int a[],int left,int right);
void swap(int a[],int i,int j);
void main()
{
int n,a[20];
clrscr();
printf("\n\nQUICK SORT");
printf("\n\nEnter the array size");
scanf("%d",&n);
printf("\n\nEnter the element\n\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quick(a,0,n-1);
printf("\n\nThe sorted list is \n\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}
void quick(int a[],int first,int last)
{
if(first<last)
{
pivot=a[first];
i=first;
j=last;
while(i<j)
{
while(a[i]<=pivot&&i<last)
i++;
while(a[j]>=pivot&&j>first)
j--;
if(i<j)
swap(a,i,j);
}
swap(a,first,j);
quick(a,first,j-1);
quick(a,j+1,last);
}
}
void swap(int a[],int i,int j)
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
Output:
EX. NO: 4 (C) INSERTION SORT
Aim:
Write C programs that implement Insertion sort, to sort a given list of integers in ascending
order
Algorithm:
/* Insertion_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array
Step 1: Start
Step 2: read no of elements n
Step 3: repeat step 4 for i: from 0 to n-1
Step 4: read a[i]
Step 5: repeat steps 6 to 10 for j: from 1 to n-1
Step 6: key a[i]
Step 7: j i-1
Step 8: repeat step 9 while j >= 0 and a[j] > x
Step 9: a[j+1] a[j--]
Step 10: a[j+1] x
Step 11: for i: 0 to n-1
Step 12: print a[i]
Step 13: Stop
Program:
#include <stdio.h>
#include<conio.h>
void main()
{
void insertion_sort(int [],int);
int A[100];
int x=0,n=0;
int key,i,j;
clrscr();
printf("******INSERTION SORT******");
printf("\n\nENTER THE LIMIT : ");
scanf("%d",&n);
printf("\n\nENTER THE ELEMENTS ONE BY ONE\n\n");
for(x=0;x<n;x++)
scanf("%d",&A[x]);
printf("\n\nNON SORTED LIST\n\n");
for(x=0;x<n;x++)
{
printf("\t%d",A[x]);
}
for(j=1;j<n;j++)
{
key=A[j];
i=j-1;
while(A[i]>key && i>=0)
{
A[i+1]=A[i];
i--;
}
A[i+1]=key;
}
printf("\n\nSORTED LIST\n\n");
for(x=0;x<n;x++)
{
printf("\t%d",A[x]);
}
getch();
}
Output:
EX. NO: 5 (A) HEAP SORT
Aim: Write C programs that implement heap sort, to sort a given list of integers in
ascending order
BUILD_HEAP (A)
heap-size (A) ← length [A]
For i ← floor(length[A]/2) down to 1 do
Heapify (A, i)
HEAPSORT (A)
BUILD_HEAP (A)
for i ← length (A) down to 2 do
exchange A[1] ↔ A[i]
heap-size [A] ← heap-size [A] - 1
Heapify (A, 1)
end := count-1 //in languages with zero-based arrays the children are 2*i+1 and 2*i+2
while end > 0 do
(swap the root(maximum value) of the heap with the last element of the heap)
swap(a[end], a[0]) (put the heap back in max-heap order)
siftDown(a, 0, end- (decrease the size of the heap by one so that the previous
max value will stay in its proper placement)
end := end - 1
function heapify(a, count) is
(start is assigned the index in a of the last parent node)
start := count / 2 - 1
while start ≥ 0 do (sift down the node at index start to the proper place such
that all nodes below the start index are in heap order)
siftDown(a, start, count-1)
start := start - 1
(after sifting down the root all nodes/elements are in heap order)
while root * 2 + 1 ≤ end do (While the root has at least one child)
child := root * 2 + 1 (root*2 + 1 points to the left child)
swap := root (keeps track of child to swap with)
(check if root is smaller than left child)
if a[swap] < a[child]
swap := child
(check if right child exists, and if it's bigger than what we're currently swapping with)
if child+1 ≤ end and a[swap] < a[child+1]
swap := child + 1
(check if we need to swap at all)
if swap != root
swap(a[root], a[swap])
root := swap (repeat to continue sifting down the child now)
else
return
Program:
#include<stdio.h>
#include<conio.h>
void heapsort( int arr[], int count);
void makeheap( int arr[], int count);
int main()
{
int a[20],i,j,n,temp,k;
clrscr();
printf("Enter array size\n");
scanf("%d",&n);
printf("Enter any %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
makeheap( a,n)
heapsort(a,n ) ;
printf("After sorting, the element are\n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
getch();
return 0;
}
Output:
EX. NO: 5 (B) RADIX SORT
Aim: Write C programs that implement radix sort, to sort a given list of integers in ascending
order
Algorithm: /* Radix_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array
radixsort( L, n, r, d )
/* radix sort sorts a list L of n keys, each comprising d digits with radix r * */
Initialize each of the Q[0:r-1] linked queues representing the bins to be empty;
For i = d to 1 step -1 /* for each of the d passes over the list */
Sort the list L of n keys Ki=k1k2k3…..kd based on the digit i, inserting each of the keys K into
the linked queue Q [ ki ], 0 ≤ ki < r ; /* distribute the keys into Q [ 0 : (r-`) ] based on the
radix value of the digits */
Delete the keys from the queues Q [ 0: r-1 ] in order, and append the elements to the output
list L;
end;
Return ( L );
end radixsort.
Algorithm:
Step 1: set LARGE = large element in the array
Step 2: set NUM=total no of digits in the largest element of the array
Step 3: set DIGIT = NUM
Step 4: set PASS = 1
Step 5: repeat steps 6 to 12 while PASS <= NUM
Step 6: Initialize buckets
Step 7: set i=0
Step 8: repeate steps 9 to 11 while i<=n-1
Step 9: Set l=PASS-1 , position of number a[i] [0th position of number 123 is 3]
Step 10: put the number a[i] in the bucket l
Step 11: set i=i+1 [end of step 8 loop]
Step 12: set PASS=PASS+1 [end of step 5 loop]
Step 13: write all the numbers from the bucket in order
Step 14: stop.
Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void radix(int a[],int n,int m)
{
typedef struct node
{
int data;
struct node * next;
}NODE;
NODE * ptr,*start,*prev;
NODE *front[10], *rear[10];
int k=1,i,j,y,p;;
/*creating initial linked list*/
start=NULL;
for(i=0;i< n;++i)
{
ptr=(NODE *)malloc(sizeof(NODE));
ptr->data=a[i];
ptr->next=NULL;
if(start==NULL)
start=ptr;
else
prev->next=ptr;
prev=ptr;
}
/*radix sort*/
for(i=1;i<=m;++i)
{
for(j=0;j< 10;++j)
front[j]=NULL;
/*placing elements into queues*/
ptr=start;
while(ptr!=NULL)
{y=ptr->data/k %10;/*y is the digit*/
if(front[y]==NULL)
{
front[y]=ptr;
rear[y]=ptr;
}
else
{
rear[y]->next=ptr;
rear[y]=ptr;
}
ptr=ptr->next;
}
start=NULL;
for(j=0;j< 10;++j)
if(front[j]!=NULL)
{
if(start==NULL)
start=front[j];
else rear[p]->next=front[j];
p=j;
}
rear[p]->next=NULL;
k=k*10;
}
/*copying back to array*/
ptr=start;
for(i=0;i< n;++i,ptr=ptr->next)
a[i]=ptr->data;
}
void main()
{
int a[100],n,i,m;
char temp;
do
{
clrscr();
printf("===========================RADIX
SORT===========================================\n");
printf("ENTER NUMBER OF NUMBERS AND NUMBER OF DIGITS\n");
scanf("%d%d",&n,&m);
printf("ENTER ELEMENTS\n");
for(i=0;i< n;++i)
scanf("%d",&a[i]);
radix(a,n,m);
printf("SORTED LIST\n");
for(i=0;i< n;++i)
printf("%d ",a[i]);
printf("\nDO YOU wish to continue?[y/n]\n");
scanf("%c",&temp);
}while(temp=='y'|| temp=='Y');
printf("\n \n");
getch();
}
Output:
EX. NO: 5 (C) MERGE SORT
Aim: Write C programs that implement merge sort, to sort a given list of integers in
ascending order
Algorithm: /* Merge_ Sort */
Input: An integer n and a list of n elements stored in array elements a[0], . . . , a[n – 1]
Output: sorted array
Step 1: Start
Step 2: read no of elements n
Step 3: repeat step 4 for i: from 0 to n-1
Step 4: read a[i]
Step 5: call function merge_sort(a, 0, n-1)
Step 6: repeat step 9 while j >= 0 and a[j] > x
Step 7: print a[i]
Step 8: Stop
Program:
#include<stdio.h>
#include<conio.h>
void mergesort(int a[], int low, int high);
void merge(int a[], int low, int high, int mid);
int main()
{
int a[20],i,n;
clrscr();
printf("Enter array size\n");
scanf("%d",&n);
printf("Enter any %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort( a,0,n-1);
printf("After sorting, the element are\n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
return 0;
}
void mergesort(int a[], int low, int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,high,mid);
}
return;
}
void merge(int a[], int low, int high, int mid)
{
int i, j, k, c[50];
i=low;
j=mid+1;
k=low;
while((i<=mid)&&(j<=high))
{
if(a[i]<a[j])
{
c[k]=a[i];
k++;
i++;
}
else
{
c[k]=a[j];
k++;
j++;
}
}
while(i<=mid)
{
c[k]=a[i];
k++;
i++;
}
while(j<=high)
{
c[k]=a[j];
k++;
j++;
}
for(i=low;i<k;i++)
{
a[i]=c[i];
}
}
Output:
EX. NO: 6 (A) STACK USING ARRAY
Aim: Write C programs that implement stack (its operations) using arrays
Algorithm: /* Stack_Array */
Input: int a[size], top, i, ch
Output:
Define size 20
top = -1
Step 1: Start
Step 2: do
Step 3: print choice [1] push. [2] pop. [3] display. [4] exit
Step 4: read choice ch
Step 5: switch ch
Step 6: case 1: call sub-routine push()
Step 7: break
Step 8: case 2: call sub-routine pop()
Step 9: break
Step 10: case 3: call sub-routine disp()
Step 11: break
Step 12: case 4: break
Step 13: default: print invalid choice
Step 14: read choice
Step 15: while ch! = 4
Step 16: Stop
Algorithm for sub routine push()
Step 1: begin
Step 2: if top equal to size-1
Step 3: print ‘Stack over flow’
Step 4: else
Step 5: top top+1
Step 6: read a[top]
Step 7: end
Algorithm for sub routine pop()
Step 1: begin
Step 2: if top equal to -1
Step 3: print ‘stack under flow’
Step 4: else
Step 5: print ‘popped element is a[top]
Step 6: top top-1
Step 7: end
Algorithm for sub routine disp()
Step 1: begin
Step 2: if top equal to -1
Step 3: print ‘ Stack is empty’
Step 4: else
Step 5: repeat step 6 for: i from top to 0
Step 6: print a[i]
Step 7: end
Program:
#include<stdio.h>
#include<process.h>
#include<conio.h>
#define SIZE 3
int stack[SIZE], top=-1;
void push(int);
void pop(void);
int topmost(void);
void display();
void main()
{
int item, ch;
clrscr();
while(1)
{
printf("\n1.push");
printf("\n2.pop");
printf("\n3.Top ELEMENT");
printf("\n4.display");
printf("\n5.exit");
printf("\nEnter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the element to be pushed\n");
scanf("%d",&item);
push(item);
printf("\nPress enter");
getch();
break;
case 2: pop();
printf("\nPress enter");
getch();
break;
case 3: item=topmost();
printf("\n Topmost element is %d", item);
printf("\nPress enter");
getch();
break;
case 4: display();
printf("\nPress enter");
getch();
break;
default : exit(0);
}
}
}
void push(int i)
{
if(top==(SIZE-1))
{
printf("\nStack Overflow");
return;
}
top=top+1;
stack[top]=i;
}
void pop()
{
int i;
if(top==-1)
{
printf("\nStack Underflow");
return;
}
i=stack[top];
top=top-1;
printf("\nDeleted item is %d",i);
return;
}
int topmost()
{
return stack[top];
}
void display()
{
int i;
if(top==-1)
{
printf("\nStack is Empty");
return;
}
printf("\nContents of the stack are\n");
for(i=top;i>=0;i--)
printf("%d\t",stack[i]);
}
Output:
EX. NO: 6 (B) STACK USING LINKED LISTS
Aim: Write C programs that implement stack (its operations) using Linked list
default : exit(0);
}
}
}
void push( int x)
{
struct stack *p;
p = getnode(x );
/* checking for an empty stack */
if ( top == NULL)
{
top = p;
}
else
{
p->next = top;
top = p;
}
} /* end of push( )*/
void display()
{
struct stack *p;
p=top;
if (top == NULL)
{
printf("\nStack is Empty");
return;
}
printf("\nContents of the stack are\n");
for(p=top; p!= NULL; p=p->next)
printf("%d\t",p->info);
}
Output:
EX. NO: 7(A) CONVERT INFIX EXPRESSION INTO POSTFIX EXPRESSION
Aim: Write a C program that uses Stack operations to convert infix expression into postfix
expression
Algorithm: /* Infix_to_Postfix */
Input:
Output:
Define size 20
declare char a[size], integer top -1
Step 1: Start
Step 4: declare integer i, j0, n,u,v; char infix[size], postfix[size]
Step 5: read infix expression
Step 6: nstring length (infix)
Step 7: repeat steps 8 to 20 for i : from 0 to n-1
Step 8: if ((infix[i]>=’a’ && infix[i]<=’z’) || (infix[i]>=’A’ && infix[i]>=’Z’))
Step 9: postfix[j] infix[i];
Step 10: j j+1
Step 11: else if (infix[i]= = ‘*’ || infix[i]= = ‘/’|| infix[i]= = ‘+’|| infix[i]= = ‘-’)
Step 12: if top = = -1 then go to step13 else go to step14
Step 13: push(a[i])
Step 14: ucall sub routine preced(a[top])
Step 15: v call sub routine preced(infix[i])
Step 16: repeat steps 17 to 19 while v<=u
Step 17: postfix[j] pop()
Step 18: j++
Step 19: u preced(a[top]) // end of while
Step 20: push(in[i]) //end of else //end of for
Step 21: repeat steps 22, 23 while top!=-1
Step 22: post[j]pop()
Step 23: jj+1
Step 24: post[j]’\0’
Step 25: print ‘post string’, post
Step 26: end
Algorithm for sub routine push(char c)
Step 1: begin
Step 2: top+1
Step 3: a[top]c
Step 4: end
Algorithm for sub routine pop()
Step 1: begin
Step 2: char vala[top]
Step 3: top-1
Step 4: return(val)
Step 5: end
Algorithm for sub routine preced(char c)
Step 1: begin
Step 2: switch ch
Step 3: case ‘*’:
Step 4: case ‘/’: v2
Step 5: break
Step 6: case ‘+’:
Step 7: case ‘-‘ : v1
Step 8: break
Step 9: default: v0
Step 10: break
Step 11: return (v)
Step 12: end
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 20
char stack[MAX];
int top=-1;
char pop();
void push(char item);
int prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-':return 2;
break;
case '*':
case '/':return 4;
break;
case '^':
case '$':return 6;
break;
case '(':
case ')':
case '#':return 1;
break;
}
}
int isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':return 1;
break;
default:return 0;
}
}
char pop()
{
char a;
a=stack[top];
top--;
return a;
}
Output:
EX. NO: 7(B) QUEUE USING LINKED LISTS
Aim: Write C programs that implement Queue (its operations) using linked lists
Program:
/*Queue Using Linked List*/
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
struct node
{
int info;
struct node* next;
}*front,*rear;
void enqueue(int elt);
int dequeue();
void display();
void first(void);
void last(void);
void main()
{
int ch,elt;
rear=NULL;
front=NULL;
clrscr();
while(1)
{
printf("\nEnter:\n1->Insert\n2->Delete\n3->Display\n4->First\n5->Last\n6->Exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter The Element Value\n");
scanf("%d",&elt);
enqueue(elt);
break;
case 2:
elt=dequeue();
printf("The deleted element = %d\n",elt);
break;
case 3:
display();
break;
case 4:
first();
break;
case 5:
last();
break;
default:
printf("~~~Exit~~~");
getch();
return;
}} }
void enqueue(int elt)
{
struct node *p;
p=(struct node*)malloc(sizeof(struct node));
p->info=elt;
p- >next=NULL;
if(rear==NULL||front==NULL)
front=p;
else
rear->next=p;
rear=p;
}
int dequeue()
{
struct node *p;
int elt;
if(front==NULL||rear==NULL)
{
printf("\nUnder Flow");
getch();
exit(0);
}
else
{
p=front;
elt=p->info;
front=front->next;
free(p);
}
return(elt);
}
void display()
{
struct node *t;
t=front;
printf("Queue content :\n");
while(t){
printf("\t%d",t->info);
t=t->next;
}
getch();
}
void first (void){
if(front)
printf("First Element is%d;",front->info);
}
void last (void){
if(rear)
printf("Last Element is%d;",rear->info);
}
Output:
EX. NO: 8 (A) CREATING A SINGLE LINKED LIST
Aim: Write a C program that uses functions to create a singly linked list
Algorithm:
/* Singly_linkedlist */
Input:
Output:
declare struct linkedlist
integer data
struct linkedlist *next
Step 1: Start
Step 2: int num, loc; char ch; node start=NULL;
Step 3: repeat steps 4 to 6 until ch!=’5’
Step 4: print ‘1. insert 2. display 3. exit’
Step 5: read choice ch
Step 6: switch (ch)
case 1: read num
insert(&start,num)
break;
case 2: disp(&start)
break
case 3: exit
break
default: print ‘invalid choice’
break
Step 8: Stop
Algorithm to insert()
Step1: create a new node
struct llist *new;
new=(struct llist *)malloc(sizeof(Struct llist));
Step 2: check overflow
If new==NULL print overflow; return;
Step 3: if memory available keeps the new element value in the node
else new->info=item;
Step 4:-traverse upto the last node
ptr=start;
while(ptr->next != NULL) ptr=ptr->next
Step 5: insert the new node with new information at the end
ptr->next=new;
new->next=NULL
Step 6: stop
Algorithm to display()
Step 1: if(first==NULL) then
printf("LIST EMPTY\n");
return;
Step 2: print ‘The contents of the list are’
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->link;
}
Step 3: stop.
Program:
#include<stdio.h>
#include<stdlib.h>
#include<process.h>
#include<conio.h>
struct node
{
int info;
struct node *link;
};
typedef struct node *NODE;
NODE first=NULL;
NODE getnode()
{
NODE x;
x=(NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf("Cannot allocate memory\'t");
getch();
exit(0);
}
return x;
}
void display()
{
NODE temp;
if(first==NULL)
{
printf("LIST EMPTY\n");
return;
}
printf("The contents of the list are\n");
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->link;
}
printf("\n");
}
void insert(int i)
{
NODE temp,cur;
temp=getnode();
temp->info=i;
temp->link=NULL;
if(first==NULL)
first=temp;
else
{
cur=first;
while(cur->link!=NULL)
cur=cur->link;
cur->link=temp;
}
return;
}
void main()
{
int ch,i;
clrscr();
for(;;)
{
printf("1.insert\n");
printf("2.display\n");
printf("3.exit\n");
printf("Enter the choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1 :
printf("Enter the item to be inserted");
scanf("%d",&i);
insert(i);
getch();
break;
case 2 :
display();
getch();
break;
case 3: exit(0);
default :exit(0);
}
}
}
Output:
EX. NO: 8 (B) INSERTION OPERATIONS ON A SINGLY LINKED LIST
Aim: Write a C program that uses functions to perform insertion operation on a singly
linked list
Algorithm:
Algorithm to create a single linked list: create ()
Step 1: create a data type for the linked list
struct llist
{ int info; struct llist *next; };
Step 2: create a node
struct llist *start,*ptr;
strat= (struct llist *)malloc(sizeof(Struct llist));
ptr=start;/*ptr is taken to help in traversing*/
Step 3: stop
Program:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct node
{
int info;
struct node *link;
};
typedef struct node *NODE;
NODE first=NULL;
NODE getnode(int i)
{
NODE x;
x=(NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf("Cannot allocate memory\'t");
getch();
exit(0);
}
x->info=i;
return x;
}
Output:
EX. NO: 8(C) DELETION OPERATIONS ON A SINGLY LINKED LIST
Aim:Write a C program that uses functions to perform deletion operation on a singly linked
list
Algorithm:
create a data type for the linked list
struct llist
{ int info; struct llist *next; };
create a node
struct llist *start,*ptr;
strat= (struct llist *)malloc(sizeof(Struct llist));
ptr=start;/*ptr is taken to help in traversing*/
NODE getnode(int i)
{
NODE x;
x=(NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf("Cannot allocate memory\'t");
getch();
exit(0);
}
x->info=i;
x->link=NULL;
return x;
}
void create(void)
{
int n,i,x;
NODE temp;
printf(" Enter the no of elements");
scanf("%d",&n);
printf("Enter the Elements");
scanf("%d",&x);
first=getnode(x);
first->link=NULL;
i=2;
while(i<=n)
{
i++;
scanf("%d",&x);
temp=getnode(x);
temp->link=first;
first=temp;
}
}
void EleDelete(int x)
{// Delete element x of linked list
//p will eventually point to node having value x
NODE p = first;
NODE q = first;
while(p && p->info!=x)
{
q=p;
p=p->link;
}
if(!p)
printf("no element");
else
{
if(p==first)
first=p->link;
else
q->link = p->link; // remove from linked list
free(p);
}
return;
}
void Delete(int k, int &x) {// Delete k'th element of chain.
if (k < 1 || !first) printf("no k'th element"); // p will eventually point to k'th node
NODE q,p = first; // move p to k'th & remove from chain
if (k == 1) // p already at k'th
first = first->link; // remove
else { // use q to get to k-1'st
q = first;
for (int index = 1; index < k - 1 && q; index++)
q = q->link;
if (!q || !q->link)
printf("no k'th element");
p = q->link; // k'th
q->link = p->link;
} // remove from chain
// save k'th element and free node p
x = p->info;
printf("Deleted element %d\n",x);
free(p);
return;
}
void display()
{
NODE temp;
if(first==NULL)
{
printf("LIST EMPTY\n");
return;
}
printf("The contents of the list are\n");
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->link;
}
printf("\n");
}
void main()
{
int ch,x,pos;
NODE p, q;
clrscr();
create();
for(;;)
{
printf("\n1.Delete first element\n");
printf("2. Delete last element \n");
printf("3. Delete the kth element\n");
printf("4. Delete the element e from list\n");
printf("5.display\n");
printf("6.exit\n");
printf("Enter the choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1 :
if(first){
p=first;
x=p->info;
first=p->link;
printf("Deleted item is %d",x);
free(p);
}
else
printf("Deletion is not possible");
break;
case 2 :
if(first)
{
q=first;
for(p=first; p->link; p=p->link)
q=p;
x=p->info;
printf("Deleted item is %d",x);
q->link=NULL;
if(p==first)
first=NULL;
free(p);
}
else
{
printf("Deletion is not possible");
}
break;
case 3 :
printf("Enter the Position");
scanf("%d",&pos);
Delete(pos,x);
break;
case 4 :
printf("Enter the element to be deleted");
scanf("%d",&x);
EleDelete(x);
break;
case 5 :
display();
break;
default :exit(0);
}
}
}
Output:
EX. NO: 9(A) ADDITION OF TWO LARGE INTEGERS USING LINKED LIST
Aim: Write a C program for adding two large integers which are represented in linked list fashion.
Algorithm: /* Addition Of Two Large Integers Using Linked List */
Program:
/* Program for adding two large integers which are represented in linked list fashion. */
#include<stdio.h>
#include<alloc.h>
#include<conio.h>
typedef struct Node
{
int data;
struct Node *next;
}node;
void main()
{
node *head1,*head2,*head3,*temp1,*temp2;
node *get_node();
node *read_num(node *head1);
void Sum(node *head1,node *head2,node *head3);
void display_num(node *temp,node *head);
clrscr();
head1=get_node(); /*Allocating memory for header nodes*/
head2=get_node();
head3=get_node();
head1->next=head1;
head2->next=head2;
head3->next=head3; /*-999 is representing the last node */
head1->data=head2->data=head3->data=-999;
printf("\n Press ENTER key to terminate the number ... \n");
printf("\n Enter First number: ");
temp1=read_num(head1);
printf("\n Enter Second number: ");
temp2=read_num(head2);
printf("\n First Number is \n");
display_num(temp1,head1);
printf("\n Second Number is \n");
display_num(temp2,head2);
printf("\n The addition of two long integers is ... \n");
Sum(temp1,temp2,head3);
getch();
}
node *get_node()
{
node *New;
New=(node*)malloc(sizeof(node));
New->next=NULL;
return New;
}
node *read_num(node *head)
{
char ch;
int flag=1;
node *New,*temp;
while((ch=getchar())!='\n')
{
New=get_node(); /*converting characters to its equivalent value */
ch=ch-'0';
New->data=ch;
if(flag==1) /*creation of first node*/
{
New->next=head;
temp=New;
flag=0; /*first node is created*/
}
else
{
New->next=temp; /*making the list circular*/
temp=New;
}
}
return temp;
}
void Sum(node *head1,node *head2,node *head3)
{
long int carry,number,total,num,n;
node *temp;
void display_num(node *,node *);
temp=head3;
carry=0;
/*adding the two numbers from LSB and creating the third list*/
while(head1->data!=-999 &&head2->data!=-999)
{
n=head1->data+head2->data+carry; /*Getting the carry from sum of two numbers*/
num=n%10;
carry=n/10;
head1=head1->next;
head2=head2->next;
head3->data=num;
head3->next=get_node();
head3=head3->next;
}
while(head1->data!=-999) /*if first number is bigger than second*/
{
n=head1->data+carry;
num=n%10;
carry=n/10;
head3->data=num;
head1=head1->next;
head3->next=get_node();
head3=head3->next;
}
while(head2->data!=-999) /*if second number is bigger than first*/
{
n=head2->data+carry;
num=n%10;
carry=n/10;
head3->data=num;
head2=head2->next;
head3->next=get_node();
head3=head3->next;
}
if(carry!=0) /*addition of 2 numbers is over/*and only carry is remaining*/
{
head3->data=carry;
head3->next=get_node();/*separate node for storing the carry of leftmost umber*/
head3=head3->next;
}
head3->data=-999;
head3->next=temp; /*making the list circular*/
display_num(temp,head3);
}
void display_num(node *temp,node *head)
{
int stack[50],i,n;
i=0;
while(temp!=head)
{
stack[i]=temp->data;
temp=temp->next;
i++;
}
n=i-1;
for(i=n;i>=0;i--)
printf("%d",stack[i]);
}
Output:
EX. NO: 9(B) REVERSE ELEMENTS OF A SINGLE LINKED LIST
Program:
#include<stdio.h>
#include<stdlib.h>
#include<process.h>
#include<conio.h>
struct node
{
int info;
struct node *link;
};
typedef struct node *NODE;
NODE first;
NODE getnode()
{
NODE x;
x=(NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf("Cannot allocate memory\'t");
getch();
exit(0);
}
return x;
}
void display()
{
NODE temp;
if(first==NULL)
{
printf("LIST EMPTY\n");
return;
}
printf("The contents of the list are\n");
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->info);
temp=temp->link;
}
printf("\n");
}
void insert(int i)
{
NODE temp,cur;
temp=getnode();
temp->info=i;
temp->link=NULL;
if(first==NULL)
{
first=temp;
return ;
}
cur=first;
while(cur->link!=NULL)
cur=cur->link;
cur->link=temp;
return;
}
void reverse()
{
NODE p,q,r;
p=first;
if(p&&p->link)
{
q=p->link;
while(q->link)
{
r=q->link;
q->link=p;
p=q;
q=r;
}
q->link=p;
first->link=NULL;
first=q;
}
return;
}
void main()
{
first=NULL;
int n,i=1,x;
clrscr();
printf("Enter the no of elements in the list\t:");
scanf("%d",&n);
while(i<=n)
{
printf("Enter the item to be inserted\t:");
scanf("%d",&x);
insert(x);
i++;
}
display();
reverse();
printf("\nAfter reversing. ... \n");
display();
}
Output:
EX. NO: 9(C) Store A Polynomial Expression In Memory Using Linked List
Aim: Write a C program to store a polynomial expression in memory using linked list
Algorithm:
Program:
/* Program for storing a polynomial expression in memory using linked list */
#include<stdio.h>
#include<stdlib.h>
#include<process.h>
#include<conio.h>
struct node
{
float coeff;
int exp;
struct node *link;
};
typedef struct node *NODE;
NODE first=NULL;
NODE getnode()
{
NODE x;
x=(NODE)malloc(sizeof(struct node));
if(x==NULL)
{
printf("Cannot allocate memory\'t");
getch();
exit(0);
}
return x;
}
void display()
{
NODE temp;
if(first==NULL)
{
printf("LIST EMPTY\n");
return;
}
printf("The Polynomial is\n");
temp=first;
while(temp)
{
printf("+%4.2fX\^%d ",temp->coeff,temp->exp);
temp=temp->link;
}
printf("\n");
}
void main()
{
NODE p;
int ch,i=1,n;
float c;
int e;
clrscr();
printf("Enter the no of terms in the polynomial\t:");
scanf("%d",&n);
while(i<=n)
{
printf("coefficient and the exponent : %d :",i);
scanf("%f%d",&c,&e);
i++;
if(first)
{
p=first;
while(p->link)
p=p->link;
p->link=getnode();
p=p->link;
p->coeff=c;
p->exp=e;
p- >link=NULL;
}
else
{
first=getnode();
first->coeff=c;
first->exp=e;
first->link=NULL;
}
}
display();
}
Output:
EX. NO: 9(D) REPRESENT THE GIVEN SPARSE MATRIX USING ARRAYS
Aim: Write a C programme to representation the given sparse matrix using arrays.
Algorithm:
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int spm[25][3],a[5][5],i,j,count,n,m,k;
clrscr();
printf("Enter matrix size as mxn\t: :");
scanf("%d%d",&m,&n);
count=0;
k=1;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\nelement A %d%d",i,j);
scanf("%d",&a[i][j]);
/* }
}
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{ */
if(a[i][j] !=0)
{
spm[k][0]=i;
spm[k][1]=j;
spm[k++][2]=a[i][j];
count++;
}
}
}
spm[0][0]=m;
spm[0][1]=n;
spm[0][2]=count;
printf("\nsparse matrix is : :\n");
for(i=0;i<=count;i++)
{
for(j=0;j<3;j++)
printf("%d ",spm[i][j]);
printf("\n");
}
getch();
}
Output:
EX. NO: 9(E) REPRESENT THE GIVEN SPARSE MATRIX USING LINKED LIST
Aim: Write a C programme to representation the given sparse matrix using linked list.
Algorithm:
Program: /* Program for representing a sparse matrix using linked list */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct spars /*creating the data type for the node */
{
int row;
int col;
int item;
struct spars *next;
}*ptr;
struct head_sp /*creating the data type for header node header*/
{
int rows;
int cols;
int items;
struct spars *next;
}*header;
void main()
{
int i,j;
/*create the header node*/
header=(struct head_sp *)malloc(sizeof(struct head_sp));
/*store elements of the header node*/
printf("Enter the Header node information\n");
printf("Enter Number of rows,columns, and Non zero elements\t:");
scanf("%d%d%d",&header->rows,&header->cols,&header->items);
/*if sparse matrix is empty then return*/
if(header->items==0)
{
printf("If no Non-zero elements, Press any key to return");
getch();
exit(0);
} /*Otherwise, Head node pointer will point to the first element of the sparse matrix*/
header->next=(struct spars *)malloc(sizeof(struct spars));
/*keep elements in the first node*/
printf("Enter the ROW No., COL no., and Non-zero element\t:");
scanf("%d%d%d",&header->next->row,&header->next->col,&header->next->item );
/*initializing special pointer to the sparse matrix elements*/
ptr=header->next;
/*create nodes for sparse matrix elements and enter information in them*/
for(i=2;i<=header->items;i++)
{
ptr->next=(struct spars *)malloc(sizeof(struct spars));
ptr=ptr->next;
printf("enter the row no., col no., value of %dth element\t:",i);
scanf("%d%d%d",&ptr->row, &ptr->col, &ptr->item);
}
ptr->next=NULL; /*display the header node*/
printf("\n\nHeader node Information:\n\n");
printf(" No.of rows=%d\n No. of cols=%d\n No. of Non-zero elements=%d\n", header-
>rows,header->cols,header->items); /*display the matrix elemnts*/
printf("Elements of the matrix are:\nrow no. col no. value \n");
ptr=header->next;
for(i=0;i<header->rows;i++)
for(j=0;j<header->cols;j++)
{
printf("%d\t%d\t",i,j);
if(ptr!=NULL)
{
if((i==(ptr->row)) && (j==(ptr->col)))
{
printf("%d\n",ptr->item);
ptr=ptr->next;
}
else
printf("0 \n");
}
else printf("0 \n");
}
}
Output:
EX. NO: 10(A) CREATE A BINARY TREE OF INTEGERS
Algorithm:
Program:
/**********************************************************
Program for creating a Binary Tree and Displaying the tree
**********************************************************/
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node{
int info;
struct node *left,*right;
};
int getitem()
{
int item;
printf("\nEnter item\t:");
scanf("%d",&item);
return item;
}
void insert(struct node **root,int item)
{
char lch,rch;
struct node *nn;
nn=(struct node *)malloc(sizeof(struct node));
nn->info=item;
nn->left=NULL;
nn->right=NULL;
if(*root == NULL)
*root=nn;
printf("%d HAS ANY LEFT (y/n)?\t::",(*root)->info);
lch=getche();
if(lch == 'y' || lch == 'Y')
insert(&(*root)->left,getitem());
printf("\n%d HAS ANY RIGHT(y/n)?::",(*root)->info);
rch=getche();
if(rch == 'y' || rch == 'Y')
insert(&(*root)->right,getitem());
}
void inorder(struct node *r)
{
if(r ==NULL)
return;
inorder(r->left);
printf("%d-->",r->info);
inorder(r->right);
}
void main()
{
struct node *root=NULL;
int item;
clrscr();
puts("\t\t\tImplementing a simple Binary Tree\n");
item=getitem();
insert(&root,item);
puts("\nDisplaying the Tree\n");
printf("\nRoot node is %d",root->info);
printf("\n\nINORDER TRAVERSAL : :\n");
inorder(root);
getch();
}
Output:
EX. NO: 10(B) TRAVERSING A BINARY TREE IN PREORDER, INORDER AND
POSTORDER USING RECURSION
Aim: Write a recursive C program, for traversing a binary tree in preorder, inorder and
postorder.
Algorithm:
Program:
/**********************************************************
Program for creation Of a Binary Tree and Display the tree
using recursive inorder, preorder and postorder traversals.
**********************************************************/
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
struct node{
int info;
struct node *left,*right;
};
int getitem()
{
int item;
printf("\nEnter item\t:");
scanf("%d",&item);
return item;
}
void insert(struct node **root,int item)
{
char lch,rch;
struct node *nn;
nn=(struct node *)malloc(sizeof(struct node));
nn->info=item;
nn->left=NULL;
nn->right=NULL;
if(*root == NULL)
*root=nn;
printf("%d HAS ANY LEFT (y/n)?\t::",(*root)->info);
lch=getche();
}
/* This function displays the tree in preorder fashion */
void preorder(struct node *r)
{
if(r== NULL)
return;
printf("%d-->",r->info);
preorder(r->left);
preorder(r->right);
}
/* This function displays the tree in postorder fashion */
void postorder(struct node *r)
{
if(r==NULL)
return;
postorder(r->left);
postorder(r->right);
printf("%d-->",r->info);
}
void main()
{
struct node *root=NULL;
int item;
int choice;
clrscr();
printf("\n\t Program For Binary Tree\n\n");
do
{
printf("\n1.Create\n2.Inorder Traversal\n3.Preorder Traversal\n4.Postorder
Traversal\n5.Exit");
printf("\n\n Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1:
root=NULL;
item=getitem();
insert(&root,item);
break;
case 2:
if(root==NULL)
printf("Tree Is Not Created");
else
{
printf("\n\nINORDER TRAVERSAL : :\n");
inorder(root);
}
break;
case 3:
if(root==NULL)
printf("Tree Is Not Created");
else
{
printf("\n\nPREORDER TRAVERSAL ::\n");
preorder(root);
}
break;
case 4:
if(root==NULL)
printf("Tree Is Not Created");
else
{
printf("\n\nPOST ORDER TRAVERSAL ::\n");
postorder(root);
}
break;
}
}while(choice!=5);
getch();
}
Output:
EX. NO: 10(C) TRAVERSING A BINARY TREE IN PREORDER, INORDER AND
POSTORDER NOT USING RECURSION
Aim: Write a non recursive C program, for traversing a binary tree in preorder, inorder and
postorder.
Algorithm: A binary tree T is in memory. The algorithm does a preorder traversal of T,
Applying a PROCESS to each of its nodes. An array STACK is used to temporarily hold the
address of nodes.
Algorithm for preorder (using stack):
Step 1: Initially push NULL into the STACK, and initialize PTR.
Set TOP=1 STACK[1]=NULL and PTR=ROOT
Step 2: repeate step 3 to 5 untill PTR != NULL
Step 3: Apply PROCESS to PTR->INFO
Step 4: check for right child
If PTR->RIGHT !=NULL then push on stack
Set TOP=TOP+1 and
STACK[TOP]=PTR->RIGHT
Step 5:Check for left child
If PTR->LEFT != NULL then PTR=PTR->left
Else set ptr=STASCK[TOP] and TOP=TOP-1
Step 6: stop.
Program:
/***********************************************************************
Program for Implementation of Simple Binary Tree and Non-recursive inorder, preorder and
postorder traversals.
**************************************************************************/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct bstnode
{
int data;
struct bstnode *lc,*rc;
}*root,*a[20],*b[20];
int top=-1,top1=-1,n,i;
push (struct bstnode *);
struct bstnode *pop();
void insert(struct bstnode **,int);
int getitem();
void Nonrecursive_Inorder(struct bstnode *);
void Nonrecursive_Postorder(struct bstnode *);
void Nonrecursive_Preorder(struct bstnode *);
void main()
{
int ch,item;
struct bstnode *root;
clrscr();
root=NULL;
while(1)
{
printf("\n **** M E N U **** \n");
printf("\nstep 1:Create\nstep 2:NON-RECURSIVE TRAVERSE\nstep 3:EXIT\n");
printf("Enter your choice\t:");
scanf("%d",&ch);
switch(ch)
{
case 1: root=NULL;
item=getitem();
insert(&root,item);
break;
case 2:
if(root==NULL)
printf("\nTREE IS EMPTY\n");
else
{
printf("\nINORDER\t:");
Nonrecursive_Inorder(root);
printf("\nPREORDER\t:");
Nonrecursive_Preorder(root);
printf("\nPOSTORDER\t:");
Nonrecursive_Postorder(root);
}
break;
case 3:
exit(0);
}
}
}
int getitem()
{
int item;
printf("\nEnter item\t:");
scanf("%d",&item);
return item;
}
void insert(struct bstnode **root,int item)
{
char lch,rch;
struct bstnode *nn;
nn=(struct bstnode *)malloc(sizeof(struct bstnode));
nn->data=item;
nn->lc=NULL;
nn->rc=NULL;
if(*root == NULL)
*root=nn;
printf("%d HAS ANY LEFT (y/n)?\t::",(*root)->data);
lch=getche();
Algorithm:
Program:
/* Program For Implementation Of Binary Search Tree and display of tree. */
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
void main()
{
int choice;
char ans='N';
node *New,*root;
node *get_node();
root=NULL;
clrscr();
printf("\n\t***** Binary Search Tree ****** ");
do
{
printf("\n1.Create\n2.Display\n3.Exit");
printf("\n\n Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1:root=NULL;
do
{
New=get_node();
printf("\n Enter The Element ");
scanf("%d",&New->data);
if(root==NULL) /* Tree is not Created */
root=New;
else
insert(root,New);
printf("\n Do u Want To enter More Elements?(y/n)");
ans=getch();
}while(ans=='y'||ans=='Y');
break;
case 2:if(root==NULL)
printf("Tree Is Not Created\n");
else
{
printf("\n The Inorder display of the Tree is : ");
inorder(root);
}
break;
}
}while(choice!=3);
}
node *get_node()
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->left=NULL;
temp->right=NULL;
return temp;
}
Output:
EX. NO: 11(B) INSERT A NODE INTO A BST
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
Output:
EX. NO: 11(C) INSERT A NODE INTO A BST
Algorithm:
Program:
/*Program For Implementation of Binary Search Tree,perform deletion and display of tree. */
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct bst
{
int data;
struct bst *left,*right;
}node;
void insert(node *,node *);
void inorder(node *);
void preorder(node *);
void postorder(node *);
void search (node **root, int num,node **par, node **x, int *found );
void delete(node **root, int);
void main()
{
int choice,ele;
char ans='N';
node *New,*root;
node *get_node();
root=NULL;
clrscr();
printf("\n\t Program For Binary Search Tree ");
do
{
printf("\n1.Create\n2.Delete\n3.Recursive Traversals\n4.Exit");
printf("\n\n Enter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1: root=NULL;
do
{
New=get_node();
printf("\n Enter The Element ");
scanf("%d",&New->data);
if(root==NULL) /* Tree is not Created */
root=New;
else
insert(root,New);
printf("\n Do u Want To enter More Elements?(y/n)");
ans=getch();
}while(ans=='y');
break;
case 2:printf("\n Enter The Element Which You Want To Delete");
scanf("%d",&ele) ;
delete(&root,ele);
break;
case 3:if(root==NULL)
printf("Tree Is Not Created");
else
{
printf("\n The Inorder display of the Tree is : ");
inorder(root);
printf("\n The Preorder display of the Tree is : ");
preorder(root);
printf("\n The Postorder display of the Tree is : ");
postorder(root);
}
break;
}
}while(choice!=4);
}
node *get_node()
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->left=NULL;
temp->right=NULL;
return temp;
}
/*This function is for creating a binary search tree */
void insert(node *root,node *New)
{
if(New->data<root->data)
{
if(root->left==NULL)
root->left=New;
else
insert(root->left,New);
}
if(New->data>root->data)
{
if(root->right==NULL)
root->right=New;
else
insert(root->right,New);
}
}
/* This function is for searching the node from binary Search Tree */
/* deletes a node from the binary search tree */
void delete (node **root, int num )
{
int found ;
node *parent, *x, *xsucc ;
/* if tree is empty */
if ( *root == NULL )
{
printf ( "\nTree is empty" ) ;
return ;
}
parent = x = NULL ; /* call to search function to find the node to be deleted */
search ( root, num, &parent, &x, &found ) ;
free ( x ) ;
return ;
}
/* if the node to be deleted has only right child */
if ( x -> left == NULL && x -> right != NULL )
{
if ( parent -> left == x )
parent -> left= x -> right;
else
parent -> right= x -> right;
free ( x ) ;
return ;
}
/* if the node to be deleted has only left child */
if ( x -> left != NULL && x -> right == NULL )
{
if ( parent -> left == x )
parent -> left = x -> left ;
else
parent -> right = x -> left ;
free ( x ) ;
return ;
}
}
/*returns the address of the node to be deleted, address of its parent and whether the node is
found or not */
void search (node **root, int num,node **par, node **x, int *found )
{
node *q ;
q = *root ;
*found = FALSE ;
*par = NULL ;
while ( q != NULL )
{
/* if the node to be deleted is found */
if ( q -> data == num )
{
*found = TRUE ;
*x = q ;
return ;
}
*par = q ;
if ( q -> data > num )
q = q -> left;
else
q = q -> right;
}
}
/* This function displays the tree in inorder fashion */
void inorder(node *temp)
{
if(temp!=NULL)
{
inorder(temp->left);
printf(" %d",temp->data);
inorder(temp->right);
}
}
/* This function displays the tree in preorder fashion */
void preorder(node *temp)
{
if(temp!=NULL)
{
printf(" %d",temp->data);
preorder(temp->left);
preorder(temp->right);
}
}
/* This function displays the tree in postorder fashion */
void postorder(node *temp)
{
if(temp!=NULL)
{
postorder(temp->left);
postorder(temp->right);
printf(" %d",temp->data);
}
}
Output: