DS LAB Manual
DS LAB Manual
GROUP OF INSTITUTIONS
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
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;
OUTPUT:
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 */
Output:
Output:
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);
Output:
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>
Output:
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
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
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)
Output:
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:
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);
}
}
Output:
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");
Output:
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)
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:
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;
Output:
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);
Output:
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
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:
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
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 '(':
char pop()
{
char a;
a=stack[top];
top--;
return a;
}
Output:
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;
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);
}
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);
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
{
Output:
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:
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
Output:
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;
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;
Output:
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()
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();
}
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);
}
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);
Output:
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)
Output:
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:");
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();
node *get_node()
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->left=NULL;
temp->right=NULL;
return temp;
}
Output:
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
Output:
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
/* 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 ;
}
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;
}
}
}
}
Output: