0% found this document useful (0 votes)
1 views106 pages

Cds Lab Record (Overall)

The document is a practical record for MCA I semester students at Gayatri Vidya Parishad College of Engineering, detailing various C programming experiments completed during the academic year 2020-21. It includes a list of experiments covering topics such as Fibonacci sequences, prime number generation, data structures like stacks and queues, and algorithms for searching and sorting. Each experiment is accompanied by sample code and expected outputs, showcasing the practical application of programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views106 pages

Cds Lab Record (Overall)

The document is a practical record for MCA I semester students at Gayatri Vidya Parishad College of Engineering, detailing various C programming experiments completed during the academic year 2020-21. It includes a list of experiments covering topics such as Fibonacci sequences, prime number generation, data structures like stacks and queues, and algorithms for searching and sorting. Each experiment is accompanied by sample code and expected outputs, showcasing the practical application of programming concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

GAYATRI VIDYA PARISHAD COLLEGE OF ENGINEERING

(AUTONOMOUS)
Madhurawada, Visakhapatnam-530048

COLLEGE OF ENGINEERING
(AUTONOMOUS)

CERTIFICATE

Certified that this is a bonifide record of practical done by

______ bearing

Roll No. of MCA I semester successfully completed

Introduction to CDS programming lab from the department of

computer applications during the academic year 2020-21.

No. of Experiments done:


Signature of the Faculty

Signature of Internal Examiner:

Signature of External Examiner:


INDEX
S.NO Nameof the Experiments Date Page Marks Remarks
No. Awarded
1 a) Write a C program to find the 1
sum of individual digits of a
positiveinteger.
b) A Fibonacci sequence is defined
as follows: the first and second
termsin the sequence are 0 and 1.
Subsequent terms are found by 1-2
adding thepreceding two terms in
the sequence. Write a C program to
generatethe first n terms of the
sequence
C)Write a C program to generate all
the prime numbers between 1 and
n,where n is a value supplied by the
2-3
user
d) Write a program which checks a
given integer is Fibonacci number
or not.
3-4
2 a) Write a C program to calculate
thefollowing Sum: Sum=1-
x2/2!+x4/4!-x6/6!+x8/8!-x10/10!
4
b) Write a C program to find the 5-6
roots of a quadratic equation
3 3 a) Write C programs that use both
recursive and non-recursive
functions i) To find the factorial of
6-7
a given integer.
4 Write C programs that implement
the following data structures using
arrays: i) Stack ii) Queue.
7-16
5 Write C programs to implement the
following Stack applications i)
Factorial ii) Evaluations of postfix
16-21
expression
6 Write C program to implement the
following types of queues i) Linear
Queue ii) Circular Queue.
21-28
Write C programs to implement the
7 following types of Lists i) Singly
linked list ii) Circular Linked list
28-51
iii) Doubly linked list.
Write C programs to implement the
8 following data structures using Lists
i) Stack ii) Queue.
51-62
9 Write C programs to implement the 62-64
following search algorithms: i)
Linear Search ii) Binary Search
Write C programs to implement the
following sorting algorithms i)
64-66
10 Bubble Sort ii) Insertion Sort
Write C programs to implement the
11 following sorting algorithms
i) Quick Sort
66-68
Write a C program to implement
12 binary tree using arrays and to
perform binary tree traversals i)
68-85
inorder ii) postorder iii) preorder.
Write a C program to perform the
following operations using linked
lists: i)Insert an element into a
binary search tree.ii) Delete an 85-88
13
element from a binary search tree.
iii) Search for a key element in a
binary search tree.
Write C programs for the
14 implementation of bfs and dfs for a
given graph.
88-91
Write a C program for the
implementation of Prim’s algorithm
15 to obtain the minimum cost
spanning tree from a connected 91=94
undirected graph.
Write a C program to implement
16 Dijkstra’s algorithm for the single
source shortest path problem
94-96
1)a)Write a c program to find the sum of individual digits of a given
number.
#include<stdio.h>
#include<conio.h>
void main()
{
int n,s,p;
clrscr();
printf(“enter the value for n:”);
scanf(“%d”,&n);
s=0;
if(n<0)
printf(“the given number is not valid:”);
else
{
while(n!=0)
{
p=n%10;
n=n/10;
s=s+p;
}
printf(“sum of individual digits is %d”,s);
}
}
Output:
1)Enter the value for n: 333
Sum of individual digits is 9
2)Enter the value for n: 4733
Sum of individual digits is 17
b) Write a program to print the Fibonacci series for n values.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,n,i;
clrscr();
printf(“enter n values”);
scanf(“%d”,&n);
a=0;
b=1;
1
if(n==1)
printf(“%d”,a);
else
if(n==2)
printf(“%d%d”,a,b);
else
{
printf(“%d%d”,a,b);
for(i=2;i<n;i++)
{
c=a+b;
printf(“%d”,c);
a=b;
b=c;
}
}
}
Output:
1)Enter the number: 5
01123
2)Enter the number: 7
0112358
c) Write a C program to print the prime numbers between 1 to n,
where n is value supplied by the user.
#include<stdio.h>
#include<conio.h>
void main()
{
int n, i, fact, j;
clrscr();
printf(“enter the number:”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
fact=0;
for(j=1;j<=I;j++)
{
if(i%j==0)
fact++;
}
2
if(fact==2)
printf(“\n%d”,i);
}
}
Output:
1)Enter the number: 5
235
2)Enter the number: 10
2357

d) Write a program which checks a given integer is Fibonacci


number or not.

#include<stdio.h>
int main()
{
int a,b,c,next,num;
printf("Enter any number: ");
scanf("%d", &num);
if((num==0)||(num==1))
printf("\n%d is a Fibonacci term",num);
else
{
a=0;
b=1;
c=a+b;
while(c<num)
{
a=b;
b=c;
c=a+b;
}
if(c==num)
printf("\n%d is a Fibonacci term",num);
else
printf("\n%d is not a Fibonacci term",num);
}
return 0;
}

3
Output:-
Enter any number: 5

5 is a Fibonacci term

2) a) Write a c program to calculate the following sum:


Sum=1-x2/2!+x4/4!-x6/6!+x8/8!-x10/10!
#include<stdio.h>
#include<conio.h>
#include<math.h>
long fact(int);
void main()
{
int x,i,n;
float s=0,c;
clrscr();
printf(“enter the value of x”);
for(i=0,n=0;i<=10;i=i+2,n++)
s=s+(pow(-1,n)*pow(x,i)/fact(i));
printf(“the result is %f”,s);
}
long fact(int x)
{
long int y=1;
while(x!=0)
{
y=y*x;
x--;
}
return y;
}
Output:
1)Enter the value of x: 1
The result is 0.540302
2)enter the value of x: 2
The result is -0.416155

