0% found this document useful (0 votes)
13 views135 pages

CDS Lab MODIFIED

MISRIMALNAVAJEEMUNOTHJAIN ENGINEERING COLLEGE aims to provide technical education and career skills to students, focusing on ethical development and continuous learning. The document includes a laboratory record template for students in the Electrical and Electronics Engineering department, detailing various C programming exercises and their corresponding algorithms, programs, outputs, and results. Each exercise demonstrates fundamental programming concepts such as conversions, leap year checks, and basic arithmetic operations.

Uploaded by

dhananjeyans41
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)
13 views135 pages

CDS Lab MODIFIED

MISRIMALNAVAJEEMUNOTHJAIN ENGINEERING COLLEGE aims to provide technical education and career skills to students, focusing on ethical development and continuous learning. The document includes a laboratory record template for students in the Electrical and Electronics Engineering department, detailing various C programming exercises and their corresponding algorithms, programs, outputs, and results. Each exercise demonstrates fundamental programming concepts such as conversions, leap year checks, and basic arithmetic operations.

Uploaded by

dhananjeyans41
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/ 135

MISRIMALNAVAJEEMUNOTHJAINENGINEERIN

GCOLLEGE
OWNEDANDMANAGEDBYTAMILNADUEDUCATIONALANDMEDICALTRUSTTHORAPAKKAM,CHENNAI-

600097.

LABORATORYRECORD

SUBJECT:………………………………
NAME:………………………………….

CLASS :………………………………….

REGISTERNUMBER :………………………………….
COLLEGE

VISION :
● To impart technical education and career skills to our students and
to develop them technically and ethically to contribute to the
advancement of the society and mankind.

MISSION :

● To inculcate strong fundamentals in basic science, mathematics


and Engineering concepts and thereby ignite the desire for
continuous learning.
● To educate future leaders by providing career skills and state of
the art facilities in all domains of Electrical and Electronic
Engineering.
● To nurture ethical and moral values and thereby mould the
students to serve the society.

DEPARTMENT :
ELECTRICAL AND ELECTRONICS ENGINEERING
MISRIMAL NAVAJEE MUNOTH JAIN
ENGINEERING COLLEGE
OWNED AND MANAGED BY TAMILNADU EDUCATIONAL AND MEDICAL TRUST
THORAPAKKAM , CHENNAI - 600 097.

NAME : ………………………………………… CLASS : …………………………….

REGISTER NO. : …………………………………………BRANCH : …………………………..

Certificate that this is a bonafide record of the work done by the above student
inthe…….……………………………………………………Laboratory during the year2023.

Signature Of The Faculty-In-Charge Signature Of Head Of Dept.

Submitted For The Practical Examination Held On ……………………………

External Examiner Internal Examiner

Date :
INDEX
S.No. DATE NAME OF THE EXPERIMENT PAGE SIGNATURE
1. PRACTICE OF C PROGRAMMING USING
STATEMENTS,EXPRESSIONS,DECISIONMAKINGANDITERATIVESTATEMENTS

Ex.No:1A
Aim: CONVERTINGCENTIGRADETOFAHRENHEIT
Date: TowriteaCprogramtoconvertcentigradetoFahrenheit.

Algorithm:
1. Start.
2. ReadcentigradevalueC.
3. CalculateF=C*(9/5)+32
4. PrintFahrenheitvalueF.
5. Stop.

Program:
#include<stdio.h>#in
clude<conio.h>voidma
in()
{
Float
c,f;clrscr();
printf(“CONVERSIONOFCENTIGRADETOFARENHEIT\n”);
scanf(“%f”,&c);
printf(“CENTIGRADEVALUE:%f\n”,c);printf(“\
n FORMULA
USED\n”);printf(“\nF=C*(9/5)+32\n”);
f=c*9/5+32;
printf(“\nFARENHEITVALUE:%\n”,f);getch();
}

OUTPUT:
CONVERSIONOFCENTIGRADETOFARENHEIT165
CENTIGRADEVALUE:165.000000FORMU
LAUSED
F=C*(9/5)+32
FAHRENHEITVALUE:329.000000

RESULT:
ThustheaboveCprogramisexecutedandtheoutputisverified.
Ex.No:1B
CHECKLEAPYEARORNOT
Date:
Aim:
TowriteaCprogramtocheckleapyearornot.

Algorithm:
1. Start.
2. Read year.
3. Check whetheryearisdivisibleby4and400andnotdivisibleby100.
4. Iftheconditionistruethenprintyearisleapyear.Otherwiseprintyearisnotleapyear.
5. Stop.

Program:
#include<stdio.h>#in
clude<conio.h>voidma
in()
{
int i,
year;clrscr();
printf(“EnterthevalueofN:”);scanf(
“%d”,&year);
if(((year%4==0)&&(year%100!=0))||(year%400==0))print
f(“%disaleapyear\n”,year);
else
printf(“%d is not a leap
year\n”,year);getch();
}

Output:
EntertheValueofN:20002000
isaleapyear.
EnterthevalueofN:
17001700isnotaleapyear.

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:1C
BIGGESTAMONGTWONUMBERSUSINGGOTO
Date:

Aim:
TowriteaCprogramtofindbiggestamongtwonumbersusinggoto.

Algorithm:
1. Start.
2. Readtwonumbersa,b.
3. Ifa>bthengotogreater.OtherwiseprintBisgreater thanA.
4. IngreatersectionprintAisgreaterthanB.
5. Stop.

Program:
#include<stdio.h>#in
clude<conio.h>voidma
in()
{
inta,b;clrsc
r();
printf(“Entertwonumbers:\n”);scan
f(“%d%d”,&a,&b);
if(a>b)
goto
greater;else
{
printf(“BisgreaterthanA”);exit(
0);
}
greater:
printf(“AisgreaterthanB”);getch();
}

Output:
Enter two numbers45
12
A is greater than
BEntertwonumbers45
97
BisgreaterthanA

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:1D
SIMULATINGSIMPLECALCULATOR
Date:

Aim:
TowriteaCprogramtosimulatesimplecalculator.

Algorithm:
1. Start
2. Displaythemenu
3. Readthechoice
4. If the choice is1,then Read two numbers .Add two numbers ,and print
theresult.
5. Ifthechoiceis2,thenreadtwonumbers,subtracta-bandprinttheresult.
6. If the choice is 3then read two numbers ,multiply two numbers and print
theresult.
7. Ifthechoiceis4thenreadtwonumbers,dividea/bandprinttheresult.
8. Ifthechoiceis5,thenexit.

Program:
#include<stdio.h>#in
clude<conio.h>voidma
in()
{
float
num1,num2,result;charop;
clrscr();
printf(“Typeyourexpression(num1opnum2)”);scanf(
“%f %c %f”, &num1,&op,&num2);switch(op)
{
case‘+’:
result=num1+num2;break;case‘
-’:
result=num1-
num2;break;case‘*’:
result=num1*num2;break;case‘
/’:
if(num2==0)
{
printf(“\nDivisionbyzeroerror”);
}
else
{
result=num1/num2;
}
break;defa
ult:
printf(“\nInvalidoperator”);
}
printf(“\n%.2f%c%.2f=%.2f”, num1,op,num2, result);getch();
}

Output:
Typeyourexpression(num1opnum2)65-98
65.00-98.00=-33.00
Typeyourexpression(num1opnum2)65+76
65.00+76.00=141.00
Typeyourexpression(num1opnum2)7*7
7*7=49

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:1E
PRINTINGNUMBERDIGITS
Date:

Aim:
Towriteacprogramtoprintnumberdigits.

Algorithm:
1. Start.
2. Read n
3. Ifnis1thenprint“ONE”,ifnis2thenprint“TWO”,Similarlyprinttillnumber9and
numbers 0.
4. Stop.

Program:#include<st
dio.h>#include<conio.
h>voidmain()
{
intn;clrscr()
;
printf(“Enterthevalueofn”);scanf
(“%d”,&n);
switch(n)
{
case1: printf(“ONE”);break;case2:
printf(“TWO”);break;case3:
printf(“THREE”);break;case4:
printf(“FOUR”);break;case5:
printf(“FIVE”);break;case6:
printf(“SIX”);break;case7:printf(“S
EVEN”);break;case8 :
printf(“EIGHT”);break;case9:
printf(“NINE”);break;case0:
printf(“ZERO”);break;default:
printf(“Invalidnumber”);break;
}
getch();
}
Output:
Enter the value of N: 1 ONEEnter
the value of N:2
TWOEnterthevalueofN:3THREEEn
ter the value of N:4 FOUREnter
the value of N:5 FIVEEnter the
value of N:6
SIXEnterthevalueofN:7SEVENEnte
r the value of N:8 EIGHTEnter the
value of N:9 NINEEnterthe value
ofN:0ZERO

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:1F
ILLUSTRATIONOFCONTINUESTATEMENT
Date:

Aim:
TowriteaCprogramtoprintnumberstoillustratecontinuestatement.

Algorithm:
1. Start
2. Assignj=10.
3. For (i=0;i<=j;i++)ifi==jthencontinueotherwiseprintI value
4.Stop.

Program:
#include<stdio.h>#in
clude<conio.h>voidma
in()
{
inti;
intj=10;clrscr();for(
i=0;i<=j;i++)
{
if(i==5)
{
continue;
}
printf(“Hello%d\n”,i);
}
getch();
}

Output:
Hello0Hell
o1Hello2H
ello3Hello4
Hello6Hell
o7Hello8H
ello9Hello
10

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:1G
ILLUSTRATIONOFFORLOOP
Date:
Aim:
Towriteacprogramtoevaluatetheseries.

Algorithm:
1. Start
2. Readn,assignsum=0
3. fori=1toncalculatesum=sum+1/(i*i*i)
4. printsum
5. Stop.

Program:
#include<stdio.h>voi
dmain()
{
intn,i,sum=0;clrscr();pri
ntf(“\nEnter
n\t”);scanf(“%d”,&n);for
(i=1;i<=n;i++)
{
sum=sum+i*i*i;
}
printf(“Sum=%d”,sum);getch();
}

Output:
Enter
n5Sum=225

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:1H
ILLUSTRATIONOFWHILECHECKINGPALINDROMENUMBERORN
Date: OT

Aim:
TowriteaCprogramtocheckwhethergiven numberispalindromenumberornot.

Algorithm:
1. Start.
2. Readn.
3. Assignrev=0 andtemp =h
4. Calculater=n%10rev=rev*10+rn=n/10
5. Repeatstep4tilln>0
6. Checkwhetherthevaluesoftempandreverseequal.
7. Ifbothareequalthenprintnumberispalindrome.
8. Ifbotharenotequalthenprintnumberisnotpalindrome.
9. Stop.

