0% found this document useful (0 votes)
5 views

c Programming and Data Structures Lab Manual (1)

The document is a lab manual for a C programming course at P.S.V College of Engineering and Technology, detailing various experiments and their objectives. It includes algorithms, sample programs, and expected outputs for exercises involving statements, functions, arrays, pointers, structures, and file handling. The manual aims to enhance students' programming skills and understanding of real-time applications in C.

Uploaded by

Divya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

c Programming and Data Structures Lab Manual (1)

The document is a lab manual for a C programming course at P.S.V College of Engineering and Technology, detailing various experiments and their objectives. It includes algorithms, sample programs, and expected outputs for exercises involving statements, functions, arrays, pointers, structures, and file handling. The manual aims to enhance students' programming skills and understanding of real-time applications in C.

Uploaded by

Divya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

P.S.

V COLLEGE OF ENGINEERIN AND TECHNOLOGY


KRISHNAGIRI-635108

DEPARTMENT OF INFORMATION TECHNOLOGY


LAB MANUAL

PROGRAMMING IN C - LABORATORY

SUBJECT CODE : CS3271

YEAR/SEM : I\II

REGULATION : 2021

6
Vision

To facilitate technical education with high quality and ethics for developing

professionals to fit into the competitive atmosphere in the global market.

Mission:

M1: To provide a learning ambience to enhance innovations, problem solving

skills managerial qualities, team-spirit and ethical responsibilities.

M2: To provide exposure to latest tools and technologies in the area of

Information Technology

M3: To support society by participating in and encouraging technology

transfer

M4: To undertake collaborative learning which offers opportunities for

long term interaction with academia and industry

7
INDEX

EX.NO NAME OF THE EXPERIMENT REMARK

1 STATEMENTS EXPRESSIONS DECISION MAKING AND


INTERATIVE STATEMENT
2
C PROGRAMMING USING FUNCTIONS AND ARRAYS
STATEMENTS

3 IMPLEMENT C PROGRAMS USING POINTERS AND


STRUCTURES

4 IMPLEMENT C PROGRAMS USING FILES

5 DEVELOPMENT OF REAL TIME C APPLICATIONS

6 ARRAY IMPLEMENTATION OF LIST ADT

7 ARRAY IMPLEMENTATION OF STACK AND QUEUE ADTS

8 LINKED LIST IMPLEMENTATION OF LIST,STACK AND QUEUE


ADTS

9 APPLICATIONS OF LIST , STACK AND QUEUE ADTS

10 IMPLEMENTATION OF BINARY TREES AND OPERATIONS OF


BINARY TREES
11 IMPLEMENTATION OF BINARY SEARCH TREES

12 IMPLEMENTATION OF SEARCHING TECHNIQUES

13 IMPLEMENTATION OF SORTING ALGORITHMS

14 IMPLEMENTATION OF HASHING–ANY TWO COLLISION


TECHNIQUES

8
EX.NO:1

STATEMENTS, EXPRESSIONS, DECISION MAKING


AND ITERATIVE STATEMENTS

AIM
To write a C program to practice of c programming using statements, expressions,
Decision making and iterative statements

USING STATEMENTS, EXPRESSIONS

ALGORITHM

Step1:Start
Step2:Declarevariablesnum1,num2,num3andsum,average.
Step 3: Read values num1,num2,num3
Step4:Addnum1,num2,num3andassigntheresulttosum.sum←num1+num2+num3
average ← sum/3
Step5:Displaysumandaverage Step
6: Stop

PROGRAM
#include<stdio.h>in
t main( )
{
inta,b,c;
intsum,average;
printf("Enter any three integers:");
scanf("%d%d %d",&a,&b,&c);
sum = a+b+c;
average=sum/3
printf("Sum and average of three integers:%d%d",sum,average);
return 0;
}

9
OUTPUT

Enteranythreeintegers:245

Sumandaverageofthreeintegers:113

DECISIONMAKING

ALGORITHM

1. Start.

2. Readyear.

3. Check whether year is divisible by 4 and 400andnotdivisibleby100.

4. If the condition Is true then printy ear is leapyear.Otherwiseprintyearisnotleapyear.

5. Stop.

PROGRAM
#include<stdio.h>#include<conio.
h>voidmain()
{
inti,year;clrscr();
printf(“EnterthevalueofN:”);
scanf(“%d”,&year);
if(((year%4==0)&&(year%100!=0))||(year
%400==0))printf(“%d is a leap year\n”,year);
else

printf(“%disnotaleapyear\n”,year);
getch();
}

1
0
OUTPUT:

Enter the Value of N: 2000 2000 is a leap year.

EnterthevalueofN:17001700isnotaleapyear.

ITERATIVESTATEMENTS

ALGORITHM
1. Start
2. Readn,assignsum=0
3. fori=1ton
Calculatesum=sum+1/(i*i*i)
4. printsum
5. Stop.

PROGRAM
#include<stdio.h>
void main()
{
intn,i,sum=0;
clrscr();
printf(“\nEntern\t”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i*i*i;
}
printf(“Sum=%d”,sum);
getch();

1
1
OUTPUT

Entern5
Sum=225

RESULT:

Thus above problem was successfully executed.

12
EX.NO :2

C PROGRAMMING USING FUNCTIONS AND ARRAYS STATEMENTS

AIM
To write a C program to practice of c programming using function sandarrays statements.

ARRAYSSTATEMENTS

ALGORITHM

1. Start.

2. Read the elements of matrix A.

3. Read the elements of matrix B.

4. Setaloo pup to the row.

5. Setainnerloo pup to the column.

6. Add the element of A and B in column wise and store the result in sum OF matrix.

7. After execution no two loops ,print the values in sum matrix.

8. Stop.

PROGRAM

#include<stdio.h>
void main()
{
intA[3][3],B[3][3],sum[3][3],i,j;
clrscr();
printf(“Enter the elements of matrix A”);for(i=0;i<3;i++)
{
for(j=0;j<3;j++)

13
{
scanf(“%d”,&A[i][j]);

}
}
printf(“Enter the elements of matrix B”);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&B[i][j]);
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
sum[i][j]=A[i][j]+B[i][j];
}
}
printf(“sum of two matrix\n”);for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%3d”,sum[i][j]); printf(“\
n”);
}

}
OUTPUT