4
b) Write a C program to find the root of a quadratic equation .
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,r1,r2,d;
clrscr();
printf(“Enter the values for equation:”);
scanf(“%f%f%f”,&a,&b,&c);
if(a==0)
printf(“Enter value should not be zero”);
else
{
d=b*b-4*a*c;
if(d>0)
{
r1=(-b+sqrt(d)/(2*a));
r2=(-b-sqrt(d)/(2*a));
printf(“roots are real and unequal\n”);
printf(“%f\n%f\n”,r1,r2);
}
else
if(d==0)
{
r1=-b/(2*a);
r2=-b/(2*a);
printf(“roots are real and equal\n”);
printf(“root=%f\n”,r1);
printf(“root=%f\n”,r2);
}
else
printf(“roots are imaginary”);
}
}
Output:
1)Enter the values for equation: 1,6,9
Roots are real and equal
Root= -3.0000
Root= -3.0000
5
2)Enter the values for equation: 2,7,6
Roots are real and unequal
Root= -6.75
Root= -7.25
3) a) Write a C program that use both recursive and non-
recursive functions. To find the factorial of a given integer.
i)Recursive Function Program:
#include<stdio.h>
#include<conio.h>
int fact(int n)
{
int f;
if((n==0)||(n==1))
return(n);
else
f=n*fact(n-1);
return(f);
}
void main()
{
int n;
clrscr();
printf(“enter the number:”);
scanf(“%d”,&n);
printf(“factorial of number %d”,fact(n));
}
Output:
1)Enter the number: 5
Factorial of number: 120
2)Enter the number: 3
Factorial of number: 6

ii)Non-Recursive Function Program:


#include<stdio.h>
#include<conio.h>
int fact(int n)
{
int f=1,i;
if((n==0)||(n==1))
return(1);
6
else
for(i=1;i<=n;i++)
f=n*fact(n-1);
return(f);
}
void main()
{
int n;
clrscr();
printf(“enter the number:”);
scanf(“%d”,&n);
printf(“factorial of number %d”,fact(n));
}

Output:
1)Enter the number: 7
Factorial of number: 5040
2)Enter the number: 6
Factorial of number: 720
4. Write a C programs that implement the following data
structures using arrays,pointers and functions.
(i)Stack (ii)Queue

(i)Stack program
#include<stdio.h.
#include<alloc.h>
// 1. Data Organiztion
struct stack
{
int a[10]; // Array implementation
int tos; // Top of Stack
};
// alias name for is st
typedef struct stack st;
st* create(); // Allocating memory for the data elements
void init(st *p); // init array ele to zero and tos = -1
void print(st *p); // display all elements in the stack
int get_tos(st *p);
// returing present tos value
void push(st *p,int val);
7
// is_full is false then can call push operation
int pop(st *p);
//is_empty is false then can call pop operation
int is_empty(st *p); // validation , under flow 1- true / 0- false
// TOS = -1 ,is_empty must return 1 can not call pop function
// other wise 0 can call pop function
int is_full(st *p); // validation - over flow 1- true / 0- false
// TOS = 9 is_full must return 1
// otherwise return 0
int is_full(st *p)
{
int flag;
int count;
count = get_tos(p);//getting TOS
if (count == 9)
{
flag = 1; // if stack full , set flag as 1, TRUE
}
else
{
flag = 0; // else FALSE
}
return flag;
}

int pop(st *p)


{
int index;int val=0;
if(is_empty(p)) // is_empty is true - under flow condition
{
printf("Stack --- UNDER FLOW\n\n");
}
else
{
index = get_tos(p); //get TOS
val = p->a[index]; // get the value to be deleted, store in val
p->a[index] = 0; // reset the pos as zero
index = index - 1; // decrement TOS
p->tos = index; // assign latest TOS
}

8
return val; // return the val , which is deleted
}
void push(st *p,int val)
{
int index;
if (is_full(p)) // is_full TRUE , Over flow condition
{
printf("Stack --- OVER FLOW \n\n");
}
else
{
index = get_tos(p); // otherwise, get TOS, store in index
index = index+1; // increment TOS by 1
p->tos = index; // assign latest TOS
p->a[index] = val; // Place the value in the stack
}
}
int is_empty(st *p)
{
int flag;
int count;
count = get_tos(p); // getting TOS
if (count == -1) // TOS = -1 set flag as 1, true
{ // UNDER FLOW condition
flag = 1;
}
else
{
flag = 0; // flag is 0, false
} // implies Stack NOT EMpty
return flag; // return flag
}
st* create()
{
st *p=NULL;
p = (st*) malloc(sizeof(st));
return p;
}
void init(st *p)
{

9
int i;
p->tos = -1;
for(i=0;i<10;i++)
p->a[i]=0;
}
void print(st *p)
{
int i;
for(i=0;i<10;i++)
printf("%d \t ",p->a[i]);
}
int get_tos(st *p)
{
return p->tos;
}
void main()
{
st *p=NULL; int option;int val;
p=create();
init(p);
print(p);
printf("%d The Top of Stack ",get_tos(p));
while(1)
{
val=0;
printf("\n 1. Push \n");
printf("\n 2. Pop \n");
printf("\n 3. Traverse \n");
printf("\n 4. Top of Stack\n");
printf("\n 5. Exit \n");
printf("Enter your Option ");
scanf("%d",&option);
switch(option)
{
case 1: // push
printf("Enter value to be pushed ");
scanf("%d",&val);
push(p,val);
break;
case 2: // pop

10
val = pop(p);
printf("The Poped val is %d ",val);
break;
case 3: // Traverse or View
print(p);
break;
case 4: // Get Top of stack
printf("The Top of Stack is %d ",get_tos(p));
break;
case 5: exit(0);
break;
default: printf("Enter Proper option \n\n");
} // End of Switch Case
} // End of While Loop
}
Output:
0 0 0 0 0
0 0 0 0 0
-1 The Top of Stack
1. Push
2. Pop
3. Traverse
4. Top of Stack
5. Exit
Enter your Option 1
Enter value to be pushed 10
1. Push
2. Pop
3. Traverse
4. Top of Stack
5. Exit
Enter your Option 1
Enter value to be pushed 20
1. Push
2. Pop
3. Traverse
4. Top ofStack
5. Exit
Enter your Option 2
The poped val is 20
11
1. Push
2. Pop
3. Traverse
4. Top of Stack
5. Exit
Enter your Option 3
10 0 0 0 0
0 0 0 0 0
1. Push
2. Pop
3. Traverse
4. Top of Stack
5. Exit
Enter your Option 4
The Top of Stack is 0
1. Push
2. Pop
3. Traverse
4. Top of Stack
5. Exit
Enter your Option 5
Exit
(ii)Queue Program

