0% found this document useful (0 votes)
61 views58 pages

LabManual DS 18MCAL27-2

This document contains 5 programming problems involving recursion in C: 1. A program to calculate the greatest common divisor (GCD) and least common multiple (LCM) of 3 integers recursively. 2. A recursive solution to the Towers of Hanoi problem to move a set of disks from one rod to another according to the rules of the puzzle. 3. A recursive function to calculate the sum of integers from 1 to a given number n. 4. The document provides algorithms for solving each problem recursively and outlines the necessary functions and parameters. 5. A starter C program is given that defines the necessary functions and variables to implement the recursive solutions.

Uploaded by

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

LabManual DS 18MCAL27-2

This document contains 5 programming problems involving recursion in C: 1. A program to calculate the greatest common divisor (GCD) and least common multiple (LCM) of 3 integers recursively. 2. A recursive solution to the Towers of Hanoi problem to move a set of disks from one rod to another according to the rules of the puzzle. 3. A recursive function to calculate the sum of integers from 1 to a given number n. 4. The document provides algorithms for solving each problem recursively and outlines the necessary functions and parameters. 5. A starter C program is given that defines the necessary functions and variables to implement the recursive solutions.

Uploaded by

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

Data Structures Using C Laboratory 18MCAL27

1. Write a C program to find Average and Deviation by passing


Array of elements as a parameter to a function.

/* ARRAY DEVIATION BY PASSING TO FUNCTION */

#include<stdio.h>

#include<conio.h>

void avg(int [],int);

void main()

int a[100],i,n;

clrscr();

printf("\n Enter the number of element");

scanf("%d",&n);

printf("\n Enter the numbers");

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

scanf("%d",&a[i]);

avg(a,n);

getch();

void avg(int a[],int n)

int sum=0,i;

float avg,dev[100];

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

sum=sum+a[i];

avg=sum/n;

printf("\n Sum=%d \n Average=%f\n",sum,avg);

Department of MCA, NHCE Page 1 2017- 2018


Data Structures Using C Laboratory 18MCAL27

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

dev[i]=a[i]-avg;

printf("\n %d deviates is %5.2f",a[i],dev[i]);

Output:

Department of MCA, NHCE Page 2 2017- 2018


Data Structures Using C Laboratory 18MCAL27

2 Write C program to perform String operations without using


built in function.
/*STRING OPERATIONS */

#include<stdio.h>

#include<string.h>

/* To find length */

void length()

char str[100];

int l,i;

printf(" Enter the string \n");

scanf("%s",str);

for(i=0;str[i]!='\0';i++);

printf(" length of string is %d\n",i);

/* To concatinate */

void concat()

char s1[100],s2[100];

int i,j;

printf(" Enter the first string \n");

scanf("%s",s1);

printf(" Enter the second string \n");

scanf("%s",&s2);

i=strlen(s1);

for(j=0;s2[j]!='\0';i++,j++)

s1[i]=s2[j];

Department of MCA, NHCE Page 3 2017- 2018


Data Structures Using C Laboratory 18MCAL27

s1[i]='\0';

printf(" Concated string is %s\n",s1);

/* To find substring */

void substr()

char s1[100],s2[100];

int i,j,k,m;

printf(" Enter the string ");

scanf("%s",s1);

printf(" Enter the position and length ");

scanf("%d%d",&i,&j);

for(k=i,m=0;m<j;s2[m++]=s1[k++]);

s2[m]='\0';

printf(" The substring is : %s\n",s2);

void main()

int ch;

char ans;

clrscr();

do

printf("Enter your choice");

printf("\n1.Length \t2.Concat \t3.Extraction\t4.Exit\n");

scanf("%d",&ch);

switch(ch)

Department of MCA, NHCE Page 4 2017- 2018


Data Structures Using C Laboratory 18MCAL27

case 1:length();

break;

case 2:concat();

break;

case 3:substr();

break;

case 4:exit (0);

printf("Do u want to continue \n");

scanf("%s",&ans);

}while(ans=='y');

getch();

Output:

Department of MCA, NHCE Page 5 2017- 2018


Data Structures Using C Laboratory 18MCAL27

3. Write a C program to convert an infix notation to postfix


notation.