Program:
#include<stdio.h>#in
clude<conio.h>voidma
in()
{
int
n,r,rev,temp;rev=0;
clrscr();
printf(“Enterthenumber”);scanf(“%d”,&n);
temp=n;while(
n>0)
{r=n%10;
rev=rev*10+r;n=n
/10;
}
printf(“The reversed of number %d is = %d\n”, temp,
rev);if(temp==rev)
printf(“Itispalindrome”);else
printf(“Itisnotpalindrome”);getc
h();
}
Output:
Enterthenumber:123
Thereversedofnumber
123is=321ItisnotpalindromeEnterthenu
mber:151
Thereversedofnumber 151is=151Itis
palindrome

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:1I
ILLUSTRATIONOFDO-WHILEPRINTINGNUMBERS
Date:

Aim:
TowriteaCprogramtoprintnumbersusingdo-whileloop.

Algorithm:
1. Start
2. Assigndigit=0
3. Using do-whileloop Printthedigitandincrementi.Ifdigit<=9
4. Stop.

Program:
#include<stdio.h>#in
clude<conio.h>voidma
in()
{
int
digit=0;clrscr()
;
do
{
printf(“%d\t”,digit);
++digit;
}while(digit<=9);get
ch();
}

Output:

0 1 2 3 4 5 6 7 8 9
Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
2.PRACTICEOFCPROGRAMMING USINGFUNCTIONSANDARRAYS

Ex.No:2A
Aim: COMPUTINGMEAN VALUEOFNNUMBERS
Date: TowriteaCprogramtocomputethemeanvalueofNnumbers.

Algorithm:
1. Start
2. Readnumberofelementsn,andnnumbersinanarray.
3. Assignsum=0.
4. Readoneelementatatimefromthearrayandaddittothesum.
5. Calculatemean=sum/n
6. Printmean
7. Stop.

Program:#include<st
dio.h>#include<math.
h>voidmain()
{
intn,i;
float
A[20],sum=0.0,mean;clrscr();
printf("Enternumberofelements\n");scanf
("%d",&n);
printf("Entertheelements\n");for(i
=0;i<n;i++)
{
scanf("%f",&A[i]);
}
for(i=0;i<n;i++)
{
sum=sum+A[i];
}
mean=sum/n;
printf("Arithmetic
mean=%f\n",mean);getch();
}
Output:
Enternumberofelements6Entertheelements83
9
4
5
6
Arithmeticmean=5.833333

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:2B
MULTIPLICATIONOFTWOMATRICES
Date:

Aim:
TowriteaCprogramtomultiplytwomatrices.

Algorithm:
1. Start.
2. Entertherowandcolumn ofthematrixA.
3. EntertherowandcolumnofthematrixB.
4. EntertheelementsofthematrixA.
5. EntertheelementsofthematrixB.
6. PrinttheelementsofthematrixAinmatrixfrom.
7. PrinttheelementsofthematrixBinmatrixfrom.
8. Set aloopuptorow.
9. Set aninnerloopuptocolumn.
10. Setanotherinnerloopuptocolumn.
11. MultiplytheAandBmatrixandstoretheelementsintheCmatrix.
12. Printtheresultandmatrix.
13. Stop.

Program:
#include
<stdio.h>voidmain()
{intA[10][10],B[10][10],C[20][20];
int
i,j,k,m,n,p,q;clrscr();
printf(“EntertherowandcolumnvalueofAmatrix”);scanf(“%
d%d”,&m,&n);
printf(“EntertherowandcolumnvalueofBmatrix”);scanf(“%
d%d”,&p,&q);
if(n!=p)
{
printf(“matrixmultiplicationisnotpossible”);getch();
}
printf(“EntertheelementsofmatrixA”);for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&A[i][j]);
}
}
printf(“EntertheelementsofmatrixB”);for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf(“%d”,&B[i][j]);
}
}
for(i=0;i<m;i++)

{
for(j=0;j<q;j++)
{
for(k=0;k<n;k++)
{C[i][j]=C[i][j]+A[i][k]*B[k][j];
}
}
}
printf(“Theresultantmatrixis\n”);for(
i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf(%3d”,C[i][j]);
}
printf(“\n”);
}
getch();
}

Output:
Enter the row and column value of A matrix 3
3Enter the row and column value of B matrix 3
3EntertheelementsofmatrixA1
2
3
4
5
6
7
8
9
EntertheelementsofmatrixB987
6
5
4
3
2
1
Theresultandmatrixis
30241884695413811490
Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:2C
SWAPPINGTWONUMBERSUSINGPASSBYVALUE
Date:

Aim:
TowriteaCprogramswappingtwonumberusingpassbyvalue.

Algorithm:
1. Start
2. Callswapfunctionandpassa,basarguments.
3. Calculatex=x+y y=x-y x=x-y
4. Displaytheswappednumbers
5. Stop.

Program:
#include<stdio.h>voi
d
swap(int,int);voidmai
n()
{
int
a=10,b=20;clrscr()
;
printf(“Beforeswapvaluesare%d%d\n”,a,b);swap(a,
b);
printf(“Afterswapvaluesare%d%d\n”,a,b);getch();
}
voidswap(intx,inty)
{
x=x+y;y=
x-y;
x=x-y;
printf(“Inswapfunctionvaluesare%d%d\n”,x,y);return;
}

Output:
Beforeswapvaluesare1020
Inswapfunctionvaluesare2010After
swapvaluesare1020

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:2D
SWAPPINGTWONUMBERSUSINGPASSBYREFERENCE
Date:

Aim:
TowriteaCprogramswappingtwonumberusingpassbyaddress/reference.

Algorithm:
1. Start
2. Callswapfunctionandpassaddressofa,basarguments
3. Calculate
*x=*x+*y
*y=*x-*y
*x=*x-*y
4. Displayx,yvalues
5. Stop.

Program:
#include<stdio.h>int
swap(int*,int*);voidm
ain()
{
int
a=10,b=20;clrscr()
;
printf(“Beforeswapvaluesare%d%d\n”,a,b);swap(&
a,&b);
printf(“Afterswapvaluesare%d%d\n”,a,b);getch();
}
intswap(int*x,int*y)
{
*x=*x+*y;
*y=*x-*y;
*x=*x-*y;
printf(“Inswapfunction valuesare%d%d\n”,*x,*y);return;
}

Output:
Beforeswapvaluesare1020
Inswapfunctionvaluesare2010After
swapvaluesare 2010

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:2E
FACTORIALOFGIVENNUMBERUSINGRECURSIVEFUNCTION
Date:

Aim:
TowriteaCprogramtofindthefactorialofanumberusingrecursion.

Algorithm:
1. Start
2. Enterthenumber
3. Callthefactorialrecursivefunctionbypassingthenumber
4. Print theresult
5. Stop.Recursive
Function:
1. Startthefunction
2. Assignfact=1
3. Ifnumequals1thenfactorialis1
4. Calculatefact=x*fact(x-1)
5. Returnfactvalue

Program:
#include<stdio.h>#in
clude<conio.h>intfact
(int);
voidmain()
{
intn;clrscr()
;
printf(“Enterthenumber:\n”);scanf
(“%d”,&n);
printf(“factorialof%d=%d”,n,fact(n));getch()
;
}
intfact(intx)
{
inti;
if(x ==
1)return(1);e
lse
i=x*fact(x-
1);return(i);
}

Output:
Enterthenumber:5Factorial
of5=120
Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
3.IMPLEMENTCPROGRAMSUSINGPOINTERSANDSTRUCTURES
Ex.No:3A
POINTERSANDARRAYS
Date:

Aim:
Towriteacprogramtoprintvaluesandaddressofelementsusingpointers.

Algorithm:
1. Start
2. Declareandassignthearray
3. Declareandinitializepointervariable.
4. Printthevaluesandaddressofarrayelementsusingforloop.
5. Stop