#include<stdio.h>
#include<alloc.h>
#define SIZE 5
struct que
{
int a[SIZE]; // size of que
int front; // maintains counter for deletions
int rear; // maintains counter for insertions
};
typedef struct que queue;
queue* create(); // allocates momory space dynamically
void init(queue *p); // init the QUEUE Data structure
void print(queue *p); // displaying all the contents in the Queue
void insert(queue *p,int val); // insert an element in the queue
// also passing value to be inserted
int delete(queue *p); // deleting an element from the queue
12
// returns the deleted value
queue* create()//create function definition
{
queue *p = NULL;//assigning default null value to pointer
p = (queue*) malloc(sizeof(queue));//allocation of memory
return p;
}//end of create function
void init(queue *p)//init function definition
{
int i; // Iterative variable
printf("\n\n Init \n\n");
for(i=0;i<SIZE;i++)
{
p->a[i] = 0;
}
p->front = 0; // Delete counter
p->rear = -1; // Insert counter
}//end of init function
void print(queue *p)//print function definition
{
int i;
printf("\n\n Dispaying all the contents of QUeue\n\n");
for(i=0;i<SIZE;i++)
{
printf("%d\t",p->a[i]);
}
printf("\nREAR VALUE \t %d",p->rear);
printf("\tFRONT VALUE \t %d\n",p->front);
}//end of print function
void insert(queue *p,int val)//insert function definition
{
int index;
if(p->rear < (SIZE-1)) // Validations
{
p->rear = p->rear + 1;
index = p->rear;
p->a[index] = val;
}
else
{

13
printf("\n\nTHE QUE is already FULL \n\n ");
}
}//end of insert function definition
int delete(queue *p)//delete function definition
{
int index; int val;
if(p->front < SIZE) // Validations
{
index = p->front;
val = p->a[index];
p->a[index] = 0;
p->front = p->front + 1;
}
else
{
printf("\n\n QUE is Empty \n\n");
val=0;
}
return val;
}//end of delete function definition
void main()//main function
{
int option;
int Val;
queue *p=NULL;
p = create();
init(p);//function call
print(p);
while(1)
{
printf("\n 1.Insert\t2.Delete\t3.Display\t4.Exit\n\n");
printf("enter option ");
scanf("%d",&option);
switch(option)
{
case 1: //insert
{
printf("enter elements to insert ");
scanf("%d",&Val);
insert(p,Val);}

14
break;
case 2: //delete
{
Val=delete(p);
printf("deleted element %d",Val);
}
break;
case 3: //display
print(p);
break;
case 4: exit(0);
break;
default: printf("enter proper option ");
}//end of switch
}//end of while
}//end of main

Output :

Displaying all the contents of Queue


0 0 0 0 0
REAR VALUE -1 FRONT VALUE
0
1.Insert 2.Delete 3.Display 4.Exit
enter option 1
enter elements to insert 10
1.Insert 2.Delete 3.Display 4.Exit
enter option 1
enter elements to insert 20
1.Insert 2.Delete 3.Display 4.Exit
enter option 3
Displaying all the contents of Queue
10 20 0 0 0
REAR VALUE 1 FRONT VALUE
0
enter option 2
deleted element 10
1.Insert 2.Delete 3.Display 4.Exit
enter option 3
Displaying all the contents of Queue

15
0 20 0 0 0
REAR VALUE 1 FRONT VALUE
1
1.Insert 2.Delete 3.Display 4.Exit
enter option 4
Exit
5. Write C programs to implement the following Stack
applications.
(i)Conversion of postfix expression (ii)Evaluations of postfix
expression.
(i)Conversion of postfix expression.
#include<stdio.h>
#include"stack.h"

int char_status(char ch);


// assumptions
// 1. implies char is a open parenthesis (
// 2. implies that char is close parenthesis )
// 3. implies that it is an operand
// ASCII values
// numerial 0 -9 => 48 - 57 ascii values
// Alphabet A - Z => 65 - 90
// Alphabets a - z => 97 - 122
// 4. operator +, -, *, /
// any other char whose ascii value is NOT in the
// above range

int char_status(char ch)


{
int flag=0;
if (ch == '(') { flag= 1; }
else if (ch == ')') { flag = 2; }
else if ((ch >=65 && ch<= 90) || (ch >= 97 && ch <= 122))
{ flag = 3; } else { flag = 4; } return flag;
}
void main()
{
st *p=NULL; int pop1,pop2; char ch;
char *expn=""; char *out=""; int count=0;
int asc; // return values from char_status int len;
16
int i;
//////////////////////// stack p = create();
init(p); printf("\n"); print(p);
/////////////////////// stack
// Read input
printf("Enter your Expression ");
scanf("%s",expn); // Input of the expression in string form
for(i=0;expn[i]!='\0';i++); // Length of the input String
len = i; // len is holding actual length of input string

printf("The Input Expn is %s ", expn); printf("the len of Str %d ",len);


// logic of the program to convert a given infix form to postfix form

for(i=0;i<len;i++)
{
ch = expn[i];
asc = char_status(ch); if (asc == 1)
{ // open ( - 40
// close ) - 41
// open parenthesis push(p,(int)ch);

printf("\n %c from 1",ch);


}
else if (asc == 2)
{ // handle ) close parenthesis pop1 = pop(p);

printf("\n %c from 2",ch); out[count] = (char)pop1; count = count + 1;


pop2 = pop(p); // discard
}
else if (asc == 3)
{
// Operands
out[count] = ch; // placing the char in the out str printf("\n %c from 3 ",ch);
count = count +1 ;
}
else
{
// operators
push(p,(int)ch); printf("\n%c from 4 ",ch);
}

17
} // for loop end out[count] ='\0';
printf("\n The out put %s \n",out); printf("poped val %d ",pop2);
}

Output:
Enter your Expression ((a+b)*(c+d))
The Input Expn is((a+b)*(c+d))The len of str 13 ( from 1
( from 1
a from 3
+ from 4
b from 3
) from 2
* from 4
( from 1
c from 3
+ from 4
d from 3
) from 2
) from 2
The output is ab+cd+*

(ii)Evaluations of postfix expression.


#include <stdio.h>
#include <ctype.h>

#define MAXSTACK 100 /* for max size of stack */


#define POSTFIXSIZE 100 /* define max number of charcters in postfix
expression */

/* declare stack and its top pointer to be used during postfix expression
evaluation*/
int stack[MAXSTACK];
int top = -1; /* because array index in C begins at 0 */
/* can be do this initialization somewhere else */

/* define push operation */ void push(int item)


{

if (top >= MAXSTACK - 1) {


printf("stack over flow"); return;
18
}
else {
top = top + 1; stack[top] = item;
}
}

/* define pop operation */ int pop()


{
int item;
if (top < 0) {
printf("stack under flow");
}
else {
item = stack[top]; top = top - 1; return item;
}
}

/* define function that is used to input postfix expression and to evaluate it */


void EvalPostfix(char postfix[])
{

int i; char ch; int val; int A, B;

/* evaluate postfix expression */ for (i = 0; postfix[i] != ')'; i++) {


ch = postfix[i]; if (isdigit(ch)) {
/* we saw an operand,push the digit onto stack
ch - '0' is used for getting digit rather than ASCII code of digit */ push(ch - '0');
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
/* we saw an operator
pop top element A and next-to-top elemnet B
from stack and compute B operator A
*/
A = pop();
B = pop();

switch (ch) /* ch is an operator */


{
case '*':

19
val = B * A; break;

case '/':
val = B / A; break;

case '+':
val = B + A; break;

case '-':
val = B - A; break;
}

/* push the value obtained above onto the stack */ push(val);


}
}
printf(" \n Result of expression evaluation : %d \n", pop());
}