Enter the elements of matrix A


101
111
010
Enter the elements of matrix B
011
100
111
Sum of two matrix
112
211
121
14
FUNCTIONS

ALGORITHM

1. Start

2. Reada,b,c

3. Callmaxfunctionwiththeparametersa,b,c.

4. Printmaximumvalue.

5. Stop.

Maxfunction:

1. Start

2. Ifa>banda>cthenassignmax=9.

3. Otherwiseifb>cthenassignmax=b.Otherwiseassignmax=c.

4. Returnmax.
5. Stop.

PROGRAM

#include<stdio.h>i
nt max(int,int,int);
void main()
{
inta,b,c,d;

clrscr();
printf(“\n Enter three integer values:”);
scanf(“%d %d %d”,&a,&b,&c);
d=max(a,b,c);
printf(“\nMaximumis:%d”,d);
getch();
}
intmax(inta,intb,intc)

15
{
int max; if(a>b&&a>c)max=a;
else if(b>c)max=b;
else max=c;
return(max);
}
OUTPUT
Enter three integer values:

56

28

79

Maximumis:79

RESULT

Thus above Program was Successfully Executed

16
EX .NO:3

IMPLEMENTCPROGRAMSUSINGPOINTERSANDSTRUCTURES

AIM
To writ a C program to implement C programs using Pointers and Structures.

ALGORITHM

1. Start

2. Declare students structure

3. Read student rol number ,student name ,branch ,marks.

4. Print student roll number, student name, branch ,marks.

5. Stop.

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

struct

{
introllno;

charname[30];
charbranch[4];
int marks;

*stud;

18
printf(“\nEnterRollno:”);

scanf(“%d”, &stud->rollno);
printf(“\n Enter Name :”);
scanf(“%s”,stud->name);
printf(“\n Enter Branch:”);
scanf(“%s”,stud->branch);
printf(“\n Enter Marks:”);
scanf(“%d”,&stud->marks);

printf(“\n Roll Number:%d”,stud->rollno);


printf(“\nName:%s”,stud->name);
printf(“\n Branch:%s”,stud->branch);
printf(“\nMarks:%d”,stud->marks);
getch();
}
OUTPUT

Enter Rollno :1000


EnterName:vinoth
Enter Branch:CSE
Enter Marks:90
Roll Number:1000
Name:vinoth
Branch:CSE
Marks:90
RESULT

Thus above Program was Successfully Executed.

19
EX .NO:4

IMPLEMENTCPROGRAMSUSINGFILES
AIM
To write a C program to implement C programs using files.

ALGORITHM

1. Start
2. Create file pointers

3. Enter the file name

4. Open the file with read mode

5. Till the end offiler each edread one charactistics a time

(a) If it is new line character‘\n’,the n in crement no_of_lines count value by one.

(b) If it is a character the n in crement no_of_characters count value by one.

6. Printno_of_line sandno_of_characters values

7. Stop.

PROGRAM

#include
<stdio.h>#include<strin
g.h>Main()
{
FILE*fp;

intch,)no_of_characters=0,no_of_lines=1;

22
charfilename[20];
printf(“\nEnterthefilename:“); fp
= fopen(filename, “r”);

if(fp==NULL)
{

printf(“\nErroropeningtheFile”);

exit (1);
}

ch= fgetc(fp);

while(ch!=EOF)
{

if(ch==’\n’);

no_of_lines++;

no_of_characters++;

ch=fgetc(fp);
}

if(no_of_characters>0)

printf(“\nInthefile%s,thereare%dlinesand%dcharacters”,filename,no_of_lines,
no_of_characters);
else

printf(“\nFile is empty”);

fclose(fp);
}

23
OUTPUT

Enter the filename:Letter.txt

In the file Letter .txt,there is1lineand18characters

RESULT

Thus above Program was Successfully Executed

24
EX.NO:5
DEVELOPMENT OF REAL TIME C APPLICATIONS
AIM
To write a C program to Development of real time C applications.

ALGORITHM

1. Start

2. Definepias3.1415

3. Define circle _area(or)a spi*r*r

4. Read radius

5. Call circle area function radius with to calculate area of a circle.

6. Print area

7. Stop.

PROGRAM

#include
<stdio.h>#definePI3.
1415
#define circle Area(r) (PI*r*r)
int main()
{

floatradius,area;

printf(“Enter the radius:”);


scanf(“%f”, &radius);
area = circle Area(radius);
printf(“Area = %.2f”, area);
return();
}

27
OUTPUT

Entertheradius:6
Area=113.094002

RESULT

Thus above Program was Successfully Executed

PRACTICEEXCERICES

1. Write a C program to generate the scientific calculator.

28
EX.NO:6

ARRAY IMPLEMENTATION OF LIST ADT

AIM
To write a C program to Array implementation of List ADT.

ALGORITHM

1.inserted. Check for the start, middle or end position of insertion. Insert the node
and Change its link accordingly.
2. For deletion get the position in which deletion is to be done. Delete the nodeand Start the
program.
3. Create a node with two fields’ data and link field.
a. Allocate space for the node dynamically.
b. Create link between the created node sand let the last node be with NULL Link
c. Inserttheinputdatainthedatafieldandpress–1tostopthesame.
4.Get the choice of operations either insertion or deletion.
5.Forinsertiongetthepositioninwhichinsertionistobedoneandtheelementtobe then
Link it to the next node. Before deletion check whether there is data in the list to
be deleted.
6. Using display option lists the elements of the list.
7. Stop the program.

30
PROGRAM

#include<stdio.h>#incl
ude<conio.h>
#defineMAX10 void
create(); voidinsert();