Algorithm:
For each symbol in the infix expression
{
While(stk_precedence(s[top]>input_precedence(symbol))
{
Pop element from stack and add it to postfix expression
}

If(stk_precedence(s[top]!=input_precedence(symbol))
Push the item into the stack

else
delete the item from the stack
}

After reaching end of expression move the content of stack output expression.

Program:
#include<stdio.h>

#include<conio.h>

#include<string.h>

int stack_prec(char symbol)

switch(symbol)

case '+':

case '-':return 2;

case '*':

case '/':return 4;

case '^':

case '$':return 5;

case '(':return 0;

Department of MCA, NHCE Page 6 2017- 2018


Data Structures Using C Laboratory 18MCAL27

case '#':return -1;

default:return 8;

int input_prec(char symbol)

switch(symbol)

case '+':

case '-':return 1;

case '*':

case '/':return 3;

case '^':

case '$':return 6;

case '(':return 9;

case ')':return 0;

default:return 7;

void infix_postfix(char infix[],char postfix[])

int top=-1,j=0,i;

char s[20],symbol;

s[++top]='#';

for(i=0;i<strlen(infix);i++)

symbol=infix[i];

Department of MCA, NHCE Page 7 2017- 2018


Data Structures Using C Laboratory 18MCAL27

while(stack_prec(s[top])>input_prec(symbol))

postfix[j]=s[top--];

j++;

if(stack_prec(s[top])!=input_prec(symbol))

s[++top]=symbol;

else

top--;

while(s[top]!='#')

postfix[j++]=s[top--];

postfix[j]='\0';

void main()

char infix[20],postfix[20];

clrscr();

printf("\n Enter the infix expression ");

scanf("%s",infix);

infix_postfix(infix,postfix);

printf("\n Postfix expr is : %s",postfix);

getch();

Department of MCA, NHCE Page 8 2017- 2018


Data Structures Using C Laboratory 18MCAL27

Output:

Department of MCA, NHCE Page 9 2017- 2018


Data Structures Using C Laboratory 18MCAL27

4. Write a C program to evaluate a given postfix expression and


its values for the variables.

Algorithm: Evaluation of Postfix Expression


while end of input is not reached fo
{
Symbol = nextchar()
If (symbol is an operand)
Push(symbol, top, S);
Else
{
Op2=pop(top, S);
Op1=pop(top, S)
Res = Op1 op Op2;
Push(res, top, S);
}
}
Program :

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<math.h>
int isdigit (char );
float compute (char ,float ,float );
void main()
{
int i,top;
char symbol,postfix[20];
float s[20],op1,op2,res;
clrscr();
printf("\n\t***EVALUATION OF POSTFIX EXPRESSION***");
printf("\nEnter the postfix expression:");
gets(postfix);
top=-1;
for(i=0;i<strlen(postfix);i++)
{
symbol=postfix[i];
if(isdigit(symbol))
{
top=top+1;
s[top]=symbol-'0';
}
else
{
op2=s[top--];

Department of MCA, NHCE Page 10 2017- 2018


Data Structures Using C Laboratory 18MCAL27

op1=s[top--];
res=compute(symbol,op1,op2);
s[++top]=res;
}
}
res=s[top--];
printf("\n\n\tResult of the given postfix Expression:%f",res);
getch();
}

int isdigit(char symbol)


{
if(symbol>='0' && symbol<='9')
return 1;
else
return 0;
}

float compute(char symbol,float op1,float op2)


{
switch(symbol)
{
case '+':return op1+op2;
case '-':return op1-op2;
case '*':return op1*op2;
case '/':return op1/op2;
case '$':
case '^':return pow(op1,op2);
default: printf("\nInvalid...");
exit(0);
}
return ;
}

OUTPUT:

Department of MCA, NHCE Page 11 2017- 2018


Data Structures Using C Laboratory 18MCAL27

5. Write a C program to Demonstrate recursion

a. Calculate GCD and LCM of 3 integer numbers


b. Solve Towers of Hanoi Problem
c. Calculate the sum for a given number ‘n’ from 1 to n.

Algorithm :
a. Procedure for GCD & LCM :

GCD(int m, int n)

i. if m is smaller than n,
return n,m
ii. Remainder equal to m modulo n.
iii. if r is zero then,
return n
else
return GCD(n,r)
iv. exit

LCM(int a, int b, int n)

i. if a, b is divided by n then, it is zero


return n
else
return LCM(a,b,n+1)
ii. exit

b. Procedure for Tower of Hanoi :

Hanoi(int disk, int source, int destination,int other)

i. if desk is smaller then,


Move disk from source to destination
else
Hanoi(next disk,source,other disk,destination)
Move disk from source to destination
Hanoi(next disk, other,destination,source)
ii. exit

c. Procedure for sum of numbers from 1 to n


Read n ;
Sum1=0;
int sum(n)
{

Department of MCA, NHCE Page 12 2017- 2018


Data Structures Using C Laboratory 18MCAL27

Sum1= n + sum(n-1); // Recursive call


Return Sum1;
}

Program:

#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>

int gcd(int,int);
int lcm(int,int,int);
void hanoi(int,char,char,char);
int sum(int);

void main()
{
int g,l,m,x,y,z,n,ch,disk,move,i,j,ele,temp,s,range;
clrscr();

printf("\n1.GCD & LCM");


printf("\n2.Tower of Hanoi");
printf("\n3.Sum of no. from 1 to n");
printf("\n4.Exit");
printf("\nEnter your choice...");
scanf("%d",&ch);

switch(ch)
{
case 1: {
printf("Enter the Three integer");
scanf("%d%d%d",&x,&y,&z);
n=1;
g=gcd(gcd(x,y),z);
l=lcm(lcm(x,y,n),z,n);
printf("GCD is %d LCM is %d",g,l);
break;
}
case 2: {
printf("Enter the no of disk");
scanf("%d",&disk);
move=pow(2,disk)-1;
printf("No of moves are %d",move);
hanoi(disk,'A','B','C');
break;
}

case 3:{

Department of MCA, NHCE Page 13 2017- 2018


Data Structures Using C Laboratory 18MCAL27

printf("Enter the range of the sum:");


scanf("%d",&range);
s=sum(range);
printf("Sum of element 1 to n:%d",s);
break;
}
case 4:{
exit(0);
break;
}
default: printf("\nInvalid choice...");
}
getch();
}
int gcd(int m,int n)
{
int r;
if(m<n)
return gcd(n,m);
r=m%n;
if(r==0)
return n;
else
return(gcd(n,r));
}
int lcm(int a,int b,int n)
{
if(n%a==0 && n%b==0)
return n;
else
return (lcm(a,b,n+1));
}
void hanoi(int d,char source,char temp,char dest)
{
if(d==1)
{
printf("\nMove disk %d from %c to %c",d,source,dest);
}
else
{
hanoi(d-1,source,dest,temp);
printf("\nMove disk %d from %c to %c",d,source,dest);
hanoi(d-1,temp,source,dest);
}
}
int sum(int n)
{
if(n==0) return 0;
if(n==-1) return 1;
return(n+sum(n-1));

Department of MCA, NHCE Page 14 2017- 2018


Data Structures Using C Laboratory 18MCAL27

OUTPUT:

Department of MCA, NHCE Page 15 2017- 2018


Data Structures Using C Laboratory 18MCAL27

6. Write a C program to Simulate the working of circular queue


providing the following operations–Insert,Delete and Display.
Algorithm :

Procedure for Insertion :

1. if Queue is full,
Write: OVERFLOW of QUEUE
2. if Queue is not NULL, insert an ITEM,
REAR:=REAR%Size+1[increment the rear point by 1]
3. [Update the counter variable to check overflow]
COUNT:=COUNT+1
4. exit

Procedure for Deletion :

1. if Queue is empty,
Write: UNDERFLOW of QUEUE
2. [Point to next front item]
FRONT:=FRONT%Size+1
3. [update the counter variable to check underflow ]
COUNT:=COUNT-1
4. exit

Program:

#include<stdio.h>
#include<conio.h>
#define MAX 5
int cq[MAX],rear=0,front=1,count=0;

void cqins()
{
int elt;
if(count==MAX)
{
printf("\nCQ is full");
}
else
{
printf("\nEnter the element of insert");
scanf("%d",&elt);
rear=rear%MAX+1;
cq[rear]=elt;
printf("\nElement insert at location %d",rear);
count++;

}
Department of MCA, NHCE Page 16 2017- 2018
Data Structures Using C Laboratory 18MCAL27

void cqdel()
{
if(count==0)
{
printf("\nCQ is empty");
}
else
{
printf("\nDelete item is %d",cq[front]);
front=front%MAX+1;
count--;
}
}

void cqdis()
{
int i,j;
i=front;
if(count==0)
{
printf("\nempty");
}
else
{
printf("\nEnter the element are:");
for(j=1;j<=count;j++)
{
printf("%d",cq[i]);
i=i%MAX+1;
}
printf("\nFront of the CQ:%d",cq[front]);
printf("\nRear of the CQ:%d",cq[rear]);
}
}

void main()
{
int ch;
clrscr();
for(;;)
{
printf("\nCQ Operation");
printf("\n1.Insert");

Department of MCA, NHCE Page 17 2017- 2018


Data Structures Using C Laboratory 18MCAL27

printf("\n2.Delete");
printf("\n3.Display");
printf("\n4.Exit");
printf("\nEnter your choice...");
scanf("%d",&ch);

switch(ch)
{
case 1: cqins();
break;
case 2: cqdel();
break;
case 3: cqdis();
break;
case 4:exit(0);
default: printf("\nInvalid");
}
}
getch();
}

OUTPUT:

Department of MCA, NHCE Page 18 2017- 2018


Data Structures Using C Laboratory 18MCAL27

Department of MCA, NHCE Page 19 2017- 2018


Data Structures Using C Laboratory 18MCAL27

7. Write a C program to Simulate the working of a dequeue.

Algorithm – Insertion at rear end

Step -1 : [Check for overflow]


if(rear==MAX)
Output "Queue is Overflow”
return;

Step-2 : [Insert element]


else
rear=rear+1;
q[rear]=no;

[Set rear and front pointer]


if rear=0
rear=1;

if front=0
front=1;

Step-3 : return

Algorithm : Insertion at front end

Step-1 : [Check for the front position]


if(front<=1)
Ourput “Cannot add value at front end”
return;
Step-2 : [Insert at front]
else
front=front-1;
q[front]=no;
Step-3 : Return

Algorithm :Deletion from front end

Step-1 [ Check for front pointer]


if front=0
Output " Queue is Underflow”
return;
Step-2 [Perform deletion]
else
no=q[front];
Output “Deleted element is”,no

[Set front and rear pointer]

if front=rear

Department of MCA, NHCE Page 20 2017- 2018


Data Structures Using C Laboratory 18MCAL27

front=0;
rear=0;
else
front=front+1;

Step-3 : Return

Algorithm : deletion from rear end

Step-1 : [Check for the rear pointer]


if rear=0
Output “Cannot delete value at rear end”
return;
Step-2: [ perform deletion]
else
no=q[rear];
[Check for the front and rear pointer]
if front= rear
front=0;
rear=0;
else
rear=rear-1;
Output “Deleted element is”,no
Step-3 : Return

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

int dq[MAX],front=0,rear=0;
void add_rear();
void add_front();
void delete_rear();
void delete_front();
void display();

void main()
{
int ch;
clrscr();
while(ch!=6)
{
printf("\n1.Insert at rear");
printf("\n2.Insert at front");
printf("\n3.Delete at rear");
printf("\n4.Delete at front");
printf("\n5.Display");
Department of MCA, NHCE Page 21 2017- 2018
Data Structures Using C Laboratory 18MCAL27

printf("\n6.Exit");
printf("\nEnter the choice...");
scanf("%d",&ch);
switch(ch)
{
case 1:{
add_rear();
printf("\nConsist of DQ after insert at rear");
display();
break;
}
case 2:{
add_front();
printf("\nIN DQ after insert at front");
display();
break;
}
case 3:{
delete_rear();
printf("\nDQ after delete at rear");
display();
break;
}

case 4:{
delete_front();
printf("\nDQ after front at front");
display();
break;
}
case 5:{
display();
break;
}
case 6:{
exit(0);
}
default : printf("\nInvalid Choice...");

}
}
getch();
}

void add_rear()
{
int no;
printf("\nEnter the value to insert");
scanf("%d",&no);
if(rear==MAX)

Department of MCA, NHCE Page 22 2017- 2018


Data Structures Using C Laboratory 18MCAL27

{
printf("\noverflow");
return;
}
else
{
rear++;
dq[rear]=no;
if(rear==0)
rear=1;
if(front==0)
front=1;
}
}

void add_front()
{
int no;
printf("\nEnter the value for insert");
scanf("%d",&no);
if(front<=1)
{
printf("\nCan not add front");
return;
}
else
{
front++;
dq[front]=no;
}
}
void delete_front()
{
int no;
if(front==0)
{
printf("\nUnderflow");
return;
}
else
{
no=dq[front];
printf("\nDelete element is %d",no);
if(front==rear)
{
front=0;
rear=0;
}
else
{

Department of MCA, NHCE Page 23 2017- 2018


Data Structures Using C Laboratory 18MCAL27

front++;
}

}
}
void delete_rear()
{
int no;
if(rear==0)
{
printf("\nCan not delete value at rear");
return;
}
else
{
no=dq[rear];
if(front==rear)
{
front=0;
rear=0;
}
else
{
rear--;
printf("\nDelete element is %d",no);
}

}
}
void display()
{
int i;
if(front==0)
{
printf("\nunderflow");
return;
}
else
{
printf("\nOutput:\n");
for(i=front;i<=rear;i++)
{
printf("\n%d",dq[i]);
}
}
}

Department of MCA, NHCE Page 24 2017- 2018


Data Structures Using C Laboratory 18MCAL27

Output:

Department of MCA, NHCE Page 25 2017- 2018


Data Structures Using C Laboratory 18MCAL27

8. Write a C program to Simulate the working of a linked


list to implement stack and queue.
Algorithm:
Procedure for Insertion :

i. Insert a node at the front end


a. Inserted a node pointed by temp at the front of the list, address of the first node
i.e. cur:=head->link
b. The node pointed to by temp can be easily inserted between header node &
the node pointed to by cur.
i.e. head->rlink:=temp;
temp->llink:=head;
temp->rlink:=cur;
cur->llink=temp;

ii. Insert a node at the rear end


a. Inserted a node pointed by temp at the front of the list, address of the last node
i.e. cur:=head->link
b. Insert at the end of the list
i.e. head->llink:=temp
temp->rlink:=head
temp->llink:=cur
cur->rlink:=temp
c. Return the header node

Procedure for Deletion :

i. Delete a node from the front end

a. find the address of the first node


i.e. cur:=head->rlink
b. obtain the successor of the node
i.e. next:=cur->rlink
c. Establish a link between the header node & the successor of the node to be
deleted. i.e.
head->rlink:=next
next->llink:=head
d. delete the node
i.e.cur->info
freenode(cur)
e. return the address of the header node

Program - Linked list - To implement stack and queue


Department of MCA, NHCE Page 26 2017- 2018
Data Structures Using C Laboratory 18MCAL27

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *link;
};
typedef struct node *NODE;

NODE head;

NODE getnode();
void stkpush();
void pop_del();
void qinsert();
void display();
void freenode(NODE);

void main()
{
int ch;
char op;
clrscr();
head->link=NULL;
while(1)
{
printf("\n------------MENU------------");
printf("\n\t 1: STACK IMPLEMENTATION");
printf("\n\t 2: QUEUE IMPLEMENTATION");
printf("\n\t 3: DISPLAY");
printf("\n\t 4: EXIT");
printf("\n\t ENTER THE CHOICE: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n\t\t STACK ");
printf("\n\t 1: Push - Insert at front");
printf("\n\t 2: Pop - Delete at front");
printf("\n\t Enter the option : " );
scanf("%d",&op);
switch(op)
{
case 1:
stkpush();
printf("\n\t Stack contents after Push operation");
display();
break;
case 2:

Department of MCA, NHCE Page 27 2017- 2018


Data Structures Using C Laboratory 18MCAL27

pop_del();
printf("\n\t Stack contents after Pop");
display();
break;
default: printf("\n\t Invalid choice: ");
exit(1);
break;

}
break;
case 2:
printf("\n\t\t QUEUE ");
printf("\n\t 1: Insert - Insert at Last");
printf("\n\t 2: Delete - Delete at front");
printf("\n\t Enter the option : " );
scanf("%d",&op);
switch(op)
{
case 1:
qinsert();
printf("\n\t Queue contents after insertion");
display();
break;
case 2:
pop_del();
printf("\n\t Queue contents after deletion");
display();
break;
default: printf("\n\t Invalid choice: ");
exit(1);
break;

}
break;
case 3: display();
break;
case 4:
exit(1);
break;
default:
printf("\n\t INVALID CHOICE \n");
}
}
}
void stkpush() //insert at front
{
NODE p,next;
p=getnode();
printf("\n\t Enter the element to be inserted at front: ");
scanf("%d",&p->info);

Department of MCA, NHCE Page 28 2017- 2018


Data Structures Using C Laboratory 18MCAL27

if(head->link==NULL)
{
printf("\n\t This is the 1st element of the list");
head->link=p;
p->link=NULL;
}
else
{
next=head->link;
p->link=next;
head->link=p;
}
}
void pop_del() // delete at front
{
NODE cur,next;
if(head->link==NULL)
{
printf("\n\t Empty List - Underflow");
return;
}
cur=head->link;
if(cur->link!=NULL)
{
next=cur->link;
head->link=next;

freenode(cur);
return;
}

head->link=NULL;
freenode(cur);

void qinsert() // insert at back


{
NODE p,temp;
p=getnode();
printf("\n\t Enter the element to be inserted at last: ");
scanf("%d",&p->info);
if(head->link==NULL)
{
printf("\n\t This is the 1st element of the list");
head->link=p;

p->link=NULL;
}
else

Department of MCA, NHCE Page 29 2017- 2018


Data Structures Using C Laboratory 18MCAL27

{
temp=head->link;
while(temp->link != NULL)
temp=temp->link;

temp->link=p;

p->link=NULL;
}
}

void display()
{
NODE p;
if(head->link==NULL)
{
printf("\n\t Empty List");
return;
}
p=head->link;
printf("\n\t output List :\n");
printf("\n Head -->");
while(p->link!=NULL)
{
printf("%d-->",p->info);
p=p->link;
}
printf(" %d",p->info);
printf("-->");
printf("NULL");
}

NODE getnode()
{
NODE p;
p=(NODE)malloc(sizeof(struct node));
return(p);
}

void freenode(NODE p)
{
free(p);
}

Output:

Department of MCA, NHCE Page 30 2017- 2018


Data Structures Using C Laboratory 18MCAL27

Department of MCA, NHCE Page 31 2017- 2018


Data Structures Using C Laboratory 18MCAL27

Department of MCA, NHCE Page 32 2017- 2018


Data Structures Using C Laboratory 18MCAL27

Department of MCA, NHCE Page 33 2017- 2018


Data Structures Using C Laboratory 18MCAL27

Department of MCA, NHCE Page 34 2017- 2018


Data Structures Using C Laboratory 18MCAL27

9. Write a C program to perform the following operations on


circular linked list.
a. Insert at first
b. Delete at the first
c. Delete at the end
d. Delete a given element
e. Display

Algorithm:
Delete at Front:

 Point the link field of the first node to its successor


 Free the memory allocated for first node

Delete at last:

 Traverse the list to find the last node and its predecessor.

 Point the link field of the predecessor to the first node (link field of the last node).
 Free the memory of last node

Delete a given element:

 Find the element and its predecessor in the list.


 Point the link field of the predecessor to the link field of the element node to be deleted.
 Delete the node containing the element by freeing its memory.

Delete alternate element:

 Find the count for even / odd number of nodes.


 Based on the count delete the alternate nodes.

Program:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int elt;
struct node *next;
};
typedef struct node *NODE;

NODE last;
Department of MCA, NHCE Page 35 2017- 2018
Data Structures Using C Laboratory 18MCAL27

void delfront();
void delback();
void delelt();
void insback();
void display();
NODE getnode();
void freenode(NODE);

void main()
{
int ch;
clrscr();
last=NULL;
while(1)
{
printf("\n------------MENU------------");
printf("\n\t 1: INSERT AT BACK");
printf("\n\t 2: DELETE AT FRONT");
printf("\n\t 3: DELETE AT BACK");
printf("\n\t 4: DELETE THE GIVEN ELEMENT");
printf("\n\t 5: DELETE ALTERNATE ELEMENT");
printf("\n\t 6: DISPLAY");
printf("\n\t 7: EXIT");
printf("\n\t ENTER THE CHOICE: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
insback();
display();
break;
case 2:
delfront();
display();
break;
case 3:
delback();
display();
break;
case 4:
delelt();
display();
break;
case 6:
display();
break;
case 7:
exit(1);
break;
default: printf("\n\t INVALID CHOICE\n");

Department of MCA, NHCE Page 36 2017- 2018


Data Structures Using C Laboratory 18MCAL27

}
}
}
void insback()
{
NODE p,temp;
p=getnode();
printf("\n\t Enter the element to be inserted at last: ");
scanf("%d",&p->elt);
if(last==NULL)
{
printf("\n\t This is the 1st element of the list");
last=p;
}
else
p->next=last->next;

last->next=p;
last=p;
}

void delfront()
{

NODE first;
if(last==NULL)
{
printf("\n\t empty list...deletion is not possible.");
return;
}
if(last->next==last) //when there is only one node in the list
{
printf("\n\t Deleted element : %d",last->elt);
printf("\n\t After deletion, list is empty");
free(last);
last=NULL;
return;
}
first=last->next; //points to the first node to be deleted
last->next=first->next; //links to the second node
printf("\n\t Deleted element : %d",first->elt);
freenode(first);
}

void delback()
{
NODE prev;
if(last==NULL)

Department of MCA, NHCE Page 37 2017- 2018


Data Structures Using C Laboratory 18MCAL27

{
printf("\n\t Empty list...deletion is not possible");
return;
}
if(last->next==last)
{
printf("\n\t Deleted element : %d",last->elt);
printf("\n\t After deletion , list is empty");
freenode(last);
last=NULL;
return;
}
prev=last->next; //to traverse from 1st node
while(prev->next != last)
prev=prev->next;

prev->next=last->next; // to point to the 1st node;


printf("\n\t Deleted Element : %d", last->elt);
freenode(last);
last=prev;
}

void delelt()
{
NODE d,prev,temp;
if(last==NULL)
{
printf("\n\t Empty list. Deletion is not possible.");
return;
}
printf("\n\t Enter the element to be deleted: ");
scanf("%d",&d->elt);

if(last->next==last) //if only one elt is present


{
printf("\n\t only one element is present.\n");
if(d->elt==last->elt) //if the elt present is equal to elt to be deleted
{
printf("\n\t element deleted is : %d", last->elt);
freenode(last);
last=NULL;
return;
}
else
{
printf("\n\t Element entered is not present.");
return;
}
}

Department of MCA, NHCE Page 38 2017- 2018


Data Structures Using C Laboratory 18MCAL27

//if the elt to be deleted is present at first

if(last->next->elt==d->elt)
{
printf("\n\t Deleting the 1st element");
delfront();
return;
}
//if the elt to be deleted is present at last
if(last->elt==d->elt)
{
printf("\n\t Deleting the last element");
delback();
return;
}
//otherwise traverse the list from 2nd node to the node before last node

prev=last->next; //points to 1st node


temp=prev->next; //points to 2nd node
while(prev->next!=last)
{
if(temp->elt==d->elt)
{
prev->next=temp->next;
printf("\n\t element deleted is : %d", temp->elt);
freenode(temp);
return;
}
prev=temp;
temp=temp->next;
}
printf("\n\t Element entered is not present");
}

void display()
{
NODE p,temp;

if(last==NULL)
{
printf("\n\t No Elements to Display");
return;
}
temp=last->next;
printf("\n\t THE LIST OF ELEMENTS ARE :\n");
while(temp!=last)
{
printf("%d-->",temp->elt);
temp=temp->next;
}

Department of MCA, NHCE Page 39 2017- 2018


Data Structures Using C Laboratory 18MCAL27

printf("%d--->",temp->elt);
printf("%d",temp->next->elt);
}

NODE getnode()
{
NODE p;
p=(NODE)malloc(sizeof(struct node));
return(p);
}

void freenode(NODE p)
{
free(p);
}

Output:

Department of MCA, NHCE Page 40 2017- 2018


Data Structures Using C Laboratory 18MCAL27

Department of MCA, NHCE Page 41 2017- 2018


Data Structures Using C Laboratory 18MCAL27

11. Implement
a. Selection sort
b. Insertion sort

Algorithm: Selection Sort

Read n array elements


For(i=1 to n-1)
{
Minpos=i;
For(j=i+1 to n)
{
If( a[j]<a[minpos])
Minpos=j;
}
Swap(a[minpos] & a[i])
}
Print sorted element

Insertion Sort

Read n array elements


For(i=1 to n-1)
{
Item=a[i];
J=i-1;
While(j>=0 && item<a[j] )
{
a[j+1]=a[j];
j--;
}
a[j+1]=item;
}

Program:
#include <stdio.h>

int main()
{
int array[100], n, c, d, position, swap;

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]);

Department of MCA, NHCE Page 42 2017- 2018


Data Structures Using C Laboratory 18MCAL27

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


{
position = c;
for ( d = c + 1 ; d < n ; d++ )
{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);

return 0;
}

Output:

Department of MCA, NHCE Page 43 2017- 2018


Data Structures Using C Laboratory 18MCAL27

/* insertion sort ascending order */

#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] < array[d-1]) {
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:

Department of MCA, NHCE Page 44 2017- 2018


Data Structures Using C Laboratory 18MCAL27

11. Implement quick sort.


Algorithm:

1. Pick an element, called a pivot, from the list.


2. Reorder the list so that all elements which are less than the pivot come before the pivot
and so that all elements greater than the pivot come after it (equal values can go either
way). After this partitioning, the pivot is in its final position. This is called
the partition operation.
3. Recursively sort the sub-list of lesser elements and the sub-list of greater elements.

Program:

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

int a[10]; //Elements to be sorted and the sorted vector


int low; //Points to the first element
int high; //Points to the last element
int n; //Number of elements to sort

int part(int low,int high)


{
int i,j,temp,key;
key=a[low]; //First element in the table is the pivot element
i=low;
j=high+1; //Partition the array into two parts
while(i<=j)
{
do i++ ;
while (key>=a[i]);

do j-- ;
while (key<a[j]);
//Partition not completed .Exchange a[i],a[j] and repeat the process
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
//Partition completed and return the position of pivot element
temp=a[low];
a[low]=a[j];
a[j]=temp;
return j;

Department of MCA, NHCE Page 45 2017- 2018


Data Structures Using C Laboratory 18MCAL27

void quick_sort(int low,int high)


{
int pos;
if(low<high)
{
pos=part(low,high); //Partition the array into parts
quick_sort(low,pos-1); //Sort the left part of array
quick_sort(pos+1,high); //Sort the right part of array
}
}
void main()
{
int i;
clrscr();
printf("\n**Quick Sort ********\n");
printf("Enter Array size: ");
scanf("%d",&n);
printf("Enter Array elements: \n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);

quick_sort(1,n);
printf("The sorted array is:\n");
for(i=1;i<=n;i++)
printf("%d ",a[i]);
getch();
}

Output:

Department of MCA, NHCE Page 46 2017- 2018


Data Structures Using C Laboratory 18MCAL27

12. Implement Heap sort.


Algorithm:
 Create the Max Heap by using Top down approach.
 Repeatedly exchange and recreate the heap.
For (i= n-1 downto 0)
Swap the elements a[0] and a[i]
Recreate the heap
End For

Program:
/* Sort the array elements using heap sort. */
#include<stdio.h>
void main()
{
int heap[10], no, i, j, c, root, temp;
clrscr();
printf("\n\t HEAP SORT");
printf("\n Enter no of elements :");

scanf("%d", &no);

printf("\n Enter the nos :\n ");

for (i = 0; i < no; i++)

scanf("%d", &heap[i]);

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

{
c = i;

do

root = (c - 1) / 2;

if (heap[root] < heap[c]) /* to create MAX heap array */

temp = heap[root];

heap[root] = heap[c];

heap[c] = temp;

Department of MCA, NHCE Page 47 2017- 2018


Data Structures Using C Laboratory 18MCAL27

c = root;

} while (c != 0);

printf("Heap array : ");

for (i = 0; i < no; i++)

printf("%d\t ", heap[i]);

for (j = no - 1; j >= 0; j--) // sorting and adjusting the heap

temp = heap[0];

heap[0] = heap[j]; /* swap max element with rightmost leaf element */

heap[j] = temp;

root = 0;

do

c = 2 * root + 1; /* left node of root element */

if ((heap[c] < heap[c + 1]) && c < j-1)

c++;

if (heap[root]<heap[c] && c<j) /* again rearrange to max heap array */

temp = heap[root];

heap[root] = heap[c];

heap[c] = temp;

Department of MCA, NHCE Page 48 2017- 2018


Data Structures Using C Laboratory 18MCAL27

root = c;

} while (c < j);

printf("\n The sorted array is : ");

for (i = 0; i < no; i++)

printf("\t %d", heap[i]);


getch();
}

Output:

Department of MCA, NHCE Page 49 2017- 2018


Data Structures Using C Laboratory 18MCAL27

13. Write a C program to implement the search techniques of


a. Linear Search
b. Binary Search

Algorithm:
SequentialSearch(a[1..n],n,key)
for i = 1 to n do
if(a[i] = key)
return i;
end if
return -1;
end for

Steps for Binary Search:


1. [Initialize segment variables]
Set low=LB
high=UB
mid:=int(low+high)/2
2. repeat steps 3 & 4
while (low<=high and Arr[mid]!=ITEM.)
3. if Item<Arr[mid],then;
Set high:=mid-1.
else
Set low=mid+1.
4. Set mid=int(low+high)/2.
5. if Arr[mid]=Item then:
Set Loc:=mid.
else
Set Loc:=NULL.
6. Exit

Program:

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

void main()
{
int key,n,a[10],i,ch,pos=-1;
clrscr();

printf("Enter the array size:");


scanf("%d",&n);

printf("\nEnter the element...\n");


for(i=0;i<n;i++)
{
Department of MCA, NHCE Page 50 2017- 2018
Data Structures Using C Laboratory 18MCAL27

printf("a[%d]=",i);
scanf("%d",&a[i]);
}
printf("Enter the key to search...");
scanf("%d",&key);

while(ch!=3)
{
printf("\n1.Linear");
printf("\n2.Binary");
printf("\n3.Exit");
printf("\nEnter the choice...");
scanf("%d",&ch);
switch(ch)
{
case 1:{
pos=l(a,n,key);
if(pos!=-1)
{
printf("Found at %d",key);
}
else
{
printf("Not Found");
}
break;
}
case 2:{
pos=b(a,n,key);
if(pos==-1)
{
printf("Not Found");
}
else
{
printf("Element found at pos %d",pos);
}
break;
}
case 3:{
exit(0);
}
default: printf("Invalid choice...");
}
getch();
}
}

int l(int a[],int n,int key)

Department of MCA, NHCE Page 51 2017- 2018


Data Structures Using C Laboratory 18MCAL27

{
int i,pos=-1;
for(i=0;i<n;i++)
{
if(key==a[i])
{
pos=i;
}
}
return pos;
}

int b(int a[],int n,int key)


{
int high,mid,low,pos;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
return (mid);
else if(key<a[mid])
high=mid-1;
else if(key>a[mid])
low=mid+1;
}
return(-1);
}

Output:

Department of MCA, NHCE Page 52 2017- 2018


Data Structures Using C Laboratory 18MCAL27

Department of MCA, NHCE Page 53 2017- 2018


Data Structures Using C Laboratory 18MCAL27

14. Write a C program to Create a binary search tree and


implement the tree traversal techniques of inorder, preorderand
postorder.

Algorithm:
Creating a BINARY SEARCH TREE

1. Given a set of elements that takes the first element as a root node.
2. for each of the remaining element(ITEM).
a. Compare ITEM with the root node of the tree.
i. If (ITEM<root node)
Proceed to the left of the root node.
ii. If (ITEM>root node)
Proceed to the right of the root node.
b. Repeat step(a) until we meet an empty sub tree.
3. Insert ITEM in place of empty sub tree.

Procedure for Pre-order Traversal

1. Visit the ROOT node N.


2. Traverse the LEFT SUB TREE in Pre-order.
3. Traverse the RIGHT SUB TREE in Pre-order.

Procedure for In-order Traversal

1. Traverse the LEFT SUB TREE in In-order.


2. Visit the ROOT node N.
3. Traverse the RIGHT SUB TREE in In-order.

Procedure for Post-order Traversal

1. Traverse the LEFT SUB TREE in Post-order.


2. Traverse the RIGHT SUB TREE in Post-order.
3. Visit the ROOT node N

Program:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
int num;
struct node *left,*right;

Department of MCA, NHCE Page 54 2017- 2018


Data Structures Using C Laboratory 18MCAL27

};

typedef struct node* NODE;

NODE create(NODE root);


void inorder(NODE root);
void preorder(NODE root);
void postorder(NODE root);

void main()
{
NODE root=NULL;
int ch;
clrscr();
for(;;)
{
printf("\n 1. Create Binary Tree");
printf("\n 2. In-order Traversal");
printf("\n 3. Pre-order Traversal");
printf("\n 4. Post-order Traversal");
printf("\n 5. Exit");
printf("\n Enter the choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1 : root=create(root);
break;
case 2 : if (root==NULL)
printf("\n\t Tree is NULL");
else
inorder(root);
break;
case 3 : if (root==NULL)
printf("\n\t Tree is null, traversing is not possible");
else
preorder(root);
break;
case 4 : if (root==NULL)
printf("\n\t Tree is null, traversing is not possible");
else

postorder(root);
break;

case 5 : exit(0);
break;
default : printf("\n Invalid option");
break;
}
}

Department of MCA, NHCE Page 55 2017- 2018


Data Structures Using C Laboratory 18MCAL27

NODE create(NODE root)


{
NODE newnode,temp,prev;
int num;
newnode=(NODE)malloc(sizeof(struct node));
printf("\n Enter item to be added to the tree:\n");
scanf("\n%d",&num);

newnode->num=num;
newnode->left=NULL;
newnode->right=NULL;

if(root==NULL)
{
return newnode;
}

temp=root;
prev=root;

while(temp!=NULL)
{
prev=temp;
if(num<temp->num)
{
temp=temp->left;
}
else if(num>temp->num)
{
temp=temp->right;
}
else
{
printf("\n Value already exists");
return root;
}
}

if(num<prev->num)
{
prev->left=newnode;
}
else
{
prev->right=newnode;

Department of MCA, NHCE Page 56 2017- 2018


Data Structures Using C Laboratory 18MCAL27

}
return root;
}

void inorder(NODE root)


{
if(root!=NULL)
{
inorder(root->left);
printf("%d\t",root->num);
inorder(root->right);
}

}
void preorder(NODE root)
{
if(root!=NULL)
{
printf("%d\t",root->num);
preorder(root->left);
preorder(root->right);
}
}
void postorder(NODE root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d\t",root->num);

}
}

Department of MCA, NHCE Page 57 2017- 2018


Data Structures Using C Laboratory 18MCAL27

Output:

Department of MCA, NHCE Page 58 2017- 2018

You might also like