int main()
{

int i;

/* declare character array to store postfix expression */ char


postfix[POSTFIXSIZE];
printf("ASSUMPTION: There are only four operators(*, /, +, -) in an expression
and operand is single digit only.\n");
printf(" \nEnter postfix expression,\npress right parenthesis ')' for end expression
: ");

/* take input of postfix expression from user */

for (i = 0; i <= POSTFIXSIZE - 1; i++) {


scanf("%c", &postfix[i]);

if (postfix[i] == ')') /* is there any way to eliminate this if */


{
break;
} /* and break statement */
}

20
/* call function to evaluate postfix expression */ EvalPostfix(postfix);
return 0;
}

Output:-
ASSUMPTION: There are only four operators(*, /, +, -) in an expression and
operand is single digit only.

Enter postfix expression,


press right parenthesis ')' for end expression : 3+2*(4-1) stack under flow

Result of expression evaluation : 1

6. Write C program to implement the following types of queues


i) Linear Queue ii) Circular Queue
i)Linear Queue
#include<stdio.h>
#include<alloc.h>
#define SIZE 5
struct que
{
int a[SIZE]; // size of que
int front; // maintains counter for deletions
int rear; // maintains counter for insertions
};
typedef struct que queue;
queue* create(); // allocates momory space dynamically
void init(queue *p); // init the QUEUE Data structure
void print(queue *p); // displaying all the contents in the Queue
void insert(queue *p,int val); // insert an element in the queue
// also passing value to be inserted
int delete(queue *p); // deleting an element from the queue
// returns the deleted value
queue* create()//create function definition
{
queue *p = NULL;//assigning default null value to pointer
p = (queue*) malloc(sizeof(queue));//allocation of memory
return p;
}//end of create function
21
void init(queue *p)//init function definition
{
int i; // Iterative variable
printf("\n\n Init \n\n");
for(i=0;i<SIZE;i++)
{
p->a[i] = 0;
}
p->front = 0; // Delete counter
p->rear = -1; // Insert counter
}//end of init function
void print(queue *p)//print function definition
{
int i;
printf("\n\n Dispaying all the contents of Linear Queue\n\n");
for(i=0;i<SIZE;i++)
{
printf("%d\t",p->a[i]);
}
printf("\nREAR VALUE \t %d",p->rear);
printf("\tFRONT VALUE \t %d\n",p->front);
}//end of print function
void insert(queue *p,int val)//insert function definition
{
int index;
if(p->rear < (SIZE-1)) // Validations
{
p->rear = p->rear + 1;
index = p->rear;
p->a[index] = val;
}
else
{
printf("\n\nTHE Linear Queue is already FULL \n\n ");
}
}//end of insert function definition
int delete(queue *p)//delete function definition
{
int index; int val;
if(p->front < SIZE) // Validations

22
{
index = p->front;
val = p->a[index];
p->a[index] = 0;
p->front = p->front + 1;
}
else
{
printf("\n\n Linear Queue is Empty \n\n");
val=0;
}
return val;
}//end of delete function definition
void main()//main function
{
int option;
int Val;
queue *p=NULL;
p = create();
init(p);//function call
print(p);
while(1)
{
printf("\n 1.Insert\t2.Delete\t3.Display\t4.Exit\n\n");
printf("enter option ");
scanf("%d",&option);
switch(option)
{
case 1: //insert
{
printf("enter elements to insert ");
scanf("%d",&Val);
insert(p,Val);}
break;
case 2: //delete
{
Val=delete(p);
printf("deleted element %d",Val);
}
break;

23
case 3: //display
print(p);
break;
case 4: exit(0);
break;
default: printf("enter proper option ");
}//end of switch
}//end of while
}//end of main
Output :
Displaying all the contents ofLinear Queue
0 0 0 0 0
REAR VALUE -1 FRONT VALUE
0
1.Insert 2.Delete 3.Display 4.Exit
enter option 1
enter elements to insert 10
1.Insert 2.Delete 3.Display 4.Exit
enter option 1
enter elements to insert 20
1.Insert 2.Delete 3.Display 4.Exit
enter option 3
Displaying all the contents of Linear Queue
10 20 0 0 0
REAR VALUE 1 FRONT VALUE
0
enter option 2
deleted element 10
1.Insert 2.Delete 3.Display 4.Exit
enter option 3
Displaying all the contents of Linear Queue
0 20 0 0 0
REAR VALUE 1 FRONT VALUE
11.Insert 2.Delete 3.Display 4.Exit
enter option 4
Exit

ii) Circular Queue

#include<stdio.h>
24
#include<conio.h>
# define MAX 5
int cqueue_arr[MAX];
int front = -1;
int rear = -1;
void insert(int item)
{
if((front == 0 && rear == MAX-1) || (front == rear+1))
{
printf("Queue Overflow n");
return;
}
if(front == -1)
{
front = 0;
rear = 0;
}
else
{
if(rear == MAX-1)
rear = 0;
else
rear = rear+1;
}
cqueue_arr[rear] = item ;
}
void deletion()
{
if(front == -1)
{
printf("Queue Underflow");
return ;
}
printf("Element deleted from queue is : %d",cqueue_arr[front]);
if(front == rear)
{
front = -1;
rear=-1;
}
else

25
{
if(front == MAX-1)
front = 0;
else
front = front+1;
}
}
void display()
{
int front_pos = front,rear_pos = rear;
if(front == -1)
{
printf("Queue is empty");
return;
}
printf("Queue elements :");
if( front_pos <= rear_pos )
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
else
{
while(front_pos <= MAX-1)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
front_pos = 0;
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
}
printf("n");
}
int main()
{

26
int choice,item;
do
{
printf("\n1.Insert");
printf("\n2.Delete");
printf("\n3.Display");
printf("\n4.Quit");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Input the element for insertion in queue : ");
scanf("%d", &item);
insert(item);
break;
case 2 :
deletion();
break;
case 3:
display();
break;
case 4:
break;
default:
printf("Wrong choice");
}
}while(choice!=4);
return 0;
}

Output:-
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 1
Input the element for insertion in queue : 10

1.Insert
27
2.Delete
3.Display
4.Quit
Enter your choice : 1
Input the element for insertion in queue : 20

1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 2
Element deleted from queue is : 10
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 3
Queue elements :20
1.Insert
2.Delete
3.Display
4.Quit
Enter your choice : 4

7. Write C programs to implement the following types of Lists


i) Single linked list ii) Circular Linked list iii) Double linked list.

i) Single linked list

#include <stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
void create();
void display();
void insert_begin();
void insert_end();
void insert_pos();
void delete_begin();
28
void delete_end();
void delete_pos();
struct node
{
int info;
struct node *next;
};
struct node *start=NULL;
int main()
{
int choice;
while(1)
{
printf("\n MENU:");
printf("\n 1.Create");
printf("\n 2.Display");
printf("\n 3.Insert at the beginning");
printf("\n 4.Insert at the end");
printf("\n 5.Insert at specified positio");
printf("\n 6.Delete from beginning");
printf("\n 7.Delete from the end");
printf("\n 8.Delete from specified position");
printf("\n 9.Exit");
printf("\n---------------------------------");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
create();
break;
case 2:
display();
break;
case 3:
insert_begin();
break;
case 4:
insert_end();
break;

29
case 5:
insert_pos();
break;
case 6:
delete_begin();
break;
case 7:
delete_end();
break;
case 8:
delete_pos();
break;

case 9:
exit(0);
break;

default:
printf("\n Wrong Choice:");
break;
}
}
return 0;
}
void create()
{
struct node *temp,*ptr;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\nOut of Memory Space:");
exit(0);
}
printf("\nEnter the data value for the node:");
scanf("%d",&temp->info);
temp->next=NULL;
if(start==NULL)
{
start=temp;
}