Program#include<st
dio.h>intmain()
{
intarr[5]={10,20,30,40,50};
inti,*p_arr;for(i=0;i
<=5;i++)
{
printf(“Address=%u”,&arr[i]);printf
(“Element =
%d”,&arr[i]);printf(%d”,*(arr+i);pr
intf(“%d”,p_arr[i]);
printf(“%d”,*(p_arr+i));

Output:
Address4000Element10101010
Address4002Element20202020
Address4004Element30303030
Address4006Element40404040
Address4008Element50505050

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:3B
POINTERSTOPOINTERS
Date:

Aim:
Towriteacprogramtoprintvaluesandaddressofelementsusingpointers.

Algorithm:
1. Start
2. Declareandassignthevariable.
3. Declareandinitializepointervariable.
4. Printthevaluesandaddressoftheelement.
5. Stop

Program#include<st
dio.h>voidmain ()
{
int a =
10;int*p;
int**pp;
p =&a;// pointerp ispointingto the addressofa
pp=&p;//pointerppisadoublepointerpointingtotheaddressofpointerpprintf("addressofa:%
x\n",p);
printf("address of p: %x\n",pp);printf("value
stored at p:
%d\n",*p);printf("valuestoredatpp:%d\n",**
pp);
}

Output:
Addressofa:
d7675d8Addressofp:d8586
d8Value stored at p:
10Valuestored atpp:10

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:3C
ARRAYOFSTRUCTURES:CALCULATINGSTUDENTMARKDETAILS
Date:

Aim:
TowriteaCprogramtocalculatethetotalmarks usingarrayofstructures.

Algorithm:
1. Start
2. Declarethestructurewithmembers.
3. Initializethemarksofthestudents
4. Calculate the subjecttotal by
addingstudent[i].sub1+student[i].sub2+student[i].sub3.
5. Printthetotalmarksofthestudents
6. Stop.

Program:
#include<stdio.h>#in
clude<conio.h>struct
marks
{
intsub1,sub2,sub3,total;
};
voidmain()
{
inti;
structmarksstudent[3]={{45,67,81,0},{75,53,69,0},
{57,36,71,0}};
structmarkstotal;for(i=0;i<=2;i++)
{
student[i].total=student[i].sub1+student[i].sub2+student[i].sub3;
}
printf(“TOTAL
MARKS\n\n”);for(i=0;i<=2;i++)
printf(“student[%d]:%d\n”,i+1,student[i].total);
}

Output:
TOTALMARKS
student[1]:193st
udent[2]:197stud
ent[3]:164

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
4.IMPLEMENTCPROGRAMSUSINGFILES
Ex.No:4 A
READINGANDWRITINGAFILE
Date:

Aim:
TowriteaCprogramtoreadandwriteafile.

Algorithm:
1. Start
2. Createafilepointer
3. Readthefilenametobeopened.
4. Openthefilewithwritemode.
5. Writethedata
6. Openthefile withreadmode
7. Print thedata
8. Stop.

Program:
#include
<stdio.h>#defineSIZE
50Intmain()
{
FILE*fptr;
Chars1[SIZE],s2[SIZE];
printf(“\nEnteranystring:“);gets
(s1);

fptr=fopen(“abc.txt”,
“w”);fputs(s1,fptr);
fclose(fptr);
fptr=fopen(“abc.txt”,“r”);fgets(s2,
SIZE,fptr);printf(“\nYou
entered:”);puts(s2);
}

Output:
Enteranystring:
PSVPEC
YOUENTERED:
PSVPEC

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:4B
PROGRAMTOCOPYONEFILETOANOTHER
Date:

Aim:
TowriteaCprogramtocopyonefiletoanother.Algorith
m:
1. Start
2. Createfilepointers
3. Readtwofilenames
4. Openfirstfilewithread mode
5. Opensecondfilewithwritemode
6. Read first file character by character and write the characters in the second
filetillendoffilereached.
7. Closebothfilepointers
8. Stop.

Program:
#include
<stdio.h>#include<co
nio.h>main()
{
FILE*fp1,*fp2;
charfilename1[20],filename[20],str[30];clrscr
();
printf(“\nEnterthenameofthefirstfilename:“);gets(filenam
e1);
fflush(stdin);
printf(“\nEnterthenameofthesecondfilename:“);gets(filena
me2);
fflush(stdin);if((fp1=fopen(filename1,“r”))==0)
{
printf(“\nErroropeningthefirstfile”);exit(1);
}
if((fp2=fopen(filename2,“w”))==0)
{
printf(“\nErroropeningthesecondfile”);exit(1);
}
while((fgets(str,
sizeof(str),fp1))!=NULL)fputs(str,fp2);
fclose(fp1);fcl
ose(fp2);getch()
;return0;
}
Output:
Enter the name of the first
filename:a.txtEnterthename
ofthesecondfilename:b.txtFILECOPIED

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
5.DEVELOPMENTOFREALTIMECAPPLICATIONS
Ex.No:5
PROGRAMTOIMPLEMENTTIC-TAC-TOE GAME
Date:

Aim:
To write a C program to implement gaming application by using C language for tic-tac
-toegame.

Algorithm:
1. Start.
2. Eachstateisdenotedbythepositionsoccupiedbythelettersofthetwoplayersina3x3matrix
andotheremptyplaces.
3. InitialState:Anempty3x3matrix.
4. IntermediateState: Anyarrangementofa3x3matrixobtained
afterapplyingvalidrulesonthecurrentstate.
5. FinalState:Samelettersinacompleterowor
completecolumn,orcompletediagonalwinsthegame.
6. Rules: The players will get turns one after the other; they can mark their letters
onthe emptycell.
7. Stop.

Program:
#include<stdio.h>usingna
mespacestd;#defineCOMP
UTER1
#defineHUMAN2
#defineSIDE3
#defineCOMPUTERMOVE'O'
#defineHUMANMOVE 'X'

voidshowBoard(charboard[][SIDE])
{
printf("\n\n");

printf("\t\t\t%c|%c|%c\n", board[0][0],board[0][1],board[0][2]);
printf("\t\t\t \n");
printf("\t\t\t%c|%c|%c\n",board[1][0],board[1][1],board[1][2]);
printf("\t\t\t \n");
printf("\t\t\t%c|%c|%c\n\n", board[2][0],board[2][1],board[2][2]);

return;
}

voidshowInstructions()
{
printf("\t\t\tTic-Tac-Toe\n\n");
printf("Chooseacellnumberedfrom1to9asbelow""andplay\
n\n");
printf("\t\t\t1 | 2| 3
\n");printf("\t\t\t \n");
printf("\t\t\t4 | 5| 6
\n");printf("\t\t\t \n");
printf("\t\t\t7 |8|9\n\n");
printf("-\t-\t-\t-\t-\t-\t-\t-\t-\t-
\n\n");return;
}
voidinitialise(charboard[][SIDE],intmoves[])
{

srand(time(NULL));

for(inti=0;i<SIDE;i++)
{
for(int
j=0;j<SIDE;j++)board[i][j]= '';
}

for(inti=0;i<SIDE*SIDE;i++)moves[
i]=i;
random_shuffle(moves,moves+SIDE*SIDE);return;

voiddeclareWinner(intwhoseTurn)
{
if (whoseTurn ==
COMPUTER)printf("COMPUTERhasw
on\n");else
printf("HUMANhaswon\n");return;
}

boolrowCrossed(charboard[][SIDE])
{
for(inti=0;i<SIDE;i++)
{
if(board[i][0]==board[i][1]&&
board[i][1]==board[i][2]&&
board[i][0]!='')return(t
rue);
}
return(false);
}

boolcolumnCrossed(charboard[][SIDE])
{
for(inti=0;i<SIDE;i++)
{
if(board[0][i]==board[1][i]&&
board[1][i]==board[2][i]&&
board[0][i]!='')return(t
rue);
}
return(false);
}

booldiagonalCrossed(charboard[][SIDE])
{
if(board[0][0]==board[1][1]&&
board[1][1]==board[2][2]&&
board[0][0]!='')return(true);

if(board[0][2]==board[1][1]&&
board[1][1]==board[2][0]&&
board[0][2]!='')return(true);

return(false);
}

boolgameOver(charboard[][SIDE])
{
return(rowCrossed(board)||columnCrossed(board)||diagonalCrossed(board));
}

voidplayTicTacToe(int whoseTurn)
{
char

board[SIDE][SIDE];intmoves[

SIDE*SIDE];initialise(board,

moves);showInstructions();

intmoveIndex=0,x,y;

while(gameOver(board)==false&&moveIndex!=SIDE*SIDE)
{
if(whoseTurn==COMPUTER)
{
x = moves[moveIndex] /
SIDE;y=moves[moveIndex]%SIDE;
board[x][y]=COMPUTERMOVE;
printf("COMPUTERhasputa%cincell%d\n",COMPUTERMOVE,moves[moveIndex]+1);
showBoard(board);moveInd
ex ++;whoseTurn=HUMAN;
}

elseif(whoseTurn==HUMAN)
{
x = moves[moveIndex] /
SIDE;y=moves[moveIndex]%SIDE;bo
ard[x][y]=HUMANMOVE;
printf("HUMANhasputa%cincell%d\n",HUMANMOVE,moves[moveIndex]+1);
showBoard(board);mo
veIndex++;
whoseTurn=COMPUTER;
}
}

if(gameOver(board)==false&&moveI
ndex == SIDE *
SIDE)printf("It'sadraw\n");
else
{
if(whoseTurn==COMPUTER)whoseT
urn=HUMAN;
elseif(whoseTurn==HUMAN)whoseT
urn= COMPUTER;

declareWinner(whoseTurn);
}
return;
}

intmain()
{
playTicTacToe(COMPUTER);

return(0);
}
Output:
Tic-Tac-Toe

Chooseacellnumberedfrom1to9asbelowandplay

1|2|3

4|5|6

7|8|9

- - - - - - - - - -

COMPUTERhasputaOincell6

| |

| |O

| |

HUMAN hasputaXincell7

| |

| |O

X| |

COMPUTERhasputaOincell5

| |

| O| OX |

HUMAN hasputaXincell1

X| |

| O| OX |

COMPUTERhasputaOincell9
X| |

| O| OX |

|O

HUMAN hasputaXincell8

X| |

| O| OX|X|O

COMPUTERhasputaOincell4

X| |

O | O| OX

|X|O

COMPUTERhaswon

Result:
Thus,theaboveprogramhasbeenexecutedsuccessfully.
Ex.No:6
ARRAYIMPLEMENTATIONOFLISTADT
Date:

Aim:
To write a program in C to implement the list ADT using array concept
thatperforms alltheoperations ofstack.

Algorithm:

1. Createanarray[ ]withMAXsizeas yourwish.


2. Writefunctionforallthebasicoperationsoflist-
create(),insert(),deletion(),search(),display().
3. ByusingSwitchcase,selectcreate()operationtocreatethelist.
• ListWillbe intheform:A1,A2,A3, An
• FirstElementoftheList:A1
• LastElementoftheList:An
• ithElementoftheList:Ai,
• PositionofElementAi:i,Positionrangesfrom0toN
• Sizeofthe List:N
• EmptyList:IfSizeofthelistisZero(i.eN=0),itisEmptyList.
• PrecedesandSucceeds:Foranylistexceptemptylist,wesaythat
Ai+1follows(orsucceeds)Ai(i<N)andthatAi-1precedesAi(i>1)
4. Similarly, by using Switch case, select insert() operation to insert element
inthe list.
• InsertxatpositionpinlistL
• Ifp=END(L),insertxattheend
• IfLdoesnothavepositionp,resultisundefined
5. Similarly,byusingSwitchcase,selectdelete()functionisusedtoremove
theelementfromthelist.
• deleteelementatpositionpinL
• undefinedifp=END(L)ordoesnotexist
6. Similarly,byusingSwitchcase,selectsearch()functionisusedtoretrieve
therequired elementfromthelistifitisavailable.
• returnselementatpositionponL
• undefinedifpdoesnotexistorp=END(L)
7. Similarly, by using Switch case, select display() operation
todisplayallelementofthelistprinttheelementsofLinorderofoccurre
nce
8. Closetheprogram
Program:
#include<stdio.h>#inc
lude<conio.h>
#defineMAX10voidcreate();voidin
sert();
void search();void
deletion();voiddisp
lay();
inta,b[20],n,p,e,f,i,pos;voidmain()
{
intch;charg='y';clrscr();do
{
printf("\nmainmenu");
printf("\n1.create\n2.deletion\n3.search\n4.insert\n5.display\n6.exit\n");printf("\nent
eryourchoice:");
scanf("%d",&ch);switch(ch)
{
case1:
create();break;case2:
deletion();break;case3:
search();break;case4:
insert();break;case5:
display();break;case6:
exit(0);break;default:
printf("\nenterthecorrectchoice:");
}
printf("\ndoyouwanttocontinue.
");fflush(stdin);scanf("\n%c",&g);
}
while(g=='y'||g=='Y');getch();
}
voidcreate()
{
printf("\nenterthenumberofnodes:");scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("\nentertheelement:");scanf("%d",&b[i]);
}
}
voiddeletion()
{
printf("\nenterthepositionyouwanttodelete
");scanf("%d",&pos);if(pos>=n)
{
printf("\nInvalidlocation");
}
else
{
for(i=pos+1;i<n;i++)
{
b[i-1]=b[i];n--;
printf("elementsafterdeletion");for(i=0;i<n;i++)printf("\t%
d",b[i]);
}
}
}
voidsearch()
{
intflag=0;
printf("\nentertheelementsto
besearched:");scanf("%d",&e);for(i=0;i<n;i++)
{
if(b[i]==e)
{
flag=1;
printf("valueisinthe%dposition",i);break;
}
}
if(flag==0)
printf("value%disnotinthe list ",e);
}
voidinsert()
{
printf("\nenterthepositionyouneedtoinsert
");scanf("%d",&pos); if(pos>=n&&pos<MAX-1)
{
printf("\nInvalidlocation");
}
else
{
for(i=n-1;i<pos-1;i-
-)b[i+1]=b[i];printf("\nentertheelementtoinser
t\n");scanf("%d",&p);

b[pos]=p;n++;
}
printf("\nthelistafterinsertion.
\n");display();
}
voiddisplay()
{
printf("\n the elements of the list ADT are.
");for(i=0;i<n;i++)printf("\n\n%d",b[i]);
}
Output:
Result:
ThustheprogramforimplementationofarrayoflistADTiswrittenandexecutedsuccessfully.
7.ARRAYIMPLEMENTATIONOFSTACKANDQUEUEADTs
Ex.No:7A
STACKADT
Date:

Aim:
TowriteaprograminCtoimplementthestackADTusingarrayconceptthat
performsalltheoperationsofstack.

Algorithm:
1. Includealltheheader
fileswhichareusedintheprogramanddefineaconstant'SIZE'withspecificvalue.
2. Declareallthefunctionsusedinstackimplementation.
3. Createaonedimensionalarraywithfixedsize(intstack[SIZE])
4. Defineaintegervariable'top'andinitializewith'-1'.(inttop=-1)
5. In main method, display menu with listof operations andmake suitable
functioncallstoperformoperationselectedbytheuseronthestack.
Push():

● Checkwhetherstack isFULL. (top==SIZE-1)


● IfitisFULL,thendisplay"StackisFULL!!!Insertionisnotpossible!!!"andterminatethe
function.
● IfitisNOTFULL,thenincrementtopvaluebyone(top++)andsetstack[top]tovalue(
stack[top]=value).
Pop():
● CheckwhetherstackisEMPTY. (top==-1)
● IfitisEMPTY,thendisplay"StackisEMPTY!!!Deletionisnotpossible!!!"andtermin
ate thefunction.
● IfitisNOT EMPTY,thendeletestack[top]anddecrementtopvaluebyone(top--).

Display():
● CheckwhetherstackisEMPTY. (top==-1)
● IfitisEMPTY,thendisplay"StackisEMPTY!!!"andterminatethefunction.
● IfitisNOTEMPTY,thendefineavariable'i'andinitializewithtop.
● Displaystack[i]valueanddecrementivaluebyone(i--).
● Repeatabove stepuntilivaluebecomes'0'.
Program:
#include<stdio.h>
intstack[100],choice,n,top,x,i;void
push();
voidpop();void
display();main()
{
top=-1;
printf("\nEntersizeofSTACK[MAX=100]:");scanf("%d",&n);
printf("\n Stack opens using
array");printf("\n1.push\n2.pop\n3.display\n4.Exi
t");do
{
printf("\nenterchoice");scan
f("%d",&choice);switch(choi
ce)
{
case1:
push();bre
ak;case2:
pop();brea
k;case3:
display();bre
ak;case 4:
printf("\n
Exit");break;
default:
printf("\nEntervalidchoice(1/2/3/4)");
}
}
while(choice!=4);ret
urn0;
}
voidpush()
{
if(top>=n-
1)printf("\nStackfull");el
se
{
printf("\nEnteravaluetobepushed");scanf("
%d",&x);
top++;stack[top]
=x;
}
}
voidpop()
{
if(top<=-1)
printf("\nstackunderflow");else
{
printf("\npopedis%d",stack[top]);top--;
}
}
voiddisplay()
{
if(top>=0)
{
printf("\nElementsinstack\n");for(i=
top;i>=0;i--)
printf("\n
%d",stack[i]);printf("\npressnext
choice");
}
else
print("stackisempty");
}
OUTPUT:

Result:
Thustheprogramforimplementationofarrayofstackiswrittenandexecutedsuccessful
ly.
Ex.No:7B
QUEUEADT
Date:

Aim:
AimistowriteaprograminCto
implementthequeueusingarrayconceptthatperformsalltheoperation.

Algorithm:

1. Includealltheheaderfiles whichareusedintheprogramand
defineaconstant'SIZE'withspecificvalue.
2. Declarealltheuserdefinedfunctionswhichareusedinqueueimplementation.
3. CreateaonedimensionalarraywithabovedefinedSIZE(intque
ue[SIZE]).
4. Definetwo integervariables'front'and'rear'andinitializebothwith
'-1'.(intfront=-1,rear=-1).
5. Then implement main method by displaying menu of operations list andmake
suitable function calls to perform operation selected by the user onqueue.
Enqueue:
● CheckwhetherqueueisFULL.(rear==SIZE-1)
● IfitisFULL,thendisplay"QueueisFULL!!!Insertionisnotpossibl
e!!!"andterminatethe function.
● IfitisNOTFULL,thenincrementrearvaluebyonerear++
andsetqueue[rear]=value.
Dequeue:
● Checkwhether queueisEMPTY.(front==rear)
● IfitisEMPTY,thendisplay"QueueisEMPTY!!!Deletionisnotpossible!!!"and
terminatethe function.
● If it is NOT EMPTY, then increment the front value by one (front ++).
Thendisplay queue[front] as deleted element. Then check whether both front
andrear are equal (front == rear), if it TRUE, then setboth front and rear to '-
1'(front=rear=-1).
Display:
● CheckwhetherqueueisEMPTY.(front==rear).
● IfitisEMPTY,thendisplay"QueueisEMPTY!!!"andterminatethefunction.
● IfitisNOTEMPTY,thendefine anintegervariable'i'and set'i=front+1'.
● Display'queue[i]'valueandincrement'i'value
byone(i++).Repeatthesameuntil'i'valuereaches torear(i<=rear).
Program:
#include<stdio.h>#in
clude<conio.h>#defin
e n5
main()
{
intqueue[n],ch=1,front=0,rear=0,i,j=1,x=n;print
f("queue usingarray");printf("\n1.Queue
usingArray");
printf("\n1.Insertion\n2.Deletion\n3.Display\n4.Exit");w
hile(ch)
{
printf("\nEnterthechoice:");scan
f("%d",&ch);switch(ch)
{
case1:
if(rear==x)printf("\nQueueis
Full");else
{
printf("\nEnter no
%d:",j++);scanf("%d",&queue[rear
++]);
}
break;cas
e2:
if(front==rear)printf("\nQueue
isempty");else
{
printf("\nDeletedelement is%d"),queue[front++]);x++;
}
break;cas
e3:
printf("\nQueueelementare:\n");if(fr
ont==rear)
printf("\nQueueisempty");else
{
for(i=front;i<rear;i++)
{
printf("%d",queue[i]);prin
tf("\n");
}
break;case
4:exit(0);b
reak;defaul
t:
printf("wrongchoicepleaseseetheoptions");
}
}
}
getch();retu
rn0;
}

OUTPUT:

Result:
Thustheprogramforimplementationofarrayofqueueiswrittenandexecutedsuccessfu
lly.
8.LINKEDLISTIMPLEMENTATIONOFLIST,STACK,QUEUEADTs

Ex.No:8 A
SINGLYLINKEDLIST
Date: Aim:
TowriteaprograminCtoimplementthesinglylinkedlistusingarray
conceptthatperformsalltheoperations.

Algorithm:

1. Includealltheheaderfileswhichareusedintheprogram.Anddeclarealltheuserdefinedfunc
tions.
2. Definea'Node'structurewithtwomembersdataandnext.
3. DefineaNodepointer'top'andsetittoNULL.
4. Implement the main method by displaying Menu with list of operations and
makesuitablefunctioncallsinthemainmethod.
5. push(value)-InsertinganelementintotheStack•CreateanewNodewithgivenvalue.
• CheckwhetherstackisEmpty(top==NULL)•IfitisEmpty,thensetnewNode→next=NULL.
• IfitisNotEmpty,thensetnewNode→next=top.
• Finally, settop=newNode.
6. pop() - Deleting an Element from a Stack 1. Check whether stack is Empty (top
==NULL).
• IfitisEmpty,thendisplay"StackisEmpty!!!Deletionisnotpossible!!!"andterminatethe
function
• IfitisNotEmpty,thendefineaNodepointer 'temp'andsetitto'top'.
• Thenset'top=top→next'.
• Finally,delete'temp'(free(temp)).
7. display()-Displayingstackofelements
• Checkwhetherstackis Empty(top==NULL).
• IfitisEmpty,thendisplay'StackisEmpty!!!'andterminatethefunction.
• IfitisNotEmpty, thendefineaNodepointer 'temp'andinitializewithtop.
• Display'temp→data--->'andmoveittothenextnode.Repeatthesameuntiltempreachestothe
firstnode inthe stack(temp→next!= NULL).
• Finally!Display'temp→data--->NULL'.
Program:#include<s
tdio.h>#include<coni
o.h>#include<stdlib.h
>typedefstructlist
{
introll;
char
name[20];structli
st*link;
}node;
node*getnode();
voidcreatelist(node**headptr);voidins
ertfirst(node**headptr);void
insertmiddle(node**headptr);voidinse
rtlast(node**headptr);void
deletefirst(node**headptr);void
deletelast(node**headptr);voiddelete
middle(node**headptr);voidmodifynod
e(node*head);voidviewlist(node*head);
intcountlist(node*head);
void
releasenode(node*newnode);voiddispl
aymenu();
voidmain()
{
node*head=NULL;intch,
count;clrscr();display
menu();while(1)
{
printf("EnterYourChoice:");fflush(
stdin);scanf("%d",&ch);
switch(ch)
{
case
0:createlist(&head);b
reak;
case
1:insertfirst(&head);
break;
case
2:insertmiddle(&head);b
reak;
case
3:insertlast(&head);b
reak;
case
4:deletefirst(&head);
break;case5:
deletelast(&head);bre
ak;
case6:
deletemiddle(&head);bre
ak;
case7:
modifynode(head);bre
ak;
case8:
viewlist(head);bre
ak;
case9:
count=countlist(head);
printf("Number of nodes in the list
:%d\n",count);break;
case10:
displaymenu();bre
ak;
case11:
clrscr();bre
ak;default:
printf("EndofPrograms.\n");exit(
0);
}
}
}
voiddisplaymenu()
{
printf("Basicoperationinsinglylinkedlist:\n\n\n");printf("0.
Create list\n\n");
printf("1.Insertfirst\n\n");printf
("2.Insert
middle\n\n");printf("3.Insertlast
\n\n");printf("4.Delete
first\n\n");printf("5.deletelast\n
\n");
printf("6.delete middle\n\n7.modify
node\n\n8.viewlist\n\n9.count\n\n10.showmenu\n\n11.clear\n
\n12.exit\n\n");
}
node*getnode()
{
node*newnode;
intsize=sizeof(node);newnode=(no
de*)malloc(size);return(newnode);
}
voidreadnode(node*newnode)
{
printf("\nEntertherollnumber:");scanf(
"%d",&newnode->roll);printf("\nEnter
the name :");scanf("%s",newnode
->name);newnode->link=NULL;
}
voidreleasenode(node*newnode)
{
free(newnode);
}
voidcreatelist(node**headptr)
{
node*head=NULL,*newnode,*last;charc
h;
do
{
newnode=getnode();rea
dnode(newnode);if(head
==NULL)
{
head=newnode;last
=head;
}
else
{
last
->link=newnode;last=las
t->link;
}
fflush(stdin);
printf("\nDoyouwishto addfurtherdatainthelist?\n\t\t(Y/N)\n\n");scanf("%c",&ch);
}
while((ch=='Y')||(ch=='y'));
*headptr=head;
}
voidinsertfirst(node**headptr)
{
node*head,*newnode;hea
d=*headptr;newnode=get
node();readnode(newnode)
;if(head==NULL)
{
head=newnode;
}
else
{
newnode
->link=head;head=newnod
e;
}
*headptr=head;
}
voidinsertlast(node**headptr)
{
node*head,*newnode,*last;hea
d=*headptr;newnode=head=*he
adptr;newnode=getnode();read
node(newnode);if(head==NULL)
{
head=newnode;
}
else
{
last=head;
while(last
->link!=NULL)last=last->link;
last->link=newnode;
*headptr=head;
}
}
voidinsertmiddle(node**headptr)
{
node
*head,*last,*newnode;intinsdat
a;
head=*headptr;if(he
ad==NULL)
{
printf("\nSinglylinkedlistisempty.\n\nNewnodeisheadnode...");newnode=getnode();
readnode(newnode);hea
d=newnode;
}
else
{
printf("\nEntertherollnumber afterwhichdataistobeinserted:");scanf("%d",&insdata);
last=head;while(last!=
NULL)
{
if(last->roll==insdata)
{
newnode=getnode();readnode(
newnode);newnode->link=last
->link;last
->link=newnode;return;
}
else
last=last->link;
}
printf("\nInsertnodeisnotfound.");
}
*headptr=head;
}
voiddeletefirst(node**headptr)
{
node*head,*delnode;hea
d=*headptr;if(head==NU
LL)
{
printf("\n\nSingly linked list is
empty.");return;
}
delnode=head;head=h
ead->link;
printf("\nDeletelistis\n\nRollnumber:%d\n\nName:%s\n",delnode->roll,delnode-
>name);releasenode(deln
ode);
*headptr=head;
}
voiddeletelast(node**headptr)
{
node*head,*delnode,*last,*prev;head
=*headptr;
if(head==NULL)
{
printf("\n\nSingly linked list is
empty.\n");return;
}
elseif(head->link==NULL)
{
delnode=head;hea
d=NULL;
}
else
{
last=head;
while(last->link!=NULL)
{
prev=last;last=las
t->link;
}
delnode=last;
prev->link=NULL;
}
printf("\nDeletelistis\n\nRollNUmber:%d\n\nName:%s\n",delnode->roll,delnode-
>name);releasenode(deln
ode);
*headptr=head;
}
voiddeletemiddle(node**headptr)
{
node*head,*delnode,*last,*prev;intde
ldata;
head=*headptr;if(he
ad==NULL)
{
printf("\n\nSingly linked list is
empty.\n");return;
}
printf("\n\nEnterthenoderollnumbertobedeleted:");scanf("%d",&
deldata);
if(head->roll==deldata)
{
delnode=head;head=h
ead->link;
printf("\nDeletedlistis\n\nRollnumber:%d\n\nName:%s\n",delnode->roll,delnode-
>name);releasenode(deln
ode);
*headptr=head;ret
urn;
}
last=head
->link;prev=head;while
(last!=NULL)
{
if(last->roll==deldata)
{
delnode=last;
prev->link=last->link;
printf("\nDeletelist is\n\nRollnumber:%d\n\nName:%s\n",delnode->roll,delnode-
>name);releasenode(deln
ode);
*headptr=head;ret
urn;
}
else
{
last=last
->link;prev=prev
->link;
}
printf("\n\nDeletenodenot found.\n");
*headptr=head;
}
}
voidmodifynode(node*head)
{
intmoddata;
if(head==NULL)
{
printf("\n\nSingly linked list is
empty.\n");return;
}
printf("\n\nEnternoderollnumberformodification:");scanf("%d",
&moddata);
while(head!=NULL)
{
if(head->roll==moddata)
{
printf("\n\nModifythedataofthenode\nEnter
thenewnode:");scanf("%s",head->name);
return;
}
else
{
head=head->link;
}
}
printf("\nModifynodeisnotfound.\n");
}
voidviewlist(node*head)
{
if(head==NULL)
{
printf("\n\nSingly linked list is
empty.\n");return;
}
for(;head!=NULL;head=head->link)
{
printf("\n\nRollnumber :%d\n\nName:%s\n",head->roll,head->name);
}
}
intcountlist(node*head)
{
intcount=0;if(head=
=NULL)
{
printf("\n\nSingly Linked list is
empty.\n");returncount;
}
for(;head!=NULL;head=head->link)
{
count=count+1;
}
returncount;}
Output:
Result:
Thustheprogramfor implementationofsinglylinkedlistiswrittenandexecutedsuccessfully.
Ex.No:8B
STACKADT
Date:

Aim:
AimistowriteaprograminCtoimplementthestackusingarrayconceptthat
performsalltheoperationsofstack.

Algorithm:
1. Includealltheheaderfileswhichareusedintheprogram.Anddeclarealltheuser
definedfunctions.
2. Definea'Node'structurewithtwomembersdataand
next.
3. DefineaNodepointer'top'andsetittoNULL.
4. Implement themainmethod bydisplaying Menuwithlist of
operations and make suitable function calls inthe
mainmethod.
Push():
● CreateanewNodewithgivenvalue.
● CheckwhetherstackisEmpty(top==NULL).
● IfitisEmpty,thensetnewNode→next=
NULL.
● IfitisNotEmpty,thensetnewNode→next
=top.Finally,settop=newNode.
Pop():
● Checkwhether stackisEmpty (top==NULL).
● IfitisEmpty,thendisplay"StackisEmpty!!!Deletion
isnotpossible!!!"andterminate thefunction
● IfitisNot Empty,thendefineaNodepointer'temp'andsetitto'top'.
● Thenset'top=top→next'.
● Finally,delete'temp'.(free(temp)).Displa
y():
● CheckwhetherstackisEmpty(top==NULL).
● IfitisEmpty,thendisplay'StackisEmpty!!!'andterminatethefunction.
● IfitisNotEmpty,thendefineaNodepointer'temp'andinitializewithtop.
● Display 'temp → data --->' and move it to the next node. Repeat
thesameuntiltempreachestothefirstnodeinthestack.(temp→next!=NULL).
● Finally!Display'temp→data--->NULL'.
Program:
#include<stdio.h>#in
clude<conio.h>#inclu
de<stdlib.h>voidpop();
void push(int
value);voiddisplay();str
uctnode
{
intdata;
struct
node*top=NULL,*temp;voidmain()
{
int
ch,data;while(
1)
{
printf("\n1.push\n2.pop\n3.display\n4.exit");pr
intf("\n enter the choice");scanf("%d",&ch);
switch(ch)
{
case1:
printf("\nenteranewelement");scanf
("%d",&data);
push(data);bre
ak;
case2:
pop();brea
k;case3:
display();bre
ak;case 4:
exit(0);
}}}
voiddisplay()
{
temp=top;if(temp==N
ULL);printf("\nempty")
;
printf("\nthecontentsofstackare ");
while(temp!=NULL)
{
printf("%d->",temp
->data);temp=temp->link;
}}
voidpush(intdata)
{
temp=(structnode*)malloc(sizeof(structnode));tem
p->data=data;
temp
->link=top;top=tem
p;display();
}
voidpop()
{
if(top!=NULL)
{
printf("\nthepoppedelementsis%d",top->data);top=top
->link;
}
else
{
printf("\nstackunderflow");
}
display();
}
OUTPUT:
Result:
Thus the program for implementation of stack using linked list is written
andexecutedsuccessfully.
Ex.No:8C
QUEUEADT
Date:

Aim:

TowriteaprograminCtoimplement thequeueusinglinkedlistconcept
thatperformsalltheoperationsofstack.

Algorithm:
● Includealltheheaderfileswhichareusedintheprogram.Anddeclareall
theuserdefinedfunctions.
● Definea'Node'structurewithtwomembersdataandnext.
● DefinetwoNodepointers'front'and'rear'andsetbothtoNULL.
● ImplementthemainmethodbydisplayingMenuoflistofoperationsandmake
suitable function calls in the main method to perform
userselectedoperation.
Enqueue:
● CreateanewNodewithgivenvalue and set'newNode →next'to
NULL.CheckwhetherqueueisEmpty(rear==NULL).
● IfitisEmpty then,setfront=newNodeandrear=newNode.
● If it is Not Empty then, set rear → next = newNode and rear =
newNode.Dequeue:
● CheckwhetherqueueisEmpty(front==NULL).
● IfitisEmpty,thendisplay"QueueisEmpty!!!Deletionisnotpossib
le!!!"and terminatefromthefunction
● IfitisNot Emptythen,defineaNodepointer'temp'andsetitto'front'.
● Thenset'front=front→next'anddelete'temp'(free(temp)).Display():
● Checkwhether queueisEmpty(front==NULL).
● IfitisEmptythen,display'QueueisEmpty!!!'andterminatethefunction.
● IfitisNotEmptythen,defineaNodepointer'temp'andinitializewithfront.
● Display'temp → data--
->'andmoveittothenextnode.Repeatthesameuntil'temp'reachesto'rear'(temp→
next!= NULL).
● Finally!Display'temp→data--->NULL'.
Program:
#include<stdio.h>#in
clude<conio.h>structq
ueue
{
intdata;
structqueue*next;
};
typedefstructqueuenode;
node *front=NULL,*rear=NULL;main()
{
clrscr();int
ch;
voidinsert();voidd
elet();void
display();while(1)
{
printf("\nQUEUEUSINGLINKEDLIST");
printf("\n1Insert
\n2.Delete\n3.Display\n4.Exit");printf("\nEnterthechoice");
scanf("%d",&ch);swit
ch(ch)
{
case1:
insert();bre
ak;case2:
delet();bre
ak;case3:
display();bre
ak;case 4:
exit(0);
}
}
return0;
}
voidinsert()
{
node
*nn,*temp;nn=(node*)malloc(sizeof(
node));printf("\nEnterData:");scanf("
%d",&nn->data);
nn
->next=NULL;if(fron
t==NULL)
{
front=nn;
rear=nn;
}
else
{
rear
->next=nn;rear=rea
r->next;
}
}
voiddelet()
{
node
*temp;if(front==NU
LL)
printf("\nQUEUEISEMPTY");else
{
temp=front;
printf("\nDeleteddatais%d",temp
->data);front=front->next;
temp
->next=NULL;free(temp)
;
}
}
voiddisplay()
{
node
*temp;temp=front;while
(temp!=NULL)
{
printf("%d->",temp
->data);temp=temp->next;
}
}
Output:

Result:
Thus the program for implementation of queue using linked list is written
andexecutedsuccessfully.
9. APPLICATIONSOFLIST,STACKANDQUEUEADTs
Ex.No:9A
POLYNOMIALMANIPULATION
Date:

Aim:
TowriteaprograminCtoimplementpolynomialmanipulation.

Algorithm:
1. Starttheprogram

2. Createthepolynomial

3. Getthecoefficientvalues

4. Displaythepolynomial values

5. Stoptheprogram

Program:
#include<stdio.h>#in
clude<conio.h>#inclu
de<stdlib.h>#definep
ositive1
#definenegative-1typedefstruct node
{
floatcoeff;intexp;stru
ctnode*next;
}poly;
voidreadnode(poly*);voidviewpoly(poly*);poly*getnode();poly*crea
tepoly();
poly*copynode(poly*,int);poly*insertnode(poly*,poly*);poly*
polyadd(poly*p1,poly*p2);voidmain()
{
int ch;charc;
poly*poly1=NULL,*poly2=NULL,*res=NULL;clrscr();
printf("\n Menu\n9.Clear \n1.Create first polynomial\n2.Create
secondpolynomial\n3.View Both Polynomials\n4.Polynomial
addition\n0.Exit");do
{
printf("\nEnteryourchoice\t");fflush(stdin);scanf("%d",&ch);switch(c
h)
{
case1:poly1=createpoly();
break;case2:poly2=createpoly
(); break;case 3:
printf("\n The first polynomial is \n");
viewpoly(poly1);printf("\nThesecondpolynomialis\n");viewpol
y(poly2);break;case4:
printf("TheresultantPolynomialafteraddition\n");res=polyadd(poly1,poly2);viewpoly(r
es);break;
case0:exit(0);case9:

clrscr();
printf("\n Menu\n9.Clear \n1.Create first polynomial\n2.Create
secondpolynomial\n3.ViewBothPolynomials\n4.Polynomialaddition\n0.Exit\n");brea
k;
}
printf("DoYouWanttocontinueornot(y/n)\n");scanf("%s",&c);
}while((c=='y')||(c=='Y'));getch();
}
poly*createpoly()
{
poly*p,*head=NULL;do
{
p=getnode();readnode(p);head=insertnode(head,p);
}while(p->exp!=0);returnhead;
}

poly*getnode()
{
return(poly*)malloc(sizeof(poly));
}

voidreadnode(poly*newnode)
{
floatcoeff;intexp;
printf("EntertheCoefficient\n");scanf("%f",&coeff);printf("Entertheexponent\n");scanf("%d",&exp);
newnode->coeff=coeff;newnode->exp=exp;newnode->next=NULL;
}

poly*insertnode(poly*head,poly*p)
{
if(p->coeff==0.0f)returnhead;if(head==NULL)returnp;elseif(p
->exp>head->exp)
{
p- >next=head;returnp;
}
elseif(p->exp<head->exp)
head->next=insertnode(head->next,p);
else if((head->coeff=head->coeff+p->coeff)==0.0f) return head
->next;returnhead;
}
voidviewpoly(poly*ply)
{
if(ply==NULL) printf("NULL\n");while(ply!=NULL)
{
printf("%2fX^%d",ply->coeff,ply->exp);printf("%s",(ply-
>next==NULL)?"=0\n":"+");ply=ply->next;
}
}
poly*polyadd(poly*poly1,poly*poly2)
{
poly*head=NULL;while(poly1!=NULL)
{
head=insertnode(head,copynode(poly1,positive));poly1=poly1->next;
}
while(poly2!=NULL)
{
head=insertnode(head,copynode(poly2,positive));poly2=poly2->next;
}
returnhead;
}
poly*polysub(poly*poly1,poly*poly2)
{
poly*head=NULL;while(poly1!=NULL)
{
head=insertnode(head,copynode(poly1,negative));
}
while(poly2!=NULL)
{
head=insertnode(head,copynode(poly2,negative));poly2=poly2->next;
}
returnhead;
}
poly*copynode(poly*p,intsign)
{
poly*newnode; newnode=getnode();
newnode->coeff=sign*p->coeff;newnode->exp=p->exp;newnode
->next=NULL;returnnewnode;
}
OUTPUT:
Result:
Thustheprogramforimplementationofpolynomialmanipulation
iswrittenandexecutedsuccessfully.
Ex.No:9B
CONVERSIONOFINFIXTOPOSTFIX
Date:

Aim:
WriteaprogramtoconvertInfixexpressiontoPostfixexpression
usingstackdatastructure.

Algorithm:
1. Scanthe InfixExpressionfromlefttoright.
2. If the scanned character is an operand, append it with final Infix to
Postfixstring.
3. Else,
3.1 If the precedence order of the scanned(incoming) operator is
greaterthan the precedence order of the operator in the stack (or the
stack isemptyorthe stackcontainsa ‘(‘or‘[‘or‘{‘),pushitonstack.
3.2 Else, Pop all the operators from the stack which are greater than
orequaltoinprecedencethanthatofthescannedoperator.Afterdoingthat
Push the scanned operator to the stack. (If you encounterparenthesis
while popping then stop there and push the scannedoperatorinthestack.)
4. Ifthescannedcharacterisan‘(‘or‘[‘or‘{‘,pushittothestack.
5. Ifthescannedcharacterisan‘)’or‘]’or‘}’,popthestackandandoutputituntil a ‘(‘ or
‘[‘ or ‘{‘ respectively is encountered, and discard both theparenthesis.
6. Repeatsteps2-6untilinfixexpressionisscanned.
7. Printtheoutput
8. Popandoutputfromthestackuntilitisnotempty.
Program:
#include<stdio.h>#inclu
de<conio.h>#include<all
oc.h>char
inf[40],post[40];inttop=
0,st[20];
voidpostfix();voidp
ush(int);charpop();
voidmain(void)
{
clrscr();
printf("\nenterinfixexpression\t");scan
f("%s",&inf);
postfix();get
ch();
}
voidpostfix()
{
inti,j=0;for(i=0;inf[i]!='\0';i++)
{
switch(inf[i])
{
case'+':while(st[top]
>=1)post[j++]=pop();
push(1);
break;case'-':
while(st[top]>=2)pos
t[j++]=pop();push(2);
break;
case'*':while(st[top]>
=3)post[j++]=pop();p
ush(3);
break;case'/':
while(st[top]>=4)pos
t[j++]=pop();push(4);
break;case'^':
while(st[top]>=5)pos
t[j++]=pop();push(5);
break;case'(':
push(0);bre
ak;case ')':
while(st[top]!=0)pos
t[j++]=pop();top--;
break;defa
ult:
post[j++]=inf[i];
}
}
while(top>0)post[j+
+]=pop();
printf("postfixis=\n\t%s",post);
}
voidpush(intele)
{
top++;
st[top]=ele;
}
charpop()
{
intel;chare;el
=st[top];top-
-;switch(el)
{
case
1:e='+';
break;cas
e 2:e='-';
break;cas
e
3:e='*';bre
ak;case
4:e='/';bre
ak;case
5:e='^';bre
ak;
}
return(e);
}
Output:

Result:
Thustheprogramconversionofinfixtopostfixexpressionis
writtenandexecutedsuccessfully.
Ex.No:9C
CIRCULARQUEUE
Date:

Aim:
Toimplementacircular queuedatastructureusinganarray,wefirstperform
thefollowingstepsbefore weimplementactualoperations.

Algorithm:
1. Includealltheheaderfileswhichareusedintheprogramanddefineaconstant'SI
ZE'withspecificvalue.
2. Declarealluserdefinedfunctionsusedincircularqueuei
mplementation.
3. CreateaonedimensionalarraywithabovedefinedSIZE(intcQueue[SI
ZE])
4. Define two integer variables 'front' and 'rear' and initialize both with '-1'.
5. Implementmainmethodbydisplayingmenuofoperationslistandmakesuitablefu
nctioncallstoperformoperationselectedbytheuser oncircularqueue.

Program:
#include<stdio.h>#in
clude<conio.h>#inclu
de<stdlib.h>#include
<alloc.h>intqsize=5;
int
isempty();intisfu
ll();
void
produce(int);void
consume();intsize();
intqueue[5],front=-1,rear=-
1;voidmain()
{
int
status,item,ch,c;clrscr()
;
printf("producerconsumer\nprocessstarted\n1.producer\n2.consumer\n3.exit");do
{
printf("enteryourchoice\n");scan
f("%d",&ch);
switch(ch)
{
case1:
do{status=size();if(s
tatus==qsize)
{
printf("\nbucketfilled...waituntillconsumption");brea
k;
}
else
{
printf("\entertheitem\n");sca
nf("%d",&item);produce(item);
}
printf("doyouwanttocontinueproduction(1/0)t");scanf(
"%d",&c);
}
while(c==1);bre
ak;
case2:
do
{
status=size();if(
status==0)
{
printf("\nbucketempty...waituntillproduction");break;
}
else
{
consume();
printf("doyouwanttocontinueproduction(1/0)\t");scanf
("%d",&c);
}
}
while(c==1);bre
ak;
case
3:exit(0);
}
}
while(1);
}
voidproduce(intval)
{
if(isempty())
front=rear=0;else
if(isfull())return;
elserear=(rear+1)%qsize;qu
eue[rear]=val;
}
intsize()
{
int
count=1,f;if(ise
mpty())return0;
for(f=front;f!=rear;f=(f+1)%qsize)count++;
returncount;
}
voidconsume()
{
if(isempty())ret
urn;
else
printf("\nItemNo.%disconsumedfromthebucket\n",queue[front]);if(front==rea
r)
front=rear=-
1;else
front=(front+1)%qsize;
}
intisempty()
{
if((front==-1)&&(rear==-
1))return1;
elsereturn0;
}
intisfull()
{
if((rear+1)%qsize==front)return1;
elsereturn0;
}
Output:

Result:
Thustheprogramforproducer consumer
problemusingpriorityqueueiswrittenandexecutedsuccessfully.
Ex.No:10
IMPLEMENTATIONOFBINARYTREESANDOPERATIONSOFBINARYTR
Date: EES

Aim:
Writeaprogramtoimplementthebinarytreedatastructure.

Algorithm:
1. Starttheprogram

2. Createatree

3. PerformtheInsertion,DeletionandSearchoperation

4. DisplayPreorder,Postorder,Inordertraversaldata

5. Stoptheprogram

Program:

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

structbin_tree{intd
ata;
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;retur
n;
}

if(val<(*tree)->data)
{
insert(&(*tree)->left,val);
}
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;
}

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

voidmain()
{
node
*root;node*tm
p;
//inti;

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

/* Printing nodes of tree


*/printf("PreOrderDisplay\n");pr
int_preorder(root);

printf("InOrderDisplay\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("DataNotfound intree.\n");
}

/*Deletingallnodesoftree*/deltre
e(root);

Output:
PreOrderDisplay9
4
2
6
15
12
17
In Order Display2
4
6
9
12
15
17
PostOrderDisplay2
6
4
12
17
15
9
Searchednode=4

Result:
Thustheprogramforimplementation
ofbinarytreetraversaliswrittenandexecutedsuccessfully.
Ex.No:11
IMPLEMENTATIONOFBINARYSEARCHTREE
Date:

Aim:
Writeaprogramtoimplementbinarysearchtree.

Algorithm:
Binary_Search(A[],U_bound,VAL)1:setBEG=
0,END =U_bound, POS= -12:Repeatwhile
(BEG<=END)
3 :setMID =(BEG+END)/2
4 :ifA[MID]=VALthenPOS=
MID
printVAL“isavailableat“,POSGoToStep6Endif
ifA[MID]>VALthensetEND=MID– 1Else
setBEG=MID+ 1
End if End
while5:ifPOS=-1then
printVAL“isnotpresent“Endif6:EXIT

Program:#include<stdio.h>
#include<alloc.h>#include
<stdlib.h>include<conio.h>t
ypedefstructnode
{
intdata;
structnode*left,*right;
}tree;
tree
*getnode();voiddisplay
menu();
voidreadnode(tree*);
void
releasenode(tree*head);tree*cre
atetree();
tree*insertnode(tree*btree,tree*temp);tree
*deletenode(int digit,tree *btree);tree
*searchnode(tree *btree,int key);void
view(tree*btree,intlevel);
void findmin(tree
*btree);void findmax(tree
*btree);voidmain()
{
intchoice,key;
tree
*btree=NULL,*temp;clrscr();
displaymenu();whi
le(1)
{
printf("\nenteryourchoice:");scanf
("%d",&choice);switch(choice)
{
case0:
displaymenu();bre
ak;
case1:
btree=NULL;
printf("\ncreateanewbinarytree");btree
=createtree();
break;cas
e2:
printf("\ninsertthenodeinthetree");temp=
getnode();
readnode(temp);btree=insertnod
e(btree,temp);break;
case3:
if(btree==NULL)
printf("\nbinarytreeisempty");else
{
printf("\n enter the elements for deleting the
node:");scanf("%d",&key);
btree=deletenode(key,btree);
}
break;cas
e4:
if(btree==NULL)
printf("\nbinarytreeisempty:");else
{
printf("\nentersearchingelements");scan
f("%d",&key);temp=searchnode(btree,key)
;if(temp==NULL)
printf("\nsearchelements%disnotfound",key);else
printf("\nsearchelements%dis found",temp->data);
}
break;cas
e5:
if(btree!=NULL)
{
printf("\nbinarytreeis\t");vie
w(btree,1);
}
else
printf("\nbinarytreeisempty");brea
k;
case6:
findmin(btree);bre
ak;
case7:
findmax(btree);bre
ak;
default:
printf("\nendofprogram");relea
senode(btree);
exit(0);
}
}
}
voiddisplaymenu()
{
printf("\nbasicoperationinbinarysearchtree");printf
("\n0.show menu");
printf("\n1.create
tree");printf("\n2.insertnode");pr
intf("\n3.delete
node");printf("\n4.search
node");printf("\n5.view
tree");printf("\n6.find
minimum");printf("\n6.find
maximum");printf("\n8.exit");
}
tree*getnode()
{
intsize;
tree
*newnode;size=sizeof(tree);newno
de=((tree*)malloc(size));returnnew
node;
}
voidreadnode(tree*newnode)
{
printf("\n enter the
data:");scanf("%d",&newnode
->data);newnode
->left=NULL;newnode
->right=NULL;
}
voidreleasenode(tree*head)
{
free(head);
}
tree*createtree()
{
charch;
tree *btree=NULL,*temp;do
{
temp=getnode();readnode(temp);
btree=insertnode(btree,temp);ffl
ush(stdin);
printf("\ndoyouwishtoadddatainthetree?(y/n):");scanf("
%c",&ch);
}
while((ch=='y')||(ch=='Y'));retur
nbtree;
}
tree*insertnode(tree*btree,tree*temp)
{
if(btree==NULL)retu
rntemp;
elseif(temp->data<btree->data)
btree->left=insertnode(btree
->left,temp);elseif(temp->data>btree->data)
btree->right=insertnode(btree
->right,temp);elseif(temp->data==btree->data)
{
printf("\ndataalreadyexits");retu
rnbtree;
}
returnbtree;
}
tree*deletenode(intkey,tree*btree)
{
tree
*p,*fop,*suc,*fosuc;p=btree;
fop=NULL;
while((p!=NULL)&&(p->data!=key))
{
fop=p;
p=((key<p->data)?p->left:p->right);
}if(p==NULL)
{
printf("\nelementsnotfound");retur
nbtree;
}
if(p->left!=NULL&&p->right!=NULL)
{
for(fosuc=p,suc=p->right;suc->left!=NULL;suc=suc
->left)fosuc=suc;
if(suc->right==NULL)
{
if(fosuc->right==suc)fosuc
->right=NULL;else if(fosuc
->left==suc)fosuc
->left=NULL;
}
elseif(suc->right==NULL)
{
if(fosuc->right==suc)fosuc
->right=suc->right;else
if(fosuc->left==suc)fosuc
->left=suc->right;
}
suc->left=p->left;suc
->right=p
->right;if(fop==NULL)r
eturnsuc;
if(fop->left==p)fop
->left=suc;
else if(fop->right==p)fop
->right=suc;returnbtree;
}
elseif((p->left==NULL&&p->right==NULL)||(p->left==NULL&&p-
>right==NULL))
{
if(fop==NULL)
returnNULL;
else if(fop->right==p)fop
->right=NULL;else if(fop
->left==p)fop->left=NULL;
}
elseif((p->left!=NULL&&p->right==NULL)||(p->left==NULL&&p-
>right!=NULL))
{
if(fop==NULL)
return((p->right!=NULL)?p->right:p
->left);elseif(fop->right==p)
fop->right=((p->right!=NULL)?p->right:p
->left);elseif(fop->left==p)
fop->left=((p->right!=NULL)?p->right:p->left);
}
releasenode(p);ret
urnbtree;
}
tree*searchnode(tree*btree,intkey)
{
if(btree==NULL)retu
rnNULL;
elseif(key<btree
->data)return(searchnode(btree
->left,key));elseif(key>btree->data)
return(searchnode(btree
->right,key));elseif(key==btree->data)
return(btree);
}
voidview(tree*btree,intlevel)
{
intk;if(btree==NULL)
return;
view(btree
->right,level+1);printf("\n");fo
r(k=0;k<level;k++)printf("");pri
ntf("%d",btree
->data);view(btree
->left,level+1);
}
voidfindmin(tree*btree)
{
if(btree==NULL)
printf("\n binary tree is
empty");elseif(btree
->left==NULL)printf("\n
MIN=%d",btree->data);else
findmin(btree->left);
}
voidfindmax(tree*btree)
{
if(btree==NULL)
printf("\n binary tree is
empty");elseif(btree
->right==NULL)printf("\n
MAX=%d",btree->data);else
findmax(btree->right);
}
OUTPUT:
Result:
Thustheprogramforimplementationofbinarysearchtreeiswrittenandexecutedsu
ccessfully.
12. IMPLEMENTATIONOFSEARCHINGTECHNIQUES
Ex.No:12A
LINEARSEARCH
Date:

Aim:
AimistowriteaprograminCtoimplementthelinearsearch.

Algorithm:
Linear_Search (A[ ], N, val , pos
)1:Setpos =-1andk= 0
2:Repeatwhilek<NBegin3:ifA[k]
=val
Setpos=kprintposGoto
step5Endwhile
4:print “Valueisnotpresent”5:Exit

Program:
#include<stdio.h>int
main()
{
intarray[100],search,c,n;
printf("Enterthenumber
ofelementsinarray\n");scanf("%d",&n);
printf("Enter %d
integer(s)\n",n);for(c=0;c<n;c++)scanf("
%d",&array[c]);printf("Enteranumbertos
earch\n");scanf("%d",&search);for(c=0;c
<n;c++)
{
if(array[c]==search)
{
printf("%d is present at location
%d\n",search,c+1);break;
}
}
if(c==n)
printf("%d isn't present in the
array.\n",search);return0;
}
Output:

Result:
Thustheprogramfor implementationoflinearsearchiswrittenand executedsuccessfully.
Ex.No:12B
BINARYSEARCH
Date:

Aim:
TowriteaprograminCtoimplementbinarysearch.

Algorithm:
Binary_Search(A[ ], U_bound,VAL)1 : set
BEG = 0 , END = U_bound , POS = -12:Repeatwhile
(BEG<=END)
3 :setMID =(BEG+END)/2
4 :ifA[MID]=VALthenPOS=M
ID
printVAL“isavailableat“,POSGoToStep6Endif
ifA[MID]>VALthensetEND=MID–1Else
setBEG =MID +1
EndifEndwhile
5 :ifPOS =-1then
print VAL “ is not present “ End
if6:EXIT

Program:#include<st
dio.h>#include<conio.
h>intmain()
{
intc,first,last,middle,n,search,array[100];printf(
"Enter number of elements\n");scanf("%d",&n);
printf("Enter%dintegers\n", n);for
(c = 0; c < n;
c++)scanf("%d",&array[c]);printf("E
nter value to
find\n");scanf("%d",&search);
first= 0;last
=n-1;
middle =
(first+last)/2;while(first<=
last){if(array[middle]<searc
h)first= middle + 1;
elseif
(array[middle]==search)
{
printf("%d found at location %d.\n", search,
middle+1);break;
}
else
last=middle-1;
middle=(first+last)/2;}if(fir
st> last)
printf("Not found!%d isn'tpresentinthelist.\n",search);return0;
getch();
}
Output:

Result:
Thustheprogramforimplementationbinarysearchiswrittenandexecutedsuccessf
ully.
13. IMPLEMENTATIONOFSORTINGTECHNIQUES.
Ex.No:13A
INSERTIONSORT
Date:

Aim:
WriteaprogramtoimplementsInsertionsortusing Cprogram.

Algorithm:
Step1:start
Step2:fori←1tolength(A)Step3:j←i
Step4:whilej>0andA[j-
1]>A[j]Step5:swapA[j]andA[j-1]
Step 6:j←j-1Step 7:end whileStep 8:endforStep9:stop

Program:
#include<stdio.h>int
main()
{
intdata[100],n,temp,i,j;
printf("Enter number of terms(should be less than
100):");scanf("%d",&n);
printf("Enterelements:");for(i
=0;i<n;i++)
{
scanf("%d",&data[i]);
}
for(i=1;i<n;i++)
{
temp=data[i];j=i-
1;
while(temp<data[j]&&j>=0)
{
data[j+1]=data[j];
--j;
}
data[j+1]=temp;
}
printf("Inascendingorder:");for(i
=0;i<n;i++)printf("%d\t",data[i]);
return0;
}
OUTPUT:

Result:
Thustheprogramforimplementationofinsertionsortiswrittenandexecutedsuccessfully.
Ex.No:13B
MERGESORT
Date:

Aim:
WriteaprogramtoimplementsMergesortusingCprogram.

Algorithm:
1. Dividethedatatobesortedinhalfandputhalfoneachoftwotapes.
2. Mergeindividualpairsofrecordsfromthetwotapes;writetwo-
recordchunksalternatelytoeachofthetwooutputtapes.
3. Mergethetwo-recordchunksfromthetwooutputtapes intofour-
recordchunks;writethesealternatelytotheoriginaltwoinputtapes.
4. Mergethefour-recordchunksintoeight-
recordchunks;writethesealternatelytotheoriginaltwooutputtapes.
5. Repeatuntilyouhave onechunkcontainingallthedata,sorted---
thatis,forlogn passes,wheren isthe numberofrecords.
6. Conceptually,mergesort worksasfollows:
7. Dividetheunsorted listintotwosublistsofabouthalfthesize.
8. Divideeachofthetwosublistsrecursivelyuntilwehavelistsizesoflength1,inwhichca
se thelistitselfis returned.
9. Mergethetwosublistsbackintoonesortedlist.

Program:
#include
<stdio.h>#definemax
10
inta[11]={10,14,19,26,27,31, 33,35, 42,44,0};
intb[10];

voidmerging(int low,intmid,inthigh)
{
intl1,l2,i;
for(l1=low,l2=mid+1,i=low;l1<=mid&&l2<=high;i++)
{
if(a[l1]<=a[l2])
b[i] = a[l1++];else
b[i]=a[l2++];
}

while(l1<=mid)b[i++]=a[l
1++];

while(l2 <=
high)b[i++]=a[l2++];

for(i=low;i<=high;i++)a[i]=b[i]
;
}
voidsort(intlow,inthigh)
{
intmid;

if(low<high)
{
mid =(low
+high)/2;sort(low,mid);sort(
mid+1,high);merging(low,mi
d,high);
}
else
{
return;
}
}

intmain()
{
inti;
printf("List before
sorting\n");for(i= 0;i<=max;i++)
printf("%d ",

a[i]);sort(0,max);

printf("\nListaftersorting\n");

for(i=0;i<=max;i++)printf("%d
",a[i]);
}

Output:
Listbeforesorting
101419262731333542440
Listaftersorting
010141926273133354244

Result:
Thustheprogramforimplementationofmergesortiswrittenandexecutedsuccessful
ly.
Ex.No:13C
QUICKSORT
Date:

Aim:
WriteaprogramtoimplementsQuicksortusingCprogram.

Algorithm:
1. Pickanelement,calledapivot,fromthearray.
2. Partitioning: reorder the array so that all elements with values less than
thepivot come before the pivot, while all elements with values greater than
thepivot come after it (equal values can go either way). After this partitioning,
thepivot isin itsfinalposition.Thisiscalled thepartitionoperation.
3. Recursivelyapplytheabovestepstothesub-
arrayofelementswithsmallervaluesand separatelytothe sub-
arrayofelementswithgreatervalues.
4. Firstly,weinitiatetwopointers,loandhi,totheleftmostandrightmostelements
ofthearray.
5. Then, we call the partition function, which rearranges the array such that
allthesmallerelementsarelefttothepivotelementand
allthelargerelementsFirstly, we initiate two pointers, lo and hi, to the leftmost
and rightmostelementsofthearray.
6. Then, we call the partition function, which rearranges the array such that
allthe smaller elements are left to the pivot element and all the larger
elementsare righttothe pivotelement.
7. ItreturnsthefinalpivotindexPIndexintherange[lo, hi].
8. RecursivelycallthequicksortfortheleftsubarrayofPindexandtherightsubarray
ofthePindex.
9. ofPindexandtherightsubarrayofthePindex.
10. Exit.

Program:
#include<stdio.h>
void quicksort(int
number[25],intfirst,intlast){
inti,j,pivot,temp;if(fir
st<last){
pivot=first;i=f
irst;j=last;whi
le(i<j){
while(number[i]<=number[pivot]&&i<last)i++;
while(number[j]>number[pivot])j--;
if(i<j){temp=number[i];nu
mber[i]=number[j];numbe
r[j]=temp;
}
}
temp=number[pivot];number[p
ivot]=number[j];number[j]=te
mp;quicksort(number,first,j-
1);quicksort(number,j+1,last);
}
}
int main(){
inti,count,number[25];
printf("Howmanyelementsareugoingtoenter?:");scanf("%
d",&count);
printf("Enter%delements:",count);for(i=0;
i<count;i++)scanf("%d",&number[i]);quic
ksort(number,0,count-1);printf("Order
of Sorted elements:
");for(i=0;i<count;i++)
printf("
%d",number[i]);return0;
}

Output:
Howmanyelementsareugoingtoenter?:10Orderof
Sortedelements:012 3345789
OrderofSortedelements:0123345789

Result:
Thustheprogramforimplementationofquicksortiswrittenandexecutedsuccessfull
y.
14.IMPLEMENTATIONOFHASHING-ANYTWOCOLLISIONTECHNIQUES.
Ex.No:14A
LINEARPROBING
Date:

Aim:
TowriteaprograminCtoimplementtheHashing-Linear Probing.

Algorithm:
Algorithmtoinsertavalueinlinearprobing:

Hashtableisanarrayofsize=TABLE_SIZE1:Readth
e valuetobeinserted,key
2:leti=0
3:hkey= key%TABLE_SIZE
4:computethe indexatwhichthekeyhastobeinsertedinhashtableindex=
(hkey+i)%TABLE_SIZE
5: if there is no element at that index theninsert the value at index and
STOP6:Ifthereisalreadyanelementatthatindex
step4.1:i=i+1
7:if i<TABLE_SIZEthengotostep4

Algorithmtosearchavalueinlinearprobing:
Hashtableisanarrayofsize=TABLE_SIZE1:Readth
e value tobe searched,key
2:leti=0
3:hkey= key%TABLE_SIZE
4:computetheindexatwhichthekeycanbefoundindex=(hk
ey+i)%TABLE_SIZE
5: if the element at that index is same as the search value then print element found andSTOP
6:else
step4.1:i=i+1
7:if i<TABLE_SIZEthengotostep4

Program:#include<st
dio.h>#include<conio.
h>#include<stdlib.h>
#define MAX
10voidmain()
{
int
a[MAX],num,key,i;charans;
intcreate(int);
voidlinearprobing(int[],int,int);
void
display(int[]);clrscr();
printf("\ncollisionhandlingbylinearprobing\n\n");for(i=
0;i<MAX;i++)
a[i]=-1;
do
{
printf("\nEnternumber:");scanf("%d",&n
um);key=create(num);linearprobing(a,
key,num);printf("\nwish to
continue?(y/n):");ans=getch();
}
while(ans=='y');disp
lay(a);getch();
}
intcreate(intnum)
{
intkey;key=num%
10;returnkey;
}
voidlinearprobing(inta[MAX],intkey,intnum)
{
intflag,i,count=0;voiddi
splay(inta[]);flag=0;
if(a[key]==-
1)a[key]=num;els
e
{
i=0;while(i<MAX)
{
if(a[i]!=-
1)count++;i+
+;
}
if(count==MAX)
{
printf("hashtableisfull");displ
ay(a);
getch();
exit(1);
}
for(i=key+1;i<MAX;i++)if(a[
i]==-1)
{
a[i]=num;flag
=1;break;
}
for(i=0;i<key&&flag==0;i++)if(a[
i]==-1)
{
a[i]=num;flag
=1;break;
}
}
}
voiddisplay(int a[MAX])
{
inti;
printf("\n Hash table
is:");for(i=0;i<MAX;i++)printf
("\n%d\t\t%d",i,a[i]);
}
Output:-

Result:
Thus the program for implementation of Hashing-Linear Probing is
writtenandexecutedsuccessfully.
Ex.No:14B
HASHINGWITHSEPARATECHAINING
Date:

Aim:
AimistowriteaprograminCforimplementationofHashing-Separate
Chaining.

Algorithm:
1:Readthevaluetobeinserted
2:createanewnodeusingmallocfunction
3:Assignthevaluereadtothedatafieldofnewnode(newnode ->data=value)4:computeth
eindex
index=value%TABLE_SIZE5:
ifhead[index]isNULLthen
5.1:attachthenewnodeasfirstnode
6:else
6.1:attachthenewnodeaslastnode

Program:#include
<stdio.h>#include<std
lib.h>
#defineTABLE_SIZE3struct
node
{
intdata;
structnode*next;
};
struct node
*head[TABLE_SIZE]={NULL},*c,*p;voidinsert(inti,intva
l)
{
structnode*newnode=(structnode*)malloc(sizeof(structnode));newno
de->data=val;
newnode->next =
NULL;if(head[i]==NULL)head
[i]= newnode;
else
{
c=head[i];while(c
->next!=NULL)c=c->next;
c->next=newnode;
}
}
voiddisplay(inti)
{
if(head[i]==NULL)
{
printf("No Hash
Entry");return;
}
else
{
f
o
} r
} (
main() c
{ =
h
e
a
d
[
i]
;
c!
=
N
U
L
L;
c
=
c
-
>
n
e
x
t)
p
r
i
n
t
f
(
" -
% >
d d
- a
> t
", a)
c ;
int
opt,val,i;while(
1)
{
printf("\nPress1.Insert\t2.Display\t3.Exit\n");scanf("%d",&opt);
switch(opt)
{
case1:
printf("\nenteravaluetoinsertintohashtable\n");scanf(
"%d",&val);
i=val%TABLE_SIZE;
insert(i,val);br
eak;
case2:for(i=0;i<TABLE_SIZE;i++)
{
printf("\nentriesat
index%d\n",i);display(i);
}
break;c
ase3:exit(0);
}
}
}
Output:

Result:
Thus the program for implementation of Hashing-Separate Chaining
iswrittenandexecutedsuccessfully.

You might also like