voiddeletion();voids
earch();void
display();
inta,b[20],n,p,e,f,i,pos;voidmain()
{
//clrscr();int
ch;charg='y';do
{
printf("\nmainMenu");
printf("\n1.Create\n2.Delete\n3.Search\n4.Insert\n5.Display\n6.Exit
\n");printf("\n Enter your
Choice");scanf("%d", &ch);
switch(ch)
{
case1:
create();break;cas
e
2:deletion();break;
case 3:
search();break;c
ase 4:
insert();break;ca
se 5:
display();brea
k;case6:
exit();

break;default:
printf("\nEnterthecorrectchoice:");
}
printf("\
nDouwanttocontinue:::");scanf("\n%c",
&g);
}
while(g=='y'||
g=='Y');getch();
}
voidcreate()
{
31
printf("\nEnter the number of nodes");

32
scanf("%d",&n);for(i=0;
i<n;i++)
{
printf("\nEnter the
Element:",i+1);scanf("%d", &b[i]);
}
}
voiddeletion()

{
printf("\nEnterthepositionuwanttodelete::");scanf("%d",&pos);if(pos>=n)
{
printf("\nInvalidLocation::");
}
else
{
for(i=pos+1;i<n;i++)
{
b[i-1]=b[i];
}
n--;
}
printf("\nThe Element safte rdeletion");for(i=0;i<n;i++)
{
printf("\t%d",b[i]);
}
}
voidsearch()
{
printf("\nEnter the Element to be
searched:");scanf("%d",&e);for(i=0;i<n;i++)
{
if(b[i]==e)
{
printf("Valueisinthe%dPosition",i);
}
else
{
printf("Value%disnotinthelist::",e);continue;
}
}
}
voidinsert()
{
printf("\nEnterthepositionuneedtoinsert::");scanf("%d",&pos);if(pos>=n)

33
{
printf("\ninvalidLocation::");
}
else
{
for(i=MAX-1;i>=pos-1;i--)
{
b[i+1]=b[i];
}
printf("\nEntertheelementtoinsert::\n");
scanf("%d",&p);
b[pos]=p;
n++;}

printf("\nThelistafterinsertion::\
n");display();
}
voiddisplay()
{
printf("\
nTheElementsofThelistADTare:");for(i=0;i<n;i++)
{
printf("\n\n%d",b[i]);
}
}

OUTPUT:

MainMenu
1. Create
2. Delete
3. Search
4. insert
5. Display
6. Exit
EnterYourChoice:1
EntertheNumberofNodes:3 Enter
the Element : 1
EntertheElement:12
EntertheElement:23
Doyouwanttocontinue:Y Main
Menu
1. Create
2. Delete
3. Search
4. insert
5. Display
34
6. Exit
EnterYourChoice:2
Enterthepositionyouwanttodelete:2
The Element after deletion : 1 12
Doyouwanttocontinue:Y Main
Menu
1. Create
2. Delete
3. Search
4. insert
5. Display
6. Exit
EnterYourChoice:3
EntertheElementtobeSearched:12
Value is in the Position : 1
Doyouwanttocontinue:Y Main
Menu
1. Create
2. Delete

4. insert
5. Display
6. Exit
EnterYourChoice:4
Enterthepositionyouneedtoinsert:1
Enter the element to Insert : 89
Thelistafterinsertion:1 89 12

RESULT

Thus above Program was Successfully Executed

35
EX.NO:7

ARRAY IMPLEMENTATION OF STACK AND QUEUE ADTS

AIM
To write a C program to Array implementation of Stack and Queue ADTs.

ALGORITHM

1. Define a array whichs to resstack elements.


2. The operation on the stack are
a. PUSH data into the stack
b. POP data out of stack
3. PUSHDATAINTOSTACK
a. Enter the data to be insert ed into stack.

b. If TOP is NULL the input data is the first node in


stack. The link of the node is NULL .TOP points
to that node.

c. If TOP is NOT NULL the link of TOP points to the


new node. TOP points to that node.
4. POPDATAFROMSTACK
a. If TOP is NULL the stack is empty

b. If TOP is NOT NULL the link of TOP is the


current TOP. The pervious TOP is popped
from stack.
5. The stack represent ed by array is travers ed to display its content.

38
PROGRAM:
#include
<stdio.h>#include
<stdlib.h>int
stack[6],rev[6];
inttop=-1,k=0;
int size; void
push();void
pop();
void display();int
pali();
voidmain()
{
intchoice,f;
printf("Enter the size for stack\n");
scanf("%d",&size); printf("1.Push\n2.Pop\
n3.Display\n4.Check for Palindrome\n5.Exit\
n");while(1)
{
printf("Enter the choice\n");
scanf("%d",&choice);
switch(choice)
{
case1:push();
break;
case2:pop();
break;
case3:display();
break;
case 4:f=pali();
if(f==1)
printf("It's Palindrome\n");
else
printf("It'snotaPalindrome\n");
break;
case 5:exit(0); default:printf("Wrong
choice...\n");
}}}
void push() {int
num;
if(top==(size-1))
{
printf("StackOverflow\n");
}
else{
printf("Enterthenumbertobepushed\n");

39
scanf("%d",&num); top+
+; stack[top]=num;
}}voidpop()
{ int num;
if(top==-1)
{
printf("StackUnderflow\n");
}
else {
num=stack[top];
printf("Popped element is %d\n",num);
top--
;
}}
voiddisplay(){inti;
if(top==-1)
{
printf("StackUnderflow\n");
}
else
{
printf("StackContents.\n");
for(i=top;i>=0;i--)
{
printf("%d\n",stack[i]); rev[k+
+]=stack[i];
}
}
}
intpali()
{
int i,flag=1;
for(i=top;i>=0;i--)
{
if(stack[i]!=rev[--k])
{
flag=0;
}
}
returnflag;
}

OUTPUT:

--------STACKOPERATIONS-----------
1. Push2.Pop
3. Display
4. CheckforPalindrome

40
5. Exit
-Enter
your choice: 1
Entertheelementtobeinserted:1
Enter your choice: 1
Entertheelementtobeinserted:2
Enter your choice: 1
Entertheelementtobeinserted:1
Enter your choice: 1
Entertheelementtobeinserted:5
Enter your choice: 2
Thepopedelement:5Enter
your choice: 3 The stack
elements are:
1
2
1
Enteryourchoice:4It’sa
Palindrome Enter your
choice:5

ALGORITHM
1. Define a array which to resqueue elements
2. The operations on the queue area)INSERT data into the queue
b)DELETE data out of queue.
3. INSERT DATA INTO queue
a. Enter the data to be insert ed into queue.
b. If TOP is NULL the input data in the first no de in the queue &the link of
the node is NULL.
c. If the TOP is not NULL the link of oppoints to the new node. TOP points to
the node
1. Delete data from queue.
a. If TOP is NULL the queue is empty
b. If TOP is NOT NULL the link of TOP is the current
TOP ,the pervious TOP is popped from queue.
2. The queue represent ed by link ed list is travers ed to display its content.

41
PROGRAM
#include <stdio.h>
#include<conio.h>
#include<string.h>
#defineSIZE5
charCQ[SIZE];
intfront=-1,rear=-1;intch;
void CQ_Insert();void CQ_Delet();
void CQ_Display();void
main()
{
printf("1.Insert\n2.Delete\n3.Display\n4.Exit\
n");while(1)
{
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case1:CQ_Insert();
break;
case2:CQ_Delet();
break;
case 3:CQ_Display();
break;
case4:exit(0);
}
}}
void CQ_Insert() {char
ele;
if(front==(rear+1)%SIZE) {
printf("Circular Queue Full\n");
return; }
if(front==-1)front++;
printf("Enter the element to be inserted\n");scanf("\n
%c",&ele);rear = (rear+1)%SIZE;CQ[rear] =ele; }
voidCQ_Delet(){charitem;if(front==-1)
{
printf("Circular Queue Empty\n");
return; }
else if(front == rear) {item=CQ[front];
printf("Deleted element is: %c\n",item);front=
-1;
rear=
-1;

42
}
else{
item=CQ[front];
printf("Deletedelementis:%c\n",item);front=(front+1)%SIZE;}}
void CQ_Display()
{
inti;if(front==-1)

printf("Circular Queue is Empty\n");


else
{
printf("Elementsofthecircularqueueare..\n"); for(i=front;i!
=rear;i=(i+1)%SIZE)
{
printf("%c\t",CQ[i]);
}
printf("%c\n",CQ[i]);
}
}

OUTPUT:

Circular Queue operations

1.insert
2. delete3.display4.exit

Enteryourchoice:1
Enterelementtobeinsert:a

Enteryourchoice:1
Enterelementtobeinsert:b

Enteryourchoice:1
Enterelementtobeinsert:c Enter

your choice:3a b c

Enteryourchoice:2Deletedelementis:a

Enteryourchoice:3bc
Enter your choice:4

43
RESULT

Thus above Program was Successfully Executed

PRACTICEEXCERICES

1. Write a C Program to reverse the string using stack.

44
EX.NO:8

LINKED LIST IMPLEMENTATION OF LIST,STACK AND QUEUE ADTS

AIM
To write a C program Link ed list implementation of List, Stack and Queue ADTs.

ALGORITHM

1. Initialize and declare variables.

2. Enter the choice.

3. If choice is INSERT then

a. Enter the element to be inserted.


b. Get a new node and set DATA[NEWNODE]=ITEM.

c. Find the node after which the new node is to be inserted.

d. Adjust the link fields.

e. Print the link ed list after insertion.

4. If choice is DELETE then

a. Enter the element to be deleted.

b. Find the node containing the element(LOC)and its


preceding node (PAR).

c. Set ITEM=DATA[LOC]and element the node LOC.

d. Adjust the link fields the PAR points to the next


element. ie LINK[PAR] = LINK [ LOC].
5.Print the link ed list after deletion.

48
PROGRAM:

#include<stdio.h>
#include <malloc.h>#include
<stdlib.h>struct node {
intvalue;
structnode*next;
};

void insert();
voiddisplay()
;voiddelete();
int count();
typedefstructnodeDATA_NODE;

DATA_NODE*head_node,*first_node,*temp_node=0,*prev_node,next_node;int
data;
intmain() {
intoption=0;
printf("SinglyLinkedListExample-AllOperations\n");while(option<5){ printf("\
nOptions\n");
printf("1:InsertintoLinkedList \n");printf("2:DeletefromLinkedList\n");printf("3:
Display Linked List\n"); printf("4 : Count Linked List\n"); printf("Others :Exit()\n");
printf("Enter your option:"); scanf("%d", &option);
switch(option){
case1: insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
count();
break;
default:
break;
}
}
return0;
}
voidinsert(){
printf("\nEnterElementforInsertLinkedList:\n"); scanf("%d",
&data);
temp_node=(DATA_NODE*)malloc(sizeof(DATA_NODE));
49
temp_node->value=data;
if(first_node==0){first_node=temp_node;
}else{
head_node->next=temp_node;
}
temp_node->next=0;head_node=temp_node;fflush(stdin);
}
voiddelete(){
intcountvalue,pos,i=0;countvalue=count();temp_node=first_node;
printf("\nDisplay Linked List : \n"); printf("\nEnter
PositionforDeleteElement:\n");scanf("%d",&pos); if
(pos > 0 && pos <= countvalue) {if (pos == 1) {
temp_node=temp_node->next;first_node=temp_node;printf("\nDeleted Successfully \
n\n");
}else{
while(temp_node!=0){if(i==(pos-1)){
prev_node->next=temp_node->next;if(i==(countvalue-1))
{
head_node=prev_node;
}
printf("\nDeletedSuccessfully\n\n");break;
}else{i++;
prev_node=temp_node;temp_node=
temp_node -> next;
}
}
}
} else
printf("\nInvalidPosition\n\n");
}
void display() {int count = 0;
temp_node = first_node; printf("\
nDisplayLinkedList:\n"); while
(temp_node != 0) {
printf("#%d#",temp_node->value);
count++;
temp_node=temp_node->next;
}
printf("\nNoOfItemsInLinkedList:%d\n",count);
}
intcount(){intcount=0;
temp_node=first_node;while(temp_node!=0){count++;
temp_node = temp_node -> next;
}
printf("\nNoOfItemsInLinkedList:%d\n",count); return
count;
}
50
OUTPUT

Options
1: Insert into Linked List2:DeletefromLinkedList3:DisplayLinked List
4:CountLinkedListOthers:Exit()
Enter your option:1
EnterElementforInsertLinkedList:100

Options
1: Insert into Linked List2:DeletefromLinkedList3:DisplayLinked List
4:CountLinkedListOthers:Exit()
Enter your option:1
EnterElementforInsertLinkedList:200

Options
1: Insert into Linked List2:DeletefromLinkedList3:DisplayLinked List
4:CountLinkedListOthers:Exit()
Enter your option:1
EnterElementforInsertLinkedList:300
Options
1: Insert into Linked List2:DeletefromLinkedList3:DisplayLinked List
4:CountLinkedListOthers:Exit()
Enter your option:1

EnterElementforInsertLinkedList:400

Options
1: Insert into Linked List2:DeletefromLinkedList3:DisplayLinked List
4:CountLinkedListOthers:Exit()
Enter your option:1
EnterElementforInsertLinkedList:500

Options
1: Insert into Linked List2:DeletefromLinkedList3:DisplayLinked List
4:CountLinkedListOthers:Exit()
Enter your option:3
DisplayLinkedList:

51
#100##200##300##400##500#
NoOfItemsInLinkedList:5

Options
1: Insert into Linked List2:DeletefromLinkedList3:DisplayLinked List
4:CountLinkedListOthers:Exit()
Enter your option:4
NoOfItemsInLinkedList:5

Options
1: Insert into Linked List2:DeletefromLinkedList3:DisplayLinked List
4 : Count Linked ListOthers : Exit()
EnterPositionforDeleteElement:3

Deleted Successfully

Options
1: Insert into Linked List2:DeletefromLinkedList3:DisplayLinked List
4:CountLinkedListOthers:Exit()

Enteryouroption:3
DisplayLinkedList:
#100##200##400##500#
NoOfItemsInLinkedList:4

Options
1:Insertinto
Linked List2:DeletefromLinkedList3:DisplayLinkedList 4 :
Count Linked ListOthers : Exit()
Enteryouroption:2
NoOfItemsInLinkedList:4

DisplayLinkedList:
EnterPositionforDeleteElement:6

Invalid PositionOptions
1:InsertintoLinkedList
2:DeletefromLinkedList3:DisplayLinkedList 4 :
Count Linked ListOthers : Exit()
Enteryouroption:5

(programexitedwithcode:0)Pressanykeytocontinue...

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

structnode
{
intinfo;
structnode*ptr;
}*top,*top1,*temp;

inttopelement();voidpush(intdata);voidpop();
void empty(); void display();

voiddestroy();voidstack_count();voidcreate();
int count = 0;void main()
{
intno,ch,e;printf("\n1-Push");
printf("\n 2 - Pop");
printf("\n 3- Top"); printf("\n4-Empty");printf("\n 5 - Exit");printf("\n6-
Dipslay"); printf("\n7- StackCount");printf("\n8- Destroystack");create();
while (1)
{
printf("\nEnterchoice:");scanf("%d",&ch); switch
(ch)
{
case1:
printf("Enterdata:");scanf("%d",&no);push(no);
break;case 2:
pop();break;
case 3:
if(top== NULL)
printf("Noelementsinstack");else
{
e=topelement();
printf("\nTopelement:%d",e);
}
break;case 4:
empty();break;
case5:
exit(0);case 6:
display();break;

53
case7:
stack_count();

break;

54
case8:
destroy();break;
default :
printf("Wrongchoice,Pleaseentercorrectchoice");break;
}
}
}
/*Createemptystack*/voidcreate()
{
top=NULL;
}
/*Countstackelements*/voidstack_count()
{
printf("\nNo.ofelementsinstack:%d",count);
}
/*Pushdataintostack*/voidpush(intdata)
{
if(top==NULL)
{
top=(structnode*)malloc(1*sizeof(structnode));top-
>ptr = NULL;
top->info=data;
}
else
{
temp=(structnode*)malloc(1*sizeof(structnode));temp->ptr=top;
temp->info = data;top = temp;
}
count++;
}
/*Displaystackelements*/voiddisplay()
{
top1=top;

if(top1==NULL)
{
printf("Stackisempty");return;
}

while(top1!=NULL)
{
printf("%d",top1->info);top1=top1->ptr;
}
}
/*PopOperationonstack*/voidpop()
{
top1=top;
55
if(top1==NULL)
{
printf("\nError:Tryingtopopfromemptystack");return;
}
else
top1=top1->ptr;
printf("\nPoppedvalue:%d",top->info);free(top);
top = top1;count--;
}
/*Returntopelement*/inttopelement()
{
return(top->info);
}

/*Checkifstackisemptyornot*/voidempty()
{
if(top==NULL)
printf("\nStackisempty");else
printf("\nStackisnotemptywith%delements",count);
}
/*Destroyentirestack*/voiddestroy()
{
top1=top;

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

printf("\nAllstackelementsdestroyed");count=0;
}

OUTPUT

EnterYourChoice:
1 -Push
2 - Pop
3 - Top
4 -Empty
5 -Exit
6 -Dipslay
7 -StackCount8-Destroy stack

56
Enterchoice:1Enterdata:56

Enterchoice:1Enterdata:80

Enter choice : 2

Poppedvalue:80Enterchoice: 3

Topelement:56Enterchoice:1Enterdata:78 Enter

choice : 1Enter data : 90

Enterchoice:6907856 Enter
choice : 7

No.ofelementsinstack:3
Enter choice : 8

Allstackelementsdestroyed
Enter choice : 4

StackisemptyEnterchoice:5

PROGRAM

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

structnode
{
intinfo;
structnode*ptr;
}*front,*rear,*temp,*front1;

intfrontelement();
voidenq(intdata);
void deq();
voidempty();voiddisplay();voidcreate();
voidqueuesize();intcount=0;voidmain()
{
intno,ch,e;printf("\n1-Enque");printf("\n2-Deque");
printf("\n3-Frontelement");printf("\n4-Empty");printf("\n5-Exit");
printf("\n 6 - Display"); printf("\n 7 - Queue size");create();
while(1)
{
printf("\nEnterchoice:");scanf("%d",&ch);
57
switch(ch)
{
case1:
printf("Enterdata:");scanf("%d",&no);enq(no);
break;case 2:
deq();break;
case 3:
e = frontelement();if (e != 0)
printf("Frontelement:%d",e);else
printf("\nNofrontelementinQueueasqueueisempty");break; case
4:
empty();break;
case 5:
exit(0);case6:
display();break;
case 7:
queuesize();
break;
default:
printf("Wrongchoice,Pleaseentercorrectchoice"); break;
}
}
}

/*Createanemptyqueue*/void
create()
{
front=rear=NULL;
}

/*Returnsqueuesize*/void
queuesize()
{
printf("\nQueuesize:%d",count);
}

/*Enqueingthequeue*/void
enq(int data)
{
if(rear== NULL)
{
rear=(structnode*)malloc(1*sizeof(structnode));rear->ptr=NULL;
rear->info = data;front = rear;
}
else
{

58
temp=(struct node *)malloc(1*sizeof(struct node));rear->ptr =
temp;temp->info = data;temp->ptr = NULL;

rear=temp;
}
count++;
}

/*Displayingthequeueelements*/voiddisplay()
{
front1=front;

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

/*Dequeingthequeue*/voiddeq()
{ front1 = front;
if(front1==NULL)
{
printf("\nError:Tryingtodisplayelementsfromempty
queue");return;
}
else
if(front1->ptr!=NULL)
{
front1=front1->ptr;
printf("\nDequedvalue:%d",front->info);
free(front);
front=front1;
}
else
{
printf("\nDequedvalue:%d",front->info);free(front);
front = NULL;rear = NULL;
}
count--;
}

/*Returnsthefrontelementofqueue*/intfrontelement()
59
{
if((front!=NULL)&&(rear!=NULL))
return(front->info);
else
return0;
}

/*Displayifqueueisemptyornot*/
voidempty()
{
if((front==NULL)&&(rear==NULL))
printf("\n Queue empty");
else
printf("Queuenotempty");
}

OUTPUT:

EnterYourChoice:
1 -Enque
2 -Deque
3 -Frontelement4-Empty
5 -Exit
6 -Display
7 -Queue size
Enterchoice:1Enterdata:14

Enterchoice:1Enterdata:85

Enterchoice:1Enterdata:38

Enterchoice:3Frontelement:14Enter choice: 6148538 Enter


choice : 7

Queuesize:3Enterchoice:2

Dequedvalue:14Enterchoice:68538
Enter choice : 7

Queuesize:2Enterchoice:4QueuenotemptyEnterchoice:5

RESULT

ThusaboveProgramwasSuccessfullyExecuted.

60
EX.NO:9
APPLICATIONS OF LIST ,STACK AND QUEUE ADTS

AIM
To write a C program for Applications of List, Stack and Queue ADTs.

ALGORITHM

1. Start the program


2. Read the no of vertices.
3. Calculate the in degree, out degree, Total degree of a graph.
4. Find the direct ed graph using dir-graph of function.
5. Find the undirected graph using un dir-graph of function.
6. Read the adjacency values of agraph.
7. Stop the program

PROGRAM:

#include
<stdio.h>#include
<stdlib.h>
#define new_node (structnode*)malloc(sizeof(structnode))structnode
{
intvertex;
structnode*next;
};

voidmain()
{
intoption;
do
{
printf("\nAProgramtorepresentaGraphbyusinganAdjacencyList \n");printf("\n1.Directed Graph
");
printf("\n2.Un-DirectedGraph");printf("\n3.Exit");

61
printf("\n\nSelectaproperoption:");scanf("%d",&option);
switch(option)
{
case1:dir_graph();
break;
case2:undir_graph();
break;
case3:exit(0);
}
}
while(1);
}
intdir_graph()
{
structnode*adj_list[10],*p;
int n;
intin_deg,out_deg,i,j;
printf("\nHowManyVertices?:");scanf("%d",&n); for( i
= 1 ; i <= n ; i++ )adj_list[i] = NULL;
read_graph(adj_list,n);
printf("\nVertex\tIn_Degree\tOut_Degree\tTotal_Degree")
;for(i=1;i<=n;i++)
{
in_deg=out_deg=0;p=adj_list[i];
while( p != NULL )
{
out_deg++;p=p->next;
}
for(j=1;j<=n;j++)
{
p=adj_list[j];while(p!=NULL)
{
if(p->vertex==i)in_deg++; p =
p -> next;
}
}
printf("\n\n%5d\t\t\t%d\t\t%d\t\t%d\n\n",i,in_deg,out_deg,in_deg+out_deg);
}
return;
}
intundir_graph()
{
structnode*adj_list[10],*p;
int deg, i, j, n;
printf("\nHowManyVertices?:"); scanf("%d",
&n);
for(i=1; i<=n;i++) adj_list[i] =
NULL;
62
read_graph(adj_list,n);
printf("\nVertex\tDegree");for(i=1;i<=n;i++)
{
deg=0;
p=adj_list[i];while(p!=NULL)
{
deg++;
p=p->next;
}
printf("\n\n%5d\t\t%d\n\n",i,deg);
}
return;
}
intread_graph(structnode*adj_list[10],intn)
{
inti,j;charreply;
structnode*p,*c;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i ==j)continue;
printf("\nVertices%d&%dareAdjacent?(Y/N):",i,j); scanf("%c",
&reply);
if(reply=='y'||reply=='Y')
{
c=new_node;c->vertex=j; c -
> next = NULL;
if(adj_list[i]==NULL)adj_list[i]=c;
else
{
p= adj_list[i];
while( p->next!=NULL)p=p->next; p ->
next = c;
}
} } }
return;
}

OUTPUT:

AProgramtorepresentaGraphbyusinganAdjacencyMatrixmethod

1. DirectedGraph
2. Un-DirectedGraph
3. Exit

Selectaproperoption:
63
HowManyVertices?:
Vertices1&2areAdjacent?(Y/N):N
Vertices1& 3areAdjacent?(Y/N):Y
Vertices1& 4areAdjacent?(Y/N):Y
Vertices2& 1areAdjacent?(Y/N):Y
Vertices2& 3areAdjacent?(Y/N):Y
Vertices2&4areAdjacent?(Y/N):N
Vertices3&1are Adjacent?(Y/N):Y
Vertices3& 2areAdjacent?(Y/N):Y
Vertices3& 4areAdjacent?(Y/N):Y
Vertices4& 1areAdjacent?(Y/N):Y
Vertices4&2areAdjacent?(Y/N):N
Vertices4&3are Adjacent?(Y/N):Y

VertexIn_Degree

1 2

2 1

3 0

4 1

64
PROGRAM:

#include<stdio.h>
voidtowers(int,char,char,char);int
main()
{
intnum;
printf("Enter the number of disks : ");scanf("%d", &num);
printf("ThesequenceofmovesinvolvedintheTowerofHanoiare
:\n");towers(num,'A','C','B');
return 0;
}
voidtowers(intnum,charfrompeg,chartopeg,charauxpeg)
{
if(num== 1)
{
printf("\nMovedisk1frompeg%ctopeg%c",frompeg,topeg);return;
}
towers(num-1,frompeg,auxpeg,topeg);
printf("\nMovedisk%dfrompeg%ctopeg%c",num,frompeg,
topeg);towers(num - 1, auxpeg, topeg, frompeg);}

OUTPUT:
Enterthenumberofdisks: 3
Thesequenceof movesinvolvedintheTowerofHanoi are:
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C

PROGRAM:
#include<stdio.h>in
t main()
{
intn,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
printf("Enter total number of processes(maximum
20):");scanf("%d",&n);printf("\nEnter Process Burst Time\n");for(i=0;i<n;i+
+)

65
EX.NO:10
IMPLEMENTATION OF BINARY TREES AND OPERATIONS OF BINARY TREES

AIM
To write a C program Implementation of Binary Trees and operations of Binary Trees

ALGORITHM

1. Start the program


2. Create the node using insert()function.
3. Calculate in order ,preorder ,post order of the nodes using in
order(), preorder(), post order() function separately.
4. Print the result.
5. Stop the program.

PROGRAM

#include<stdlib.h>
#include<stdio.h>
struct bin_tree
{
intdata;
structbin_tree*right,*left;
};
typedefstructbin_treenode;

voidinsert(node**tree,intval)
{
node*temp=NULL;if(!(*tree))
{
temp = (node *)malloc(sizeof(node));
temp->left = temp->right = NULL;
temp->data = val;
*tree=temp;return;

insert(&(*tree)->left,val);
}

66
elseif(val>(*tree)->data)
{
insert(&(*tree)->right,val);
}
}
voidprint_preorder(node*tree)
{
if(tree)
{
printf("%d\n",tree->data);
print_preorder(tree->left);
print_preorder(tree->right);
}
}
voidprint_inorder(node*tree)
{
if(tree)
{
print_inorder(tree->left);
printf("%d\n",tree->data);
print_inorder(tree->right);
}
}
voidprint_postorder(node*tree)
{
if(tree)
{
print_postorder(tree->left);
print_postorder(tree->right);
printf("%d\n",tree->data);
}
}
voiddeltree(node*tree)
{
if(tree)
{
deltree(tree->left);deltree(tree-
>right);free(tree);
}
}
node*search(node**tree,intval)
{
if(!(*tree))
{
returnNULL;

search(&((*tree)->left),val);
}
67
elseif(val>(*tree)->data)
{
search(&((*tree)->right),val);
}
elseif(val==(*tree)->data)
{
return*tree;
}
}

voidmain()
{
node*root;node*tmp;
//inti;

root=NULL;
/*Insertingnodesintotree*/
insert(&root, 9);
insert(&root,4);
insert(&root,15);
insert(&root,6);
insert(&root,12);
insert(&root,17);
insert(&root,2);

/*Printingnodesoftree*/printf("PreOrderDisplay\n");
print_preorder(root);
printf("In Order Display\n");
print_inorder(root);
printf("Post Order Display\n");
print_postorder(root);

/*Searchnodeintotree*/tmp
=search(&root,4);
if(tmp)
{
printf("Searchednode=%d\n",tmp->data);
}
else
{
printf("DataNotfoundintree.\n");
}

/*Deletingallnodesoftree*/
deltree(root);
}

68
OUTPUT
PreOrderDisplay9
4
2
6
15
12
17
InOrderDisplay2
4
6
9
12
15
17
PostOrderDisplay2
6
4
12
17
15
9
Searchednode=4

RESULT

ThusaboveProgramwasSuccessfullyExecuted

PRACTICEEXERCISES

1. WriteaCprogramtocreatethebinarysearchtreeanddothedeletionoperationforallconstraintson the
created binary search tree

69
EX.NO:11
IMPLEMENTATION OF BINARY SEARCH TREES

AIM
To write a C program Implementation of Binary Search Trees.

ALGORITHM

1. Declare function create(),search(),delete(),Display().

2. Create a Tree with pointers for left and right sub tree.

3. Insert an element is by checking the to p node and the leaf node and the
operation will be performed.

4. Deleting an element contain searching the tree and deleting the item.
Display the Tree elements
PROGRAM:
#include<stdio.h>#incl
ude<stdlib.h>
typedefstructBST
{
intdata;
structBST*left;structBST*right;
}node;
node*create();
void insert(node *,node *);void preorder(node *);
int main()
{
charch;
node*root=NULL,*temp;

do
{
temp=create();if(root==NULL)

root=temp;else

73
insert(root,temp);

printf("nDoyouwanttoentermore(y/n)?");getchar(); scanf("%c",&ch);
}while(ch=='y'|ch=='Y');

printf("nPreorder Traversal: ");preorder(root);


return 0;
}

node*create()
{
node *temp; printf("nEnter data:");
temp=(node*)malloc(sizeof(node));scanf("%d",&temp-
>data);temp->left=temp->right=NULL;return temp;
}
voidinsert(node*root,node*temp)
{
if(temp->data<root->data)
{
if(root->left!=NULL) insert(root->left,temp);
else
root->left=temp;
}
if(temp->data>root->data)
{
if(root->right!=NULL) insert(root->right,temp);
else
root->right=temp;
}
}
voidpreorder(node*root)
{
if(root!=NULL)
{
printf("%d",root->data);preorder(root->left);preorder(root->right);
}
}

OUTPUT:

[com39@localhost ~]$ cd os
[com39@localhost os]$ gcc ex6.c
[com39@localhostos]$

./a.out

74
EX.NO:12
IMPLEMENTATION OF SEARCHING TECHNIQUES

AIM

To write a C program Implementation of searching techniques.

ALGORITHM

1. Start the program


2. Get an array of numbers as input.
3. Get an under as input to be search ed in the array.
4. Define a loop to find the matching it ems in the array.
5. Repeat the loop un till match is found.
6. Stop the program

PROGRAM

#include
<stdio.h>void
main()
{
intarray[10];
inti,num,keynum,found=0;

printf("Enter the value of num \n");scanf("%d", &num);


printf("Entertheelementsonebyone \n");for(i=0;i<num;i++)
{
scanf("%d",&array[i]);
}
printf("Inputarrayis\n");for(i=0;i<num;i++)
{
printf("%dn",array[i]);
}
printf("Entertheelementtobesearched\n");scanf("%d",&keynum);
/*Linearsearchbegins*/for(i=0; i<num;i++)
{
if(keynum==array[i])
{

79
found=1;
break;}

}
if(found==1)
printf("Elementispresentinthearray\n");else
printf("Elementisnotpresentinthearray\n");
}

OUTPUT

Enterthevalueofnum5
Entertheelementsonebyone45678
90
40
100
Inputarrayis456
78
90
40
100
Entertheelementtobesearched70

RESULT

Thus above Program was Successfully Executed

80
EX.NO:13
IMPLEMENTATION OF SORTING ALGORITHMS

AIM

To write a C program Implementation of searching techniques

ALGORITHM

1. Start the program


2. GetanArrayofnumberstobesorted.3.SetMINtolocation0.
3. Search the minimum element in the list
4. Swap with value at location MIN
5. Increment MIN to point on ex telement
6. Repeatuntillistissorted.8.Stoptheprogram

PROGRAM

#include<stdio.h>
voidselection(int[],int,int,int,int);

intmain()
{
intlist[30],size,temp,i,j;
printf("Enter the size of the list: ");scanf("%d", &size);
printf("Entertheelementsinlist:\n");for(i=0;i<size; i++)
{
scanf("%d",&list[i]);
}
selection(list,0,0,size,1);
printf("Thesortedlistinascendingorderis\n");
for(i=0;i<size;i++)
{
printf("%d",list[i]);
}

return0;
}

81
voidselection(intlist[],inti,intj,intsize,intflag)
{
inttemp;

if(i<size-1)
{
if(flag)
{
j=i + 1;
}
if(j<size)
{
if(list[i]>list[j])
{
temp=list[i];list[i]=list[j];list[j]=temp;
}
selection(list,i,j+1,size,0);
}
selection(list,i+1,0,size,1);
}
}

OUTPUT

Enterthesizeofthelist:5Enter the
elements in list:
23
45
64
12
34
Thesortedlistinascendingorderis12 23
34 45 64

RESULT

Thus above Program was Successfully Executed

82
EX.NO:14
IMPLEMENTATION OF HASHING–ANY TWO COLLISION TECHNIQUES

AIM

To write A C program Implementation of Hashing–any two collision techniques.

ALGORITHM

1. Start the program.

2. Enter the Element so array.

3. Declare the functions line ar prob()and display().

4. Use the hash function to allocate the spot and to find the index
for record.
5. Repeat the process until collision occurs.

6. If collision occurs, calllinear prob()function to allocate the next


available spot in "higher" index.
7. Stop the program.

PROGRAM:

#include
<stdio.h>#include
<stdlib.h>#define
MAX 100 int
create(int);
void linear_prob(int[], int, int);
void display (int[]);
voidmain()
{
int a[MAX],num,key,i;int
ans=1;
printf("collisionhandlingbylinearprobing:\n");for(i=0;i<MAX;i++)
{
a[i]=-1;
}
Do{
printf("\n Enter the data");scanf("%4d", &num);
key=create(num);linear_prob(a,key,num);
printf("\nDoyouwishtocontinue?(1/0)");scanf("%d",&ans);
}while(ans);display(a);
}
intcreate(intnum)
{
83
int key; key=num
%100;return key;
}
voidlinear_prob(inta[MAX],intkey,intnum)
{
int flag, i, count=0;
flag=0;if(a[key]==-1)
{
a[key]=num;
}
else
{
printf("\nCollision Detected...!!!\n");i=0;
while(i<MAX)
{
if (a[i]!=-1) count+
+;i++;
}
printf("CollisionavoidedsuccessfullyusingLINEARPROBING\n");if(count==MAX)
{
printf("\nHashtableisfull");display(a);
exit(1);
}
for(i=key+1;i<MAX;i++)if(a[i]
==-1)
{
a[i]=num;flag=1;break;
}
//for(i=0;i<key;i++)i=0;
while((i<key) && (flag==0))
{
if(a[i]==-1)
{
a[i]=num;flag=1;break;

} i++;
}
}
}
voiddisplay(inta[MAX])
{
inti,choice;

84
printf("1.Display ALL\n 2.Filtered Display\
n");scanf("%d",&choice);if(choice==1)
{
printf("\nthehashtableis\n");for(i=0;i<MAX;i++) printf("\n
%d %d ", i, a[i]);
}
else
{
printf("\nthehashtableis\n");for(i=0;i<MAX;i++)
if(a[i]!=-1)
{
printf("\n%d%d",i,a[i]);continue;
}
}
}

OUTPUT:

collisionhandlingbylinearprobing:
Enterthedata1234

Doyouwishtocontinue?(1/0)1
Enter the data2548

Doyouwishtocontinue?(1/0)1
Enter the data3256

Doyouwishtocontinue?(1/0)1
Enter the data1299

Doyouwishtocontinue?(1/0)1
Enter the data1298

Doyouwishtocontinue?(1/0)1
Enter the data1398

CollisionDetected...!!!
CollisionavoidedsuccessfullyusingLINEARPROBING

Doyouwishtocontinue?(1/0) 0
1. DisplayALL
2. FilteredDisplay2
the hash table is0
1398
341234
85
482548
563256
981298
991299

RESULT

Thus above Program was Successfully Executed

86

You might also like