30
else
{
ptr=start;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=temp;
}
}
void display()
{
struct node *ptr;
if(start==NULL)
{
printf("\nList is empty:");
return;
}
else
{
ptr=start;
printf("\nThe List elements are:");
while(ptr!=NULL)
{
printf("%d",ptr->info );
ptr=ptr->next ;
}
}
}
void insert_begin()
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\nOut of Memory Space:");
return;
}
printf("\nEnter the data value for the node:" );
scanf("%d",&temp->info);

31
temp->next =NULL;
if(start==NULL)
{
start=temp;
}
else
{
temp->next=start;
start=temp;
}
}
void insert_end()
{
struct node *temp,*ptr;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\nOut of Memory Space:");
return;
}
printf("\nEnter the data value for the node:");
scanf("%d",&temp->info );
temp->next =NULL;
if(start==NULL)
{
start=temp;
}
else
{
ptr=start;
while(ptr->next !=NULL)
{
ptr=ptr->next ;
}
ptr->next =temp;
}
}
void insert_pos()
{
struct node *ptr,*temp;

32
int i,pos;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("\nOut of Memory Space:");
return;
}
printf("\nEnter the position for the new node to be inserted:");
scanf("%d",&pos);
printf("\nEnter the data value of the node:");
scanf("%d",&temp->info) ;

temp->next=NULL;
if(pos==0)
{
temp->next=start;
start=temp;
}
else
{
for(i=0,ptr=start;i<pos-1;i++) { ptr=ptr->next;
if(ptr==NULL)
{
printf("\nPosition not found:[Handle with care]");
return;
}
}
temp->next =ptr->next ;
ptr->next=temp;
}
}
void delete_begin()
{
struct node *ptr;
if(ptr==NULL)
{
printf("\nList is Empty:");
return;
}
else

33
{
ptr=start;
start=start->next ;
printf("\nThe deleted element is :%d",ptr->info);
free(ptr);
}
}
void delete_end()
{
struct node *temp,*ptr;
if(start==NULL)
{
printf("\nList is Empty:");
exit(0);
}
else if(start->next ==NULL)
{
ptr=start;
start=NULL;
printf("\nThe deleted element is:%d",ptr->info);
free(ptr);
}
else
{
ptr=start;
while(ptr->next!=NULL)
{
temp=ptr;
ptr=ptr->next;
}
temp->next=NULL;
printf("\nThe deleted element is:%d",ptr->info);
free(ptr);
}
}
void delete_pos()
{
int i,pos;
struct node *temp,*ptr;
if(start==NULL)

34
{
printf("\nThe List is Empty:");
exit(0);
}
else
{
printf("\nEnter the position of the node to be deleted:");
scanf("%d",&pos);
if(pos==0)
{
ptr=start;
start=start->next ;
printf("\nThe deleted element is:%d",ptr->info );
free(ptr);
}
else
{
ptr=start;
for(i=0;i<pos;i++) { temp=ptr; ptr=ptr->next ;
if(ptr==NULL)
{
printf("\nPosition not Found:");
return;
}
}
temp->next =ptr->next ;
printf("\nThe deleted element is:%d",ptr->info );
free(ptr);
}
}
}

Output:-
MENU:
1.Create
2.Display
3.Insert at the beginning
4.Insert at the end
5.Insert at specified positio
6.Delete from beginning
35
7.Delete from the end
8.Delete from specified position
9.Exit
---------------------------------
Enter your choice:1
Enter the data value for the node:10

MENU:
1.Create
2.Display
3.Insert at the beginning
4.Insert at the end
5.Insert at specified positio
6.Delete from beginning
7.Delete from the end
8.Delete from specified position
9.Exit
---------------------------------
Enter your choice:1

Enter the data value for the node:20

MENU:
1.Create
2.Display
3.Insert at the beginning
4.Insert at the end
5.Insert at specified positio
6.Delete from beginning
7.Delete from the end
8.Delete from specified position
9.Exit
---------------------------------
Enter your choice:2

The List elements are:1020


MENU:
1.Create
2.Display
3.Insert at the beginning

36
4.Insert at the end
5.Insert at specified positio
6.Delete from beginning
7.Delete from the end
8.Delete from specified position
9.Exit
---------------------------------
Enter your choice:4

Enter the data value for the node:40

MENU:
1.Create
2.Display
3.Insert at the beginning
4.Insert at the end
5.Insert at specified positio
6.Delete from beginning
7.Delete from the end
8.Delete from specified position
9.Exit
---------------------------------
Enter your choice:6

The deleted element is :10


MENU:
1.Create
2.Display
3.Insert at the beginning
4.Insert at the end
5.Insert at specified positio
6.Delete from beginning
7.Delete from the end
8.Delete from specified position
9.Exit
---------------------------------
Enter your choice:9

ii)Circular linked list


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

typedef struct Node

{
int info;
struct Node *next;
}node;

node *front=NULL,*rear=NULL,*temp;

void create();
void del();
void display();

int main()
{
int chc;
do
{
printf("\nMenu\n\t 1 to create the element : ");
printf("\n\t 2 to delete the element : ");
printf("\n\t 3 to display the queue : ");
printf("\n\t 4 to exit from main : ");
printf("\nEnter your choice : ");
scanf("%d",&chc);
switch(chc)
{
case 1:
create();
break;
case 2:
del();
break;
case 3:
display();
break;
case 4:
return 1;
default:

38
printf("\nInvalid choice :");
}
}while(1);

return 0;
}

void create()
{
node *newnode;
newnode=(node*)malloc(sizeof(node));
printf("\nEnter the node value : ");
scanf("%d",&newnode->info);
newnode->next=NULL;
if(rear==NULL)
front=rear=newnode;
else
{
rear->next=newnode;
rear=newnode;
}
rear->next=front;
}

void del()
{
temp=front;
if(front==NULL)
printf("\nUnderflow :");
else
{
if(front==rear)
{
printf("\n%d",front->info);
front=rear=NULL;
}
else
{
printf("\n%d",front->info);
front=front->next;

39
rear->next=front;
}

temp->next=NULL;
free(temp);
}
}

void display()
{
temp=front;
if(front==NULL)
printf("\nEmpty");
else
{
printf("\n");
for(;temp!=rear;temp=temp->next)
printf("\n%d address=%u next=%u\t",temp->info,temp,temp->next);
printf("\n%d address=%u next=%u\t",temp->info,temp,temp->next);
}
}

Output:-
Menu
1 to create the element:
2 to delete the element :
3 to display the queue :
4 to exit from main :
Enter your choice : 1

Enter the node value : 10

Menu
1 to create the element :
2 to delete the element :
3 to display the queue :
4 to exit from main :
Enter your choice : 1

Enter the node value : 20


40
Menu
1 to create the element :
2 to delete the element :
3 to display the queue :
4 to exit from main :
Enter your choice : 3
10
20
Menu
1 to create the element :
2 to delete the element :
3 to display the queue :
4 to exit from main :
Enter your choice : 2

10
Menu
1 to create the element :
2 to delete the element :
3 to display the queue :
4 to exit from main :
Enter your choice : 4
Exit

iii)Doubly Linked list:

#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *prev;
struct node *next;
int data;
};
struct node *head;
void insertion_beginning();
void insertion_last();
void insertion_specified();
41
void deletion_beginning();
void deletion_last();
void deletion_specified();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\nMain Menu");
printf("\nChoose one option from the following list ...\n");
printf("\n=======================\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random
location\n4.Delete from Beginning\n 5.Delete from last\n6.Delete the node after the
given data\n7.Search\n8.Show\n9.Exit\n");
printf("\nEnter your choice:");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
insertion_beginning();
break;
case 2:
insertion_last();
break;
case 3:
insertion_specified();
break;
case 4:
deletion_beginning();
break;
case 5:
deletion_last();
break;
case 6:
deletion_specified();
break;
case 7:
search();

42
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void insertion_beginning()
{
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter Item value");
scanf("%d",&item);

if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;

43
}
printf("\nNode inserted\n");
}

}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}

}
printf("\nnode inserted\n");
}

44
void insertion_specified()
{
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
temp=head;
printf("Enter the location");
scanf("%d",&loc);
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
}
}
void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}

45
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("\nnode deleted\n");
}

}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nnode deleted\n");
}

46
}
void deletion_specified()
{
struct node *ptr, *temp;
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf("\nnode deleted\n");
}
}
void display()
{
struct node *ptr;
printf("\n printing values...\n");
ptr = head;
while(ptr != NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
void search()
{

47
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("\nitem found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("\nItem not found\n");
}
}

Output:-
Main Menu

Choose one option from the following list ...

48
=========================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
9.Exit

Enter your choice:1

Enter Item value20

Node inserted

Main Menu

Choose one option from the following list ...

========================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice:2

Enter value40

node inserted

49
Main Menu

Choose one option from the following list .


======================..
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice:3


Enter the location2

There are less than 2 elements

Main Menu

Choose one option from the following list ...

==================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice:7

Enter item which you want to search?


40

50
item found at location 2
Main Menu

Choose one option from the following list ...

===============================

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice:9

Exit

8. Write C programs to implement the following data structures


using Lists i) Stack ii) Queue.
i) Stack
#include <stdio.h>
#include <stdlib.h>

struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;

int topelement();
void push(int data);
void pop();
void empty();
void display();
51
void destroy();
void stack_count();
void create();

int count = 0;

void main()
{
int no, ch, e;

printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");

create();

while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);

switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack");
else

52
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}

/* Create empty stack */


void create()
{
top = NULL;
}

/* Count stack elements */


void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}

/* Push data into stack */


void push(int data)

53
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}

/* Display stack elements */


void display()
{
top1 = top;

if (top1 == NULL)
{
printf("Stack is empty");
return;
}

while (top1 != NULL)


{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}

/* Pop Operation on stack */


void pop()
{
top1 = top;

54
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}

/* Return top element */


int topelement()
{
return(top->info);
}

/* Check if stack is empty or not */


void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}

/* Destroy entire stack */


void destroy()
{
top1 = top;

while (top1 != NULL)


{
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}

55
free(top1);
top = NULL;

printf("\n All stack elements destroyed");


count = 0;
}

Output:-
1 - Push
2 - Pop
3 - Top
4 - Empty
5 - Exit
6 - Dipslay
7 - Stack Count
8 - Destroy stack
Enter choice : 1
Enter data : 56

Enter choice : 1
Enter data : 80

Enter choice : 2

Popped value : 80
Enter choice : 3

Top element : 56
Enter choice : 1
Enter data : 78

Enter choice : 1
Enter data : 90

Enter choice : 6
90 78 56
Enter choice : 7

No. of elements in stack : 3


Enter choice : 8
56
All stack elements destroyed
Enter choice : 4

Stack is empty
Enter choice : 5

ii) Queue
#include <stdio.h>
#include <stdlib.h>

struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;

int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();

int count = 0;

void main()
{
int no, ch, e;

printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");

57
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}

58
/* Create an empty queue */
void create()
{
front = rear = NULL;
}

/* Returns queue size */


void queuesize()
{
printf("\n Queue size : %d", count);
}

/* Enqueing the queue */


void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;

rear = temp;
}
count++;
}

/* Displaying the queue elements */


void display()
{
front1 = front;

59
if ((front1 == NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}

/* Dequeing the queue */


void deq()
{
front1 = front;

if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;

60
}

/* Returns the front element of queue */


int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}

/* Display if queue is empty or not */


void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}

Output:-
1 - Enque
2 - Deque
3 - Front element
4 - Empty
5 - Exit
6 - Display
7 - Queue size
Enter choice : 1
Enter data : 14

Enter choice : 1
Enter data : 85

Enter choice : 1
Enter data : 38

Enter choice : 3
Front element : 14
Enter choice : 6
61
14 85 38
Enter choice : 7

Queue size : 3
Enter choice : 2

Dequed value : 14
Enter choice : 6
85 38
Enter choice : 7

Queue size : 2
Enter choice : 4
Queue not empty
Enter choice : 5

9. Write C programs to implement the following search


algorithms:
i) Linear Search ii) Binary Search

i)Linear Search
#include<stdio.h>
void main()
{
int a[20],i,x,n;
printf("Enter number of elements:");
scanf("%d",&n);

printf("Enter the numbers:");


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

printf("Enter element to search:");


scanf("%d",&x);

for(i=0;i<n;++i)
if(a[i]==x)
break;

if(i<n)
62
printf("Element found at index %d",i);
else
printf("Element not found");

return 0;
}
Output:-
Enter the number of elements:10
Enter the numbers:1
2
3
4
5
6
7
8
9
10
Enter element to search:7
Element found at index 6

ii) Binary Search


#include <stdio.h>
void main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elements:");
scanf("%d",&n);
printf("Enter the numbers:", n);
for(i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to find");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low+high)/2;
while (low <= high)
{
if(array[mid] < key)
low = mid + 1;
63
else if (array[mid] == key)

{
printf("%d found at location %d", key, mid+1);
break;
}
else
high = mid - 1;
mid = (low + high)/2;
}
if(low > high)
printf("Not found! %d isn't present in the list", key);
return 0;
}

Output;-
Enter number of elements:5
Enter the numbers:20
10
30
40
50
Enter value to find30
30 found at location 3

10. Write C programs to implement the following sorting


algorithm
i) Bubble Sort ii) Insertion Sort iii) Selection Sort.

i) Bubble Sort
#include<stdio.h>
void main()
{
int array[100], n, i, j, swap;
printf("Enter number of elements:");
scanf("%d", &n);
printf("Enter %d Numbers:", n);
for(i = 0; i < n; i++)
scanf("%d", &array[i]);
for(i = 0 ; i < n - 1; i++)
64
{
for(j = 0 ; j < n-i-1; j++)
{
if(array[j] > array[j+1])
{
swap=array[j];
array[j]=array[j+1];
array[j+1]=swap;
}
}
}
printf("Sorted Array:");
for(i = 0; i < n; i++)
printf("%d", array[i]);
return 0;
}
Output:-
Enter number of elements:4
Enter 4 Numbers:
88 83 60 50
Sorted Array:
50
60
83
88

ii) Insertion Sort

#include <stdio.h>
void main()
{
int arr[50], num, i, j, pos, temp;
printf("Enter the number of elements in the array: ");
scanf("%d", &num);
printf("\nEnter the numbers: ");
for(i = 0; i < num; i++)
{
scanf("%d", &arr[i]);
}
for(i = 0; i < num; i++)
65
{
temp = arr[i];
j = i;
while(j > 0 && temp < arr[j-1])
{
arr[j] = arr[j-1];
j = j-1;
}
arr[j] = temp;
}
printf("\nThe array sorted in ascending order is as follows.\n");
for(i = 0; i < num; i++)
{
printf("%d ", arr[i]);
}
}

Output:-
Enter the number of elements in the array: 5
Enter the numbers: 80
50
100
60
70

The array sorted in ascending order is as follows.


50 60 70 80 100

11. Write C programs to implement the following sorting


algorithms i) Quick Sort

Quick Sort
#include<stdio.h>
void quickSort(int [10],int,int);
int main()
{
int list[20],size,i;
printf("Enter size of the list: ");
scanf("%d",&size);
66
printf("Enter %d integer values: ",size);
for(i = 0; i < size; i++)
scanf("%d",&list[i]);
quickSort(list,0,size-1);
printf("List after sorting is: ");
for(i = 0; i < size; i++)
printf(" %d",list[i]);
}
void quickSortnt list[10],int first,int last)
{
int pivot,i,j,temp;
if(first < last)
{
pivot = first;
i = first;
j = last;
while(i < j)
{
while(list[i] <= list[pivot] && i < last)
i++;
while(list[j] > list[pivot])
j--;
if(i <j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[pivot];
list[pivot] = list[j];
list[j] = temp;
quickSort(list,first,j-1);
quickSort(list,j+1,last);
}
}

Output:-
Enter size of the list: 10

67
Enter 10 integer values: 7

10

List after sorting is: 0 1 2 3 5 7 7 8 9 10

12. Write a C program to implement binary tree using arrays and to


perform binary tree traversals i) inorder ii) postorder iii) preorder.
#include <stdio.h>

#include <stdlib.h>

struct btnode

int value;

struct btnode *l;

struct btnode *r;

68
*root = NULL, *temp = NULL, *t2, *t1;

void delete1();

void insert();

void delete();

void inorder(struct btnode *t);

void create();

void search(struct btnode *t);

void preorder(struct btnode *t);

void postorder(struct btnode *t);

void search1(struct btnode *t,int data);

int smallest(struct btnode *t);

int largest(struct btnode *t);

int flag = 1;

void main()

int ch;

printf("\nOPERATIONS ---");

printf("\n1 - Insert an element into tree\n");


69
printf("2 - Delete an element from the tree\n");

printf("3 - Inorder Traversal\n");

printf("4 - Preorder Traversal\n");

printf("5 - Postorder Traversal\n");

printf("6 - Exit\n");

while(1)

printf("\nEnter your choice : ");

scanf("%d", &ch);

switch (ch)

case 1:

insert();

break;

case 2:

delete();

break;

case 3:

inorder(root);

break;

case 4:

preorder(root);
70
break;

case 5:

postorder(root);

break;

case 6:

exit(0);

default :

printf("Wrong choice, Please enter correct choice ");

break;

/* To insert a node in the tree */

void insert()

create();

if (root == NULL)

root = temp;

else

search(root);

}
71
/* To create a node */

void create()

int data;

printf("Enter data of node to be inserted : ");

scanf("%d", &data);

temp = (struct btnode *)malloc(1*sizeof(struct btnode));

temp->value = data;

temp->l = temp->r = NULL;

/* Function to search the appropriate position to insert the new node */

void search(struct btnode *t)

if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node
value insert at right */

search(t->r);

else if ((temp->value > t->value) && (t->r == NULL))

t->r = temp;

else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root
node value insert at left */
72
search(t->l);

else if ((temp->value < t->value) && (t->l == NULL))

t->l = temp;

/* recursive function to perform inorder traversal of tree */

void inorder(struct btnode *t)

if (root == NULL)

printf("No elements in a tree to display");

return;

if (t->l != NULL)

inorder(t->l);

printf("%d -> ", t->value);

if (t->r != NULL)

inorder(t->r);

/* To check for the deleted node */

void delete()
73
{

int data;

if (root == NULL)

printf("No elements in a tree to delete");

return;

printf("Enter the data to be deleted : ");

scanf("%d", &data);

t1 = root;

t2 = root;

search1(root, data);

/* To find the preorder traversal */

void preorder(struct btnode *t)

if (root == NULL)

printf("No elements in a tree to display");

return;
74
}

printf("%d -> ", t->value);

if (t->l != NULL)

preorder(t->l);

if (t->r != NULL)

preorder(t->r);

/* To find the postorder traversal */

void postorder(struct btnode *t)

if (root == NULL)

printf("No elements in a tree to display ");

return;

if (t->l != NULL)

postorder(t->l);

if (t->r != NULL)

postorder(t->r);

printf("%d -> ", t->value);

}
75
/* Search for the appropriate position to insert the new node */

void search1(struct btnode *t, int data)

if ((data>t->value))

t1 = t;

search1(t->r, data);

else if ((data < t->value))

t1 = t;

search1(t->l, data);

else if ((data==t->value))

delete1(t);

/* To delete a node */

void delete1(struct btnode *t)


76
{

int k;

/* To delete leaf node */

if ((t->l == NULL) && (t->r == NULL))

if (t1->l == t)

t1->l = NULL;

else

t1->r = NULL;

t = NULL;

free(t);

return;

/* To delete node having one left hand child */

else if ((t->r == NULL))

{
77
if (t1 == t)

root = t->l;

t1 = root;

else if (t1->l == t)

t1->l = t->l;

else

t1->r = t->l;

t = NULL;

free(t);

return;

/* To delete node having right hand child */

else if (t->l == NULL)

{
78
if (t1 == t)

root = t->r;

t1 = root;

else if (t1->r == t)

t1->r = t->r;

else

t1->l = t->r;

t == NULL;

free(t);

return;

/* To delete node having two child */

else if ((t->l != NULL) && (t->r != NULL))

t2 = root;

if (t->r != NULL)

k = smallest(t->r);

flag = 1;
79
}

else

k =largest(t->l);

flag = 2;

search1(root, k);

t->value = k;

/* To find the smallest element in the right sub tree */

int smallest(struct btnode *t)

t2 = t;

if (t->l != NULL)

t2 = t;

return(smallest(t->l));

else
80
return (t->value);

/* To find the largest element in the left sub tree */

int largest(struct btnode *t)

if (t->r != NULL)

t2 = t;

return(largest(t->r));

else

return(t->value);

Output:-
OPERATIONS ---

1 - Insert an element into tree

2 - Delete an element from the tree

3 - Inorder Traversal

4 - Preorder Traversal

5 - Postorder Traversal

6 - Exit
81
Enter your choice : 1

Enter data of node to be inserted : 40

Enter your choice : 1

Enter data of node to be inserted : 20

Enter your choice : 1

Enter data of node to be inserted : 10

Enter your choice : 1

Enter data of node to be inserted : 30

Enter your choice : 1

Enter data of node to be inserted : 60

Enter your choice : 1

Enter data of node to be inserted : 80

Enter your choice : 1

Enter data of node to be inserted : 90

Enter your choice : 3

10 -> 20 -> 30 -> 40 -> 60 -> 80 -> 90 ->

Enter your choice : 6

Exit

OPERATIONS ---

1 - Insert an element into tree


82
2 - Delete an element from the tree

3 - Inorder Traversal

4 - Preorder Traversal

5 - Postorder Traversal

6 - Exit

Enter your choice : 1

Enter data of node to be inserted : 40

Enter your choice : 1

Enter data of node to be inserted : 20

Enter your choice : 1

Enter data of node to be inserted : 10

Enter your choice : 1

Enter data of node to be inserted : 30

Enter your choice : 1

Enter data of node to be inserted : 60

Enter your choice : 1

Enter data of node to be inserted : 80

Enter your choice : 1

Enter data of node to be inserted : 90

Enter your choice : 4

40 -> 20 -> 10 -> 30 -> 60 -> 80 -> 90 ->


83
Enter your choice : 6

Exit

OPERATIONS ---

1 - Insert an element into tree

2 - Delete an element from the tree

3 - Inorder Traversal

4 - Preorder Traversal

5 - Postorder Traversal

6 - Exit

Enter your choice : 1

Enter data of node to be inserted : 40

Enter your choice : 1

Enter data of node to be inserted : 20

Enter your choice : 1

Enter data of node to be inserted : 10

Enter your choice : 1

Enter data of node to be inserted : 30

Enter your choice : 1

Enter data of node to be inserted : 60

Enter your choice : 1

Enter data of node to be inserted : 80


84
Enter your choice : 1

Enter data of node to be inserted : 90

Enter your choice : 5

10 -> 30 -> 20 -> 90 -> 80 -> 60 -> 40 ->

Enter your choice : 6

Exit

13. Write a C program to perform the following operations using


linked lists:

i) Insert an element into a binary search tree.

ii) Delete an element from a binary search tree.

iii) Search for a key element in a binary search tree

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

struct node
{
int key;
struct node *left, *right;
};

// Create a node
struct node *newNode(int item) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
85
// Inorder Traversal
void inorder(struct node *root) {
if (root != NULL) {
// Traverse left
inorder(root->left);

// Traverse root
printf("%d -> ", root->key);

// Traverse right
inorder(root->right);
}
}

// Insert a node
struct node *insert(struct node *node, int key)
{
// Return a new node if the tree is empty
if (node == NULL) return newNode(key);

// Traverse to the right place and insert the node


if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);

return node;
}

// Find the inorder successor


struct node *minValueNode(struct node *node)
{
struct node *current = node;

// Find the leftmost leaf


while (current && current->left != NULL)
current = current->left;

return current;

86
}

// Deleting a node
struct node *deleteNode(struct node *root, int key)
{
// Return if the tree is empty
if (root == NULL) return root;

// Find the node to be deleted


if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);

else
{
// If the node is with only one child or no child
if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}

// If the node has two children


struct node *temp = minValueNode(root->right);

// Place the inorder successor in position of the node to be deleted


root->key = temp->key;

// Delete the inorder successor


root->right = deleteNode(root->right, temp->key);
}
return root;

87
}

// Driver code
int main()
{
struct node *root = NULL;
root = insert(root, 8);
root = insert(root, 3);
root = insert(root, 1);
root = insert(root, 6);
root = insert(root, 7);
root = insert(root, 10);
root = insert(root, 14);
root = insert(root, 4);

printf("Inorder traversal: ");


inorder(root);

printf("\nAfter deleting 10\n");


root = deleteNode(root, 10);
printf("Inorder traversal: ");
inorder(root);
}

Output:-
Inorder traversal: 1 -> 3 -> 4 -> 6 -> 7 -> 8 -> 10 -> 14 ->
After deleting 10
Inorder traversal: 1 -> 3 -> 4 -> 6 -> 7 -> 8 -> 14 ->

14. Write C programs for the implementation of bfs and dfs for a
given graph.

Breadth First Search:

#include<stdio.h>
#include<conio.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1;
void bfs(int v) {
for (i=1;i<=n;i++)

88
if(a[v][i] && !visited[i])
q[++r]=i;
if(f<=r) {
visited[q[f]]=1;
bfs(q[f++]);
}
}
void main() {
int v;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for (i=1;i<=n;i++) {
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
bfs(v);
printf("\n The node which are reachable are:\n");
for (i=1;i<=n;i++)
if(visited[i])
printf("%d\t",i); else
printf("\n Bfs is not possible");
getch();
}

Output:-

Enter the number of vertices:4

Enter graph data in matrix form:


1243
4658
6473
7694
89
Enter the starting vertex:2

The node which are reachable are:


1234

Depth First search;-

#include<stdio.h>
int a[20][20],reach[20],n;
void dfs(int v)
{
int i;
reach[v]=1;
for (i=1;i<=n;i++)
if(a[v][i] && !reach[i])
{
printf("\n %d->%d",v,i);
dfs(i);
}
}
void main()
{
int i,j,count=0;
printf("\n Enter number of vertices:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
reach[i]=0;
for (j=1;j<=n;j++)
a[i][j]=0;
}
printf("\n Enter the adjacency matrix:\n");
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
scanf("%d",&a[i][j]);
dfs(1);
printf("\n");
for (i=1;i<=n;i++)
{
90
if(reach[i])
count++;
}
if(count==n)
printf("\n Graph is connected"); else
printf("\n Graph is not connected");
}

Output:-

Enter number of vertices:4

Enter the adjacency matrix:


1243
5468
4873
5689

1->2
2->3
3->4

Graph is connected

15. Write a C program for the implementation of Prim’s algorithm


to obtain the minimum cost spanning tree from a connected
undirected graph.

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

#define infinity 9999


#define MAX 20

int G[MAX][MAX],spanning[MAX][MAX],n;
int prims();

int main()
{
int i,j,total_cost;
91
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
printf("\nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of spanning tree=%d",total_cost);
return 0;
}

int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}
//initialise visited[],distance[] and from[]
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;

92
visited[i]=0;
}
min_cost=0; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];
//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}

Output:-
Enter no. of vertices:6
Enter the adjacency matrix:
031600
305030
150564
605002
036006
93
004260

spanning tree matrix:

031000
300030
100004
000002
030000
004200

Total cost of spanning tree=13

16. Write a C program to implement Dijkstra’s algorithm for the


single source shortest path problem.
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}
void dijkstra(int G[MAX][MAX],int n,int startnode)
{

int cost[MAX][MAX],distance[MAX],pred[MAX];
94
int visited[MAX],count,mindistance,nextnode,i,j;
//pred[] stores the predecessor of each node
//count gives the number of nodes seen so far
//create the cost matrix
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
//initialize pred[],distance[] and visited[]
for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
//check if a better path exists through nextnode
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;

95
}

//print the path and distance of each node


for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}

Output:-

Enter no. of vertices:4


Enter the adjacency matrix:
0424
5 6 8 10
4682
3761

Enter the starting node:4


Distance of node0=4
Path=0<-2<-4
Distance of node1=6
Path=1<-2<-4
Distance of node2=0
Path=2<-4
Distance of node3=1
Path=3<-4

96
97
98
99
100
101
102

You might also like