You are on page 1of 91

http://vustudents.ning.

com

http://vustudents.ning.com
INTRODUCTION TO C
C has emerged as the most widely used programming language
for software development. Its features allow the development of well-structured
programs. Most computers directly support its data types and control structures,
resulting in the construction of efficient programs. It is independent of any
particular machine architecture or operating system, which makes it easy to write portable
programs. It is this contribution of rich control structure and data types, portability and
conciseness that has contributed to the popularity of C.
History of C
C programming language is basically developed for !I"
#perating $ystem. !I" was developed in %&'& at bell telephone laboratories. It was
entirely written on ()( * assembly language. +fter !I" has been implemented
,en -hompson implemented a compiler for a new language called . used for
transporting !I" onto other machines. . was heavily influenced by .C(/ 0.asic
Cambridge (rogramming /anguage1 written for writing system software. . was latter modified by
)ennis 2itchie who was also working at bell /abs. 3e named the successor C. ni4
was later rewritten in C by )ennis 2itchie, -hompson and others by %&*5.
C Program Structure
+ basicfact about computer programming is that all programs can be written
using a combination of only three control structures: $e6uential,
$elective and repetitive. -he se6uential structure consists of a se6uence of program statements
that are e4ecuted one after another in order, the selective structure consists of a test
for a condition followed by alternative paths that the program can follow, and the
repetitive structure consists of program statements that are repeatedly e4ecuted while some
condition holds.
-he se6uential structure can be pictorially represented as follows
Entry
Statement 1
Statement 2
Statement 3 Exit
+ll C programs are made up of one or more functions, each performing
a particular task.
7very program has a special function named main. It is special because
the e4ecution of any program starts at the beginning of its main function. %
+ typical C program has following sections
%. (reprocessor )irectives
8. 9lobal :ariable )eclarations
5. ;unctions
In a C program, preprocessor directive, if present, should come first
followed by global variable definition if any.
aria!"e Dec"aration in C
%. -he variable can be 5% characters long.
8. -he variable can be any of a-<, +-=, >-& and the underscor e.
5. $hould not be a keyword.
?. ;irst character must be an alphabet
@. -he variable is case sensitive
Data Ty#es
7very programming language has its own data type. -he basic data
types in C are
Int - an integer
;loat A a single precision floating point number
Char - a character in C character set
)ouble A a double precision floating point number
aria!"es
:ariables are data obBects that are manipulated in a program.
Information can be stored in a variable and recalled later. :ariables must be declared before
they can be used in a program.
Constants
+ constant is an entity whose value does not change during
program e4ecution. Constants are of five different types
%. Integer Constants
8. ;loating point Constants 5. Character Constants ?. $tring Constants 8
http://vustudents.ning.com
http://vustudents.ning.com
C O#erators
-he operators in C include
%. +rithmetic
8. +ssignment
5. 2elational
?. Increment and )ecrement
@. .it
'. /ogical or .oolean
*. Conditional e4pression
INPUT $ OUTPUT
-he important aspects of C programming language are its ability
to handle input and output 0I/#1. + program using input / output functions must include the
standard header file 0stdio.h1 in it using the directive.
Printf functions %CONIO&H' STDIO&H(
printf A sends formatted output to stdout
fprintf A sends formatted output to a stream
cprintf A sends formatted output to the te4t window on the screen
Scanf )unction
$canf - reads data from stdin
;scanf A reads data from stream
-he 97-C3+2 and (-C3+2 ;unction
*etc+ar' #utc+ar %STDIO&+(
- getchar is a macro that gets a character from stdin
- putchar is a macro outputs a char acter on stdout
T+e *ETCH an, *ETCHE )unction
- getch gets a character from console but does not echo to the screen - getche gets a character from console and echoes to the screen gets' #uts gets01 - gets a string from stdin puts01 A outputs a string to stdout 5
http://vustudents.ning.com

http://vustudents.ning.com
CONDITION-. ST-TE/ENTS
If %con,ition( Statement
Chen an if statement is encountered in a program, condition is
evaluated, if its value is true, then the following statements are e4ecuted.
-he if statement allows conditional e4ecution of a group of statements.
If0e"se Statement
$D!-+"
If condition
$tatement %E
7lse
$tatement 8E
If the condition is true then statement % is e4ecuted else statement
8 is e4ecuted 0if it e4ists1. 7lse part is optional.
.OOPS IN C
1HI.E .OOP
Chile loop provides the mechanism for looping as long as a specified
condition is met. -he while loop should be used in applications that do not re6uire the
modification of any variables at each iteration.
$D!-+"
1+i"e %con,ition(
Statements
-he statement may be a single statement or a block of statements that is
to be repeated. -he condition may be any e4pression, with true being any non-<ero
value. -he statements are e4ecuted while the condition is true. Chen the condition
becomes false, program control passes to the line after the loop code. )OR .OOP
-his is used when the statements are to be e4ecuted more than once.
-his is the most
widely used iteration construct. -he for loop supported by C is much
more powerful than its counterpart in any other programming language. ?
http://vustudents.ning.com

http://vustudents.ning.com
$D!-+"
)or %ex#12ex#22ex#3(
3
statements2
44444&
5
9enerally e4p% is an initiali<ation, e4p8 is condition checkingE
e4p5 is either an increment or decrement statement.
-he initiali<ation is usually an assignment statement that is used to set
the loop control variable. -he condition is a relational e4pression that determines
when the loop will terminate. -he increment determines how the loop control variable
change each time the loop is repeated.
1& 1rite a C #rogram to ,etermine t+e sum of o,, an, e6en
num!ers&
F includeGstdio.hH
F includeGconio.hH
main01
I
int n, i, sevenJ>, soddJ>E
int aK8@LE
clrscr01E
printf0:Mn 7nter the total number to be entered:N1E
scanf0OPdN,Qn1E
printf0OMn 7nter the valuesN1E
for0iJ>EiGnEiRR1
I
if0aK iLP8JJ>1
sevenJsevenRaK iLE
else soddJsoddRaKILE Sprintf0OMn -he $um of 7ven number is PdN,seven1E printf0OMn -he $um of #dd number is PdN,sodd1E getch01E S @
http://vustudents.ning.com
http://vustudents.ning.com
2& 1rite a C #rogram to count t+e num!er of #ositi6e' negati6e
an, 7ero num!er in t+e gi6en "ist of num!ers&
F include Gstdio.hH
F include Gconio.hH
main01
I
int n, i, nposJ>, nnegJ>, n<eroJ>E
int aK8@LE
clrscr01E
printf0:Mn 7nter the total number to be entered:N1E
scanf0OPdN,Qn1E
printf0OMn 7nter the valuesN1E
for0iJ>EiGnEiRR1
I
if0aK iLH>1
nposJnposR%E
if0aKIL G>1
nnegJnnegR%E
else
n<eroJn<eroR%E
S
printf0OMn -he number of positive value is PdN,npos1E
printf0OMn -he number of negative value is PdN,nneg1E
printf0OMn -he number of <eros is PdN,n<ero1E
getch01E
S
3& 1rite a C #rogram for tem#erature con6ersion&
FincludeGstdio.hH
FincludeGconio.hH
main01
I
int faren,cenE
clrscr01E printf0OMn 7nter the farenheit value :N1E scanf0OPdN,Qfaren1E cenJ0faren-581R@/&E printf0OMn -he e6uivalent Centigrade value is PdN,cen1E getch01E S '
http://vustudents.ning.com
http://vustudents.ning.com
8& 1rite a C #rogram to c+ec9 :+et+er t+e num!er is #rime or not&
FincludeGstdio.hH
FincludeGconio.hH
main01
I
int n, iE
clrscr01E
printf0:Mn 7nter the total number to be entered:N1E
scanf0OPdN,Qn1E
for0iJ8EiGJn/8EiRR1
I
if0nPiJ J>1
printf0OMn the given number is not primeN1E
breakE
S
if0nPi1
printf0OMn the given number is primeN1E
getch01E
S
;& 1rite a C #rogram to fin, :+et+er t+e gi6en num!er is
#a"in,rome or not&
FincludeGstdio.hH
FincludeGconio.hH
main01
I
int n, iE
int p,s,eE
clrscr01E
printf0:Mn 7nter the number :N1E
scanf0OPdN,Qn1E
eJ>E
pJnE while0pTJ>1 IsJpP%>E eJ0eU%>1RsE pJp/%>E S *
http://vustudents.ning.com

http://vustudents.ning.com
if0eJ J n1
printf0OMn the given number is palindromeN1E
else
printf0OMn the given number is not a palindromeN1E
getch01E
S
<& 1rite a C #rogram to fin, t+e sum of ,igits&
FincludeGstdio.hH
FincludeGconio.hH
main01
I
int n,6,r,sJ>E
clrscr01E
printf0OMn 7nter the noV1E
scanf0OPdN,Qn1E
while0nTJ>1
I
6Jn/%>E
rJn-6U%>E
sJsRrE
nJ6E
S
printf0OMn the sum of digits :PdN,s1E
getch01E
S
=& 1rite a #rogram to fin, :+et+er t+e gi6en num!er is #erfect or
not&
FincludeGstdio.hH
FincludeGconio.hH
main01
Iint a J >E int mE
printf0O7nter a number to check whether it is a perfect number or not
MnN1E printf0O 7nter a number MnN1E scanf0OPldN,Qn1E for 0mJ>EmGnEmRR1 W
http://vustudents.ning.com
http://vustudents.ning.com
I
if 0n P m J J > 1
a J a R mE
S
if 0a J J n1
printf0Othe given number is perfect number MnN1E
else
printf0Othe given number is not a perfect number MnN1E
getch01E
>& 1rite a #rogram to fin, :+et+er t+e gi6en num!er is -rmstrong or
not&
FincludeGstdio.hH
FincludeGconio.hH
main01
I
int s J >E
int cJ >E
int m,n,bE
printf0O7nter a number to check whether it is a perfect number or not
MnN1E printf0O 7nter a number MnN1E
scanf0OPldN,Qb1E
n J bE
while 0bH>1
I
c J b P %>E
s J s R 0cUcUc1E
b J b / %>E
S
if 0s J J n1
printf0Othe given number is armstrong number MnN1E
else
printf0Othe given number is not a armstrong number MnN1E
getch01E
S
?& 1rite a C #rogram to fin, t+e gi6en num!er using "inear searc+
met+o,&
FincludeGstdio.hH FincludeGconio.hH main01 Iint n,aK5>L,sea,flagE clrscr01E &
http://vustudents.ning.com

http://vustudents.ning.com
printf0OMn 7nter the number of terms :N1E
scanf0OPdN,Qn1E
printf0OMn 7nter the values:N1E
for0iJ>EiGnEiRR1
scanf0OPdN,aKiL1E
printf0OMn 7nter the number to be searched :N1E
scanf0OPdN,Qsea1E
for0iJ>EiGnEiRR1
I
if0aKiL J J sea1
I
flagJ%E
breakE
S
else
flagJ>E
S
if0flagJ J %1
printf0OMn -he given number Pd is present in the position number
PdN,sea,i1E
else
printf0OMn -he given number is not presentN1E
getch01E S
1@& 1rite a C #rogram to fin, t+e gi6en num!er using !inary
searc+ met+o,&
FincludeGstdio.hH
FincludeGconio.hH
main01
I
int n,aK5>L,sea,flag,4,y,tE
int low,high,midE
clrscr01E
printf0OMn 7nter the number of terms :N1E
scanf0OPdN,Qn1E
printf0OMn 7nter the values:N1E
for0iJ>EiGnEiRR1 scanf0OPdN,aKiL1E for04J>E4Gn-%E4RR1 for0yJ4R%EyGnEyRR1 Iif0aK4LHaKyL1 I %>
http://vustudents.ning.com

http://vustudents.ning.com
tJaK4LE
aK4LJaK yLE
aK yLJtE
S
S
printf0OMn -he sorted numbers are :N1E
for04J>E4GnE4RR1
printf0OPdMnN,aK4L 1E
printf0OMn 7nter the number to be searched :N1E
scanf0OPdN,Qsea1E
lowJ>E
highJnE
while0lowGJhigh1
I
midJ0lowRhigh1/8E
if0tGaKmidL 1
highJmid-%E
if0tHaKmidL 1
lowJmidR%E
if0tJ J aKmidL1
I
printf0OMn the number Pd is present in the position PdN,t,mid1E
flagJ>E
breakE
S
if0mid J J% X X midJ J n1
breakE
S
if0flag1
printf0OMn -he given number is not presentN1E
getch01E
S
11& 1rite a #rogram to #rint fi!onacci series using functions
Finclude G$-)I#.3H Finclude GC#!I#.3H void main01 Iint nE void fibo0int1E %%
http://vustudents.ning.com

http://vustudents.ning.com
clrscr01E
printf0OMtMt (2#92+M -# (2I!- -37 ;I.#!+CCI $72I7$ MnN1E
printf0OMn 7nter the number of terms to be in the series Mn O1E
scanf0OPdN,Qn1E
fibo0n1E
getch01E
S
void fibo0int num1
I
int IJ%,ct,ft,stE
ft J >E
st J %E
printf0OMt Pd Mt PdN,ft,st1E
while0IGJnum-81
I
ct J ft R stE
ft J stE
st J ctE
printf0OMtPdN,ct1E
IRRE
S
S
12& Program to #erform t+e mat rix a,,itions
Finclude Gstdio.hH
Finclude Gconio.hH
void main01
I
int aK%>LK%>L,bK%>LK%>L,cK%>LK%>L,row,col,r,co,I,B,kE
clrscr01E
printf0OMtMt Matri4 +dditionMnN1E
printf0O7nter 2ow order of Matri4 + : O1E
scanf0OPdN,Qrow1E
printf0O7nter Column order of Matri4 + : O1E
scanf0OPdN,Qcol1E
printf0O7nter 2ow order of Matri4 . : O1E
scanf0OPdN,Qr1E
printf0O7nter Column order of Matri4 . : O1E scanf0OPdN,Qco1E if 00rowTJr1 XX 0col TJ co1 1 Iprintf0OMatri4 Multiplication is impossibleMnN1E getch01E S %8
http://vustudents.ning.com

http://vustudents.ning.com
else
I
printf0O7nter ;irst Matri4 7lements : O1E
for 0IJ>EIGrowEIRR1
for 0BJ>EBGcolEBRR1
scanf0OPdN,QaKILKBL 1E
printf0O7nter $econd Matri4 7lements : O1E
for 0IJ>EIGrEIRR1
for 0BJ>EBGcoEBRR1
scanf0OPdN,QbKILKBL1E
for 0IJ>EIGrowEIRR1
for 0BJ>EBGcolEBRR1
cKILKBL J aKILKBL R bKILKBLE
printf0O-he resultant matri4 is MnN1E
for 0IJ>EIGrowEIRR1
I
for 0BJ>EBGcolEBRR1
I
printf0OPtPdN,cK ILKBL1E
S
pritnf0OMnN1E
S
S
13 & Program to #rint t+e factoria" num!er
Finclude Gstdio.hH
Finclude Gconio.hH
void main01
I
int nE
clrscr01E
printf0Oprogram to print the factorialMnN1E
printf0OMnMn 7nter the number : O1E
scanf0OPdN,Qn1E
factorial0n1E
getch01E
S
void factorial0double 41
Idouble fact J %E for0IJ%EIGJnEIRR1 Ifact J fact U IE printf0O-he factorial of a given number is PdMnN,fact1E S %5
http://vustudents.ning.com
http://vustudents.ning.com
18& Program to im#"ement t+e To:er of Hanoi
Finclude Gstdio.hH
Finclude Gconio.hH
void main01
I
void transfer0int,char,char,char 1E
int nE
clrscr01E
printf0OMtMt -#C72$ #; 3+!#I MnN1E
printf0O3ow many disks Y O1E
scanf0OPdN,Qn1E
transfer0n, % , r , c 1E
getch01E
S
void transfer0int n, char from, char to, char temp1
I
if0nH>1
I
transfer0n-%,from,temp,to1E
printf0OMove disk Pd from Pc to Pc MnN,n,from,to1E
transfer0n-%,temp,to,from1E
S
returnE
S
1;& Program to count t+e num!er of 6o:e"s' consonants'
,igits' :+ite s#ace c+aracters an,
in a "ine of text using #ointers
Ainclude Gstdio.hH
main01
I
char lineKW>LE
int vowels J >E
int cons J >E
int digits J >E int ws J >E int other J >E void scanZline0char lineKL, int Upv, int Upc, int pd, int Upw, int Upo1E printf0O7nter a line of te4t MnN1E scanf0OPK[MnL,line1E scanZline0line, Qvowels, Qcons, Qdigits, Qws, Qother1E %?
http://vustudents.ning.com

http://vustudents.ning.com
printf0OPd Pd Pd Pd PdN,vowels,cons,digits,ws,other1E
return0>1E
S
void scanZline0char lineKL, int Upv, int Upc, int Upd, int Upw,int Upo1
I
char cE
int count J >E
while00c J toupper0lineKcountL11 TJ \ M> 1
I
if 0c J J \+ X X c J J \7 X X c J J I XX c J J \# XX c J J \ 1
RR UpvE
else if 0c H J \+ QQ c G J \= 1
RR UpcE
else if 0 c H J \> QQ c G J \& 1
RR Upd E
else if 0c J J \ \ X X c J J \ M> 1
RR UpwE
else
RR UpoE
RR countE
S
returnE
S
1<& Program to im#"ement to )"oy,s Triang"e
Finclude Gstdio.hH
void main01
I
int n,i,B,4J%E
clrscr01E
printf0VMtMtMt;loyds -riangleMnV1E
printf0VMtMtMtJJJJJJJJJJJJJJJMnV1E
printf0V7nter the no of /ines:V1E
scanf0VPdV,Qn1E
for0iJ>EiGnEiRR1
I
for0BJ>EBGJiEBRR1
Iprintf0VP?dV,41E 4RRE Sprintf0VMnV1E Sgetch01E S %@
http://vustudents.ning.com

http://vustudents.ning.com
1=& Program to im#"ement to Pasca" Triang"e
Finclude Gstdio.hH
void main01
I
int iJ%,B,k,m,nE
clrscr01E
printf0VMtMtMt(ascal -riangleMnV1E
printf0VMtMtMtJJJJJJJJJJJJJJJMnV1E
printf0V7nter the no of /ines:V1E
scanf0VPdV,Qn1E
for0BJ>EBGnERRB1
I
for0kJ5@-8UBEkH>Ek--1
printf0V V1E
for0mJ>EmGJBERRm1
I
if00mJJ>1XX0BJJ>11
iJ%E
else
iJ0iU0B-mR%11/mE
printf0VP?dV,i1E
S
printf0VMnV1E
S
getch01E
S
1>& Program to im#"ement sine series
Finclude Gstdio.hH
Finclude Gmath.hH
void main01
I
float d,4,sumJ>,fact0int1E
int terms,signJ%,iE
clrscr01E
printf0VMtMtMt $ine $eries MnV1E printf0VMtMtMt JJJJJJJJJJJ MnV1E printf0VMn7nter the " value:V1E scanf0VPfV,Qd1E printf0VMn7nter the number of terms:V1E scanf0VPdV,Qterms1E 4J5.%?/%W>UdE %'
http://vustudents.ning.com

http://vustudents.ning.com
for0iJ%EiGJtermsEiRJ81
I
sumJsumRsignUpow04,i1/fact0i1E
signJ-signE
S
printf0VMn-he value of sine0P?.8f1is PW.?fV,d,sum1E
getch01E
S
float fact0int n1
I
float fJ%E
int iE
for0iJ%EiGJnERRi1
fUJiE
return0f1E
S
1?& Programs on /ani#u"ations on st rings
Finclude Gstdio.hH
void main01
I
int ch,i,B,l,m,sign,c,l%,kE
char nameKW>L,name%KW>L,name8KW>L,namerKW>L,nameffK W>L,ansJ]y]E
clrscr01E
printf0VMtMtMtManipulations on $tringsMnV1E
printf0VMtMtMtJJJJJJJJJJJJJJJJJJJJJJJJMnV1E
printf0V%.ConcatenationMnV1E
printf0V8.2everseMnV1E
printf0V5.;indMnV1E
printf0V?.2eplaceMnV1E
printf0V@./engthMnV1E
printf0VChoice:V1E
scanf0VPdV,Qch1E
switch0ch1
I
case %:
I
printf0VMtMtConcatenationMnV1E
printf0VMtMtJJJJJJJJJJJJJMnV1E printf0V7nter the first string MnV1E scanf0VPsV,name1E printf0V7nter the second string MnV1E scanf0VPsV,name%1E iJBJ>E while0nameKiLTJ]M>]1 %*
http://vustudents.ning.com

http://vustudents.ning.com
I
name8KiLJnameKiLE
iRRE
S
while0name%KBLTJ]M>]1
I
name8KiLJname%KBLE
iRRE
BRRE
S
name8KiLJ]M>]E
printf0V2esultant $tring in name8 isPsV,name81E
breakE
S
case 8:
I
printf0VMtMt2everseMnV1E
printf0VMtMtJJJJJJJMnV1E
printf0V7nter the string MnV1E
scanf0VPsV,name1E
iJBJ>E
while0nameKiLTJ]M>]1
iRRE
while0--iHJ>1
name%KBRRLJnameKiLE
name%KBLJ]M>]E
printf0VMn-he reversed $tring isPsV,name%1E
breakE
S
case 5:
I
printf0VMnMtMt;indMnV1E
printf0VMtMtJJJJMnV1E
printf0VMn7nter first string:V1E
scanf0V PK[MnLV,name1E
printf0V7nter search string:V1E
scanf0V PK[MnLV,name%1E
lJstrlen0name1E
l%Jstrlen0name%1E
for0iJ>EiGlERRi1 IcJ>E if0nameKiLJJname%KcL1 ImJiE signJ>E %W
http://vustudents.ning.com
http://vustudents.ning.com
while0name%KcLTJ]M>]QQsignTJ%1
I
if0nameKmLJJname%KcL1
I
mRRE
cRRE
S
else
signJ%E
S
if0signJJ>1
I
printf0V-he given string is presentV1E
printf0VMnIts starting position isPdV,iR%1E
e4it0%1E
kJ-%E
S
S
if0kG>1breakE
S
if0signTJ>1
printf0V-he given string is not presentV1E
breakE
S
case ?:
I
iJ>E
BJ>E
strcpy0nameff,V V1E
puts0V7nter the string:V1E
scanf0V PK[MnLV,name1E
fflush0stdin1E
puts0V7nter find stringV1E
scanf0V PK[MnLV,name%1E
fflush0stdin1E
puts0V7nter replace str ing:V1E
scanf0V PK[MnLV,namer1E
fflush0stdin1E
lJstrlen0name1E strcat0namer,V V1E while0iGl1 IBJ>E for0kJ>EkGW>ERRk1 name8KkLJ] ]E %&
http://vustudents.ning.com

http://vustudents.ning.com
while0nameKiLTJ] ]QQnameKiLTJ]M>]1
I
name8KBLJnameKiLE
RRiE
RRBE
S
name8KBLJ]M>]E
RRiE
if00strcmp0name8,name%11JJ>1
I
strcat0nameff,V V1E
strcat0nameff,namer1E
S
else
I
strcat0nameff,V V1E
strcat0nameff,name81E
S
S
puts0Vstring after replacementV1E
puts0nameff1E
breakE
S
case @:
I
iJ>E
printf0V7nter $tring:V1E
scanf0V PK[MnLV,name1E
while0nameKiLTJ]M>]1
iRRE
printf0VMn-he length of the given string isPdV,i1E
breakE
S
S
getch01E
S
8>
http://vustudents.ning.com

http://vustudents.ning.com
Data Structures
-n intro,uction to CB
)ennis 2itchie at +- Q - .ell laboratory, Murray 3ill, !ew
^ersey, developed the programming language C in %&*8. -he languages
.C(/ and . mainly influenced it. It was named as C to present it as the successor of .
language which was )esigned earlier by ,en -hompson in %&*> for the first !I" system
on the )7C()(-* Computer.
Ho: to run C #rogramB
;rom the Ms )os prompt start C by typing \tc .
%.
8. #pen a file by selecting ;ile X #pen X ;ile name from the I)7 menu. #r
press ;5 ,ey
5. 2un the program by selecting 2un X 2un, #r press
CtrlR;& ,ey
-o see the program s output select Cindow X ser screen or press
?.
+ltR;@ ,ey.
Ce may compile and run the programs from the )os command
/ine like tcc ;ilename G7nterH.
+fter the program is compiled, we may run it and view the output by
typing
;ilename G7nterH
Pro!"em so"6ing using com#uter :
-o solve a problem using a computer, the following steps are r e6uired :
+ program is developed using a high level progr amming language
0program development1
-he developed program is entered into a commuter 0(rogram editing1.
-he edited program is translated and is produced as an e4ecutable
machine code. -he 74ecutable machine code is run in the computer to carry out the
actual task 0e4ecution1.
-o implement the above steps, the programmer develops a
program and the developed program is entered and edited with the help of an editor.
!ormally the editor is
provided along with the compiler. +fter editing the program, the
compilation commands
us used for the translation process. -hen the e4ecution command
is used to run the program to get the desir ed output. 8%
http://vustudents.ning.com

http://vustudents.ning.com
Com#i"ation :
3igh-level languages allow some 7nglish Alike words and
mathematical e4pressions that facilitate the better understanding of the logic
involved in a program. 3igh-level languages are machine independent. $ince a computer
system cannot follow programs written in a high language, high language programs ar e
translated into low- level language programs and then e4ecuted.
-ranslation of a high-level language program to allow level
language program is done by software known as Compiler. #bBect code is an
intermediate code between the source code and the e4ecutable code.
.in9ing:
/inker performs the linking of libraries with the obBect code, to
make the generated obBect code into an e4ecutable machine code. -hus the obBect
code becomes an input to the linker, which produces an e4ecutable machine code.
$ometimes programs are divided into modules and these modules are compiled separately and
then linked by the linker and e4ecuted.
Chen running a program, the following files will be created
automatically.
#.^ 0#bBect file1
7"7 074ecutable file1
.ak 0.ackup file1
$C( 0$wap file1
Data Structures Definition
)ata $tructure is a speciali<ed format for storing data so that the
data s can be organi<ed in an efficient way.
C"assification
Primiti6e Non C Primiti6e
74ample: -
Integer
2eal
Character .inear Non C .inear
(ointer 74ample: - 74ample: -
/ogical /inear /ist 9raph
$tack -ree
_ueue 88
http://vustudents.ning.com

http://vustudents.ning.com
-rray
+n array is a finite collection of similar elements stored in contiguous
location. -he operations done on an array are: -
Insertion
)eletion
Changing a particular element
.in9e, .ist
-here are three types of linked lists. -hey are: -
$ingle /inked /ist
)oubly /inked /ist
$ingly Circular /inked /ist
)oubly Circular /inked /ist
Sing"e .in9e, .ist
!ode structure
Data Pointer
)ie", )ie",
-he data field contains the data elements that have to be stored in the list. -he
pointer will point the ne4t node in the list.
-he operations done on a list are: -
Insertion
)eletion
Insertion
Insertion in t+e +ea, no,e
-o insert a node in the head node, Bust change the pointer field of the
new node to point to the head node. /et the new node be \ Temp and the head node be
Head,
then the insertion is
Temp data = X; Head next = head 85
http://vustudents.ning.com

http://vustudents.ning.com
Insertion in t+e mi,,"e no,e
-o insert in the middle node we need to change two pointers. /et
the new node be \ Temp and the present node is Present and, the ne4t node to the
present node is future. -he pointers used are \ data for the data field, next
X
to the pointer field , the data to be inserted is \ then the insertion is
Temp data = X
Present next = temp
Temp next = future
Insertion in t+e "ast no,e
-o insert an element in the last position Bust change the pointer field of
the present last node to point to the new node, then set the pointer field of the new
node to NULL. /et the new node be \ Temp and the present node is Present. -he
pointers used are \data for the data field, next to the pointer field , the data to be
inserted is \X then the insertion is
Present next =Temp
Temp next =null
Temp data = X
)eletion
De"etion in t+e +ea, no,e
-o delete a node in the head node, Bust point the head node as the
second node. Head,
/et the head node be and then the deletion is
Head next = head
De"etion in t+e mi,,"e no,e
-o delete a node in the middle we need to change two pointers. /et the
node to be deleted is \Temp Present
and the node previous to the node to be deleted is
future. data
and,the ne4t node to the present node is -he pointers used are \ for
the data field, next to the pointer field , the data to be inserted is \X then the
insertion is
Present next = future
De"etion in t+e "ast no,e
-o delete an element in the last position Bust change the pointer field of
the previous node to the last tonull . /et the last node be \Temp and the previous Present. data next node is -he pointers used are \ for the data field, to the the data to be inserted is \ X pointer field , then the insertion is Previous next =NULL 8?
http://vustudents.ning.com

http://vustudents.ning.com
Sing"y Circu"ar .in9e, .ist
-he advantage of using Circular /inked /ist is the last null pointer is replaced and the
pointer field of the last node points to the first node, due to this circular
ar rangement the traversing become 6uite easier. -he insertion and deletion in the first
and middle are same as singly linked list e4cept the last node.
Insertion
Insertion in t+e "ast no,e
-o insert a node in the last position, insert the new node after the
current last node, and then change the pointer field of the new node to point to the first
node. /et the last node be last , the new node to be inserted to be ne, the first node in the list to be
first.-he pointers used are \ data for the data field, next to the pointer field, the data
to be inserted is \X
then the insertion is
Last next = ne
Ne next =first
)eletion
De"etion in t+e "ast no,e
-o delete a node in the last position, change the pointer field of the
previous node to the current last to point the first node. /et the last node
be last, the previous node to the cur rent last node to be pre, the first node
data next
in the list to be first. -he pointers used are \ for the data field,
the data to be inserted is \ X
to the pointer field , then the deletion is
Prev next = first
Stac9
+n important subclass of lists permits the insertion and deletion of an
element to occur only at one end. + linear list of this type is known as \ .
sta!"
-he insertion is referred to as \ push. -he deletion is referred to as \pop. -he two
pointers used for accessing is top Q #ottom pointer.
($3 A $toring the element into the stack.
.ottom (ointer
Check topGJ allowed si<e if yes increment the top position and
store the value in the top position.
(#( - )eleting the element from the stack. If topGJ we can not delete.
#therwise decrement the top by one and return the topR% element.
Dueue
-he information in this list is processed in the same order as it was
received, that is
first in first out order 0;I;#1 or a first A come first A served 0;C;$1
basis. -his type of fre6uently used list is known as $ueue . Ce have two pointers to access the 6ueue. -hey are %. ;ront 0used for deletion1 8@
http://vustudents.ning.com

http://vustudents.ning.com
8. 2ear 0sed for insertion1
Insertion B
if rearHn 6ueue overflow
else
increment the rear pointer and insert the value in the rear position.
De"etion B
If front J> then 6ueue underflow
7lse
Increment the front pointer and return the front-% value
Tree
+n important class of digraph, which involves for the description of
hierarchy. + directed tree is an acyclic digraph which has one node called root with in degree >, while
other nodes have in degree %. 7ver y directed tr ee must have at least
one node. +n isolated node is also called as directed tree. -he node with out degree as > is
called as leaf. -he length of the path from root to particular node level of the node. If the
ordering of the node at each level is prescribed then the tree is called as ordered tree.
Einary Tree
If a tree has at most of two children, then such tr ee is called as .inar y
tree. If the elements in the binary tree are arranged in the following order
.eft e"ement is "esser t+an t+e root
Rig+t e"ement is greater t+en t+e root
No ,u#"ication of e"ements
-hen such binary tree is called as Einary Searc+ Tree
O#erations #erforme, in a !inary tree areB
o Inserting a node
o )eleting a node
o -raversing the tree
Tra6ersing /et+o,s
1& (re A order method
2& In A order method
3& (ost A order method 8& Converse (re A order method ;& Converse In A order method <& Converse post A order method8'
http://vustudents.ning.com
http://vustudents.ning.com
Pre C or,er met+o,
-his method gives the tree key value in the following manner: -
%. (rocess the root
8. -raverse the left sub tree
5. -raverse the right $ub tree
In C or,er met+o,
-his method gives the tree key value in the following manner: -
%. -raverse the left sub tree
8. (rocess the root
5. -raverse the right $ub tree
Post C or,er met+o,
-his method gives the tree key value in the following manner: -
%. -raverse the left sub tree
8. -raverse the right $ub tree
5. (rocess the root
Sorting
$orting is, without doubt, the most fundamental algorithmic problem
%. $upposedly, 8@P of all C( cycles ar e spent sorting
8. $orting is fundamental to most other algorithmic problems, for e4ample
binary search.
5. %an&different approaches lead to useful sorting algorithms, and these ideas
can be used to solve many other problems.
Chat is sortingY It is the problem of taking an arbitrary permutation of n items and
rearran'in' them into the total order,
Issues in Sorting
Increasing or Decreasing Order? - -he same algorithm can be used by both all we need do is change to in the comparison function as we desire. What about equal keys? A May be we need to sort on secondary keys, or leave in the same order as the original permutations. 8*
http://vustudents.ning.com

http://vustudents.ning.com
What about non-numerical data? - +lphabeti<ing is sorting te4t strings, and libraries
have very complicated rules concerning punctuation, etc. Is (ron)*illiams before or
after (ron +meri!a before or after (ron, ,ohn Y
Ce can ignore all three of these issues by assuming a !omparison fun!tionwhich
depends on the application. -ompare .a,#/ should return ``G]], ``H]], or ]]J]].
-##"ications of Sorting
#ne reason why sorting is so important is that once a set of items is
sorted, many other problems become easy.
Hea#s
+ heapis a complete binary tree with values stored in its nodes such that no
child has a value bigger than the value of the parent.
.elow is a heap.
&
/ M
W 8
/ M
' ?
+ heap provides a representation for a priorit& $ueue . 74ample: messages processed by
priority at a server
messages given priority weighting, higher numbers give better service
highly dynamic, messages coming and going fre6uently
need efficient insert new message and remove highest priority message
2emoval causes heap to be reheapified . ;or e4ample if we remove &
&
/ M
W 8
/ M
' ?
then we reheapify by copying rightmost leaf to root 0? becomes the
root1 ?/ M W 8 /' 8W
http://vustudents.ning.com

http://vustudents.ning.com
and then we recursively reestablish the heap property as follows: if the
parent is greater than a child, swap the parent with the highest priority child. ,eep
swapping until no more swaps are possible. $o in the above tree, first we would swamp ? with W.
W
/ M
? 8
/
'
-hen we would swap ? with '.
W
/ M
' 8
/
?
-he final swap yields a heapT
-he cost of removing an item 0reheapifiying after removing the item1 is
#0log n1. -he algorithm Bust traverses one path in the tree, which is #0log n1 in length.
;or each node on that path it performs at most two comparisons and one swap 05
operations -H constant time1. $o overall the algorithm has a worst case time comple4ity of
#0log n1.
$pace comple4ity is #0n1 since a se6uential array representation can be
used.
Duic9 sort
is a very efficient sorting algorithm invented by C.+.2. 3oarer. It has
two phases:
-he partition phase and
-he sort phase.
+s we will see, most of the work is done in the partition phase - it works
out where to divide the work. -he sort phase simply sorts the two smaller problems
that are gener ated in the partition phase.
-his makes _uick sort a good e4ample of the ,i6i,e an, conFuers strategy for solving
problems. 0Dou]ve already seen an e4ample of this approach in the binar
y search procedure.1 In 6uick sort, we divide the ar ray of items to be sorted into
two partitions and then call the 6uick sort procedure recursively to sort the two partitions, i.e.we divide the
problem into two smaller ones and !on$uer by solving the smaller ones. -hus the con6uer part of the 6uick sort routine looks like this: 8&
http://vustudents.ning.com

http://vustudents.ning.com
6uicksort0 void Ua, int low, int
high 1
I
int pivotE
/U -ermination conditionT U/
if 0 high H low 1
Initial $tep - ;irst (artition
I
pivot J partition0 a, low, high
1E
6uicksort0 a, low, pivot-% 1E
6uicksort0 a, pivotR%, high 1E
S
S
$ort /eft (artition in the same way
;or the strategy to be effective, the partition phase must ensure that all the items in one
part 0the lower part1 and less than all those in the other 0upper1 part.
-o do this, we choose a pivot element and ar range that all the items in the lower part are
less than the pivot and all those in the upper part greater than it. In the
most general case, we don]t know anything about the items to be sorted, so that any
choice of the pivot element will do - the first element is a convenient one.
DiG9straHs -"gorit+m
)Bikstra]s algorithm 0named after its discover, 7.C. )iBkstra1 solves the
problem of finding the shortest path from a point in a graph 0the sour!e 1 to a destination. It turns out
that one can find the shortest paths from a given source to all points in a graph in the
same time, hence this problem is sometimes called the sing"e0source s+ortest #at+s
problem.
*ra#+ Tra6ersa"
$ystematic traversals of gr aph are similar to preorder and post order
traversal for trees. -here are two graph traversals, depth- first and breadth-first search.
;re6uently the graph searches start at an arbitrary verte4. -he searches are efficient if they
are done in #0
n 0
m1, where nis the number of vertices and mthe number of edges.
9raph traversal can be used to determine the general characteristic of
the graph, or to solve a specific problem on a particular graph, for e4ample: 2outing phone calls, or packets (lanning a car trip /ocate particular vertices, for e4ample a win position in a game. 5>
http://vustudents.ning.com

http://vustudents.ning.com
De#t+0first Searc+
Ce start the graph traversal at arbitrary vertices, and go down a
particular branch until we reach a dead end. -hen we back up and go as deep possible. In this
way we visit all vertices, and all edges.
Ereat+0)irst Searc+
.readth-first search visit all adBacent vertices before going deeper.
-hen we go deeper in one of the adBacent vertices.
S#arse /atrix B
+ matri4 consists of more number of <eros is called sparse matri4. #nce
the matri4 is stored as it is then there is wastage of memory. ;or an efficient
memory utili<ation the sparse matri4 can be stored in a linear form. -he linear form can be of
array type or linked list type.
D-T- STRUCTURES
DefinitionB
)ata structure is collection of data elements organi<ed in a specified
manner and accessing functions are defined to store and retrieve individual data
elements. )ata structures are sometimes called )ata types.
C"assification of Data StructureB
+ data type may be defined as a set and the elements of the set are
called the values of the type. -here are four basic or atomic or primitive data types
in C. -hey are int, float, char and double. -he $imple data types built from primitives
are arrays , pointers, strings and records with which we can build new types called
structured or composite types such as stacks, 6ueues, and trees etc. -he structured
data types can be categori<ed as linear and non-linear. -he linear data structures are
stacks, 6ueues and linked lists. -he non-linear data structures are trees and graphs.
Stac9s
DefinitionB
+ stack is an ordered collection of items into which new items may be
inserted and from which items may be deleted at one end, called the top of the stack.
-he first
e4ample of stack, which permits the selection of only its end element ,
is a pile of coins.
$econd e4ample could be a pile of tr ays or a books lying one above the
other. /et us draw a stack containing integers as in the following figure. 5%
http://vustudents.ning.com

http://vustudents.ning.com
@ top
&
%
5
*
3ere, @ is the current of the stack. If we add any element in the stack, it
will be placed on top of @ , and if we delete an element , it will be @, which is on top of
the stack.
O#erations on Stac9sB
+ssociated with the stack , there ar e several primitives operations. Ce
can define the following necessary operations on stack.
a1 create0s1 - -o create s as an empty stack.
b1 push0s,i1 - -o insert the element I on top of the stack s.
c1 pop0s1 - -o remove the top element of the stack and to return
the removed element as a function value.
d1 top0s1 - -o return the top element of stack0s1.
e1 empty0s1 - -o check whether the stack is empty or not. It returns
true if stack is empty and returns false otherwise.
If a stack is empty and it contains no element, it is not possible to pop
the stack. -herefore, before popping an element, we must ensure that the stack is
not empty.
PUSH I POP OPER-TIONSB
1+en :e a,, an e"ement to a stac9' :e stay t+at :e #us+ it on t+e
stac9 an, if :e ,e"ete an e"ement from a stac9' :e say t+at :e #o# it
from t+e stac9&
.et us see +o: stac9 s+rin9s or gro:s :+en :e #o# or #us+ an
e"ement in t+e
fo""o:ing figures&
Pus+ %>( on t+e stac9
58
http://vustudents.ning.com

http://vustudents.ning.com
W top
@
&
%
5
*
(ush 0?1 on to stack
? top
W
@
&
%
5
*
(op an element from the stack
-op (opped element J ?
W
@
&
%
5
*
(op an element from the stack 55
http://vustudents.ning.com

http://vustudents.ning.com
-op (opped element J W
@
&
%
5
*
Ce may notice that the last item pushed onto a stack is always the first
that will be popped from the stack. -hat is why stack is called last in, first out or
/I;# in short.
Im#"ementation of Stac9s
T+ere are t:o :ays to im#"ement stac9s' one using arrays an,
ot+er is
using "in9e, "ist&
-rrayB
$ince the elements of the stack are ordered , an obvious choice would
be an array as a structure t contains a stack. Ce can fi4 one end of the array as
bottom of the stack. -he other end of the array may be used as a top of the stack,
which keeps shifting constantly as items are popped and pushed. Ce must store the
inde4 of the array containing the top element.
Ce can , therefore, declare a stack as a structure containing two fields-
an array to hold the elements of the stack, and an integer top to indicate the position of
the current top of the stack within the array.
F define M+" @>
struct stackI
int topE
int elements K@LE
SE
struct stack sE
3ere s is defined to be a stack containing elements of type
integer . -he ma4imum
number of elements in the stack is defined to be @>. 7lements K>L
contain the first element
so that the value of top is >. If there are five elements in the stack, the
value of top will be four and the top element is in elementsK?L. 5?
http://vustudents.ning.com

http://vustudents.ning.com
+ stack is empty when it contains no elements we can indicate this by
making top as A%. Ce can write our function clearstack as
clearstack0ts1
struct stack UtsE
I
ts-Htop J -%E
S
+nother operation is to check whether the stack is empty. -o do
this we must check whether s.top J J -%.
/et us now consider the ($3 operation . -o push or add an element
we must perform the two steps:
i. increment top indicator
ii. put the new element at the new top.
Ce might code the ($3 Q (#( operations as follows:
push0ts,41
$truct stack UtsE
Int 4E
I
if 0fullstack0ts11I
printf0 O PsN, O $tack overflowN1E
e4it0%1E
S
else
ts-HelementsKRR0ts-Htop1L J 4E
returnE
S
-his routine increments the top by % and puts 4 into array
s.elements at the new top position. In this routine we use another routine ;ull $tack which checks
whether the stack is full, before we push an element onto stack. + stack is full when ts-
Htop J J M+"-%.
;ull $tack routine as follows:
fullstack 0ts1
struct stack UtsE Iif 0 ts-Htop J J M+"-%1 return0%1E else return0>1E S 5@
http://vustudents.ning.com

http://vustudents.ning.com
-o remove an element or pop an element from the stack, we must first
check the possibility of underflow as it is 6uite possible that somebody tries to
pop an element from an empty stack. -herefore, we can write function (#( as,
(op0ts1
struct stack UtsE
I
if 0empty0ts11
printf0 O P sN , O stack underflowN1E
return0>1E
else
return0ts-HelementsKts-Htop--L1E
S
Ce can write function empty 0s1 that returns % if the stack is
empty and > if it is not empty as follows:
empty0ts1
struct stack UtsE
I
if 0 ts -H top J J -%1
return 0%1E
else
return0>1E
S
$tack as a /inked /ist 0 sing (ointers1:
sing this representation we are using the pool of available nodes and
we will never have to test whether a particular stack is full. Ce can declare
such as a stack as follows.
!ode structure: 7ach node has two fields. i.e. )ata and !e4t field
)ata field !e4t field
$tack- !ode representation:
+ . C ) $tack 7nd node -op element 5'
http://vustudents.ning.com

http://vustudents.ning.com
)eclaration : 0 sing CRR1
F include Giostream.hH
F include G process.hH
class staI
struct node I
int dataE
node U ne4tE
S Ustack E
public :
void push01E
void pop01E
void disp01E
S
PUSH OPER-TIONB
:oid sta :: push01
I
int nE
node tempE
temp J new nodeE 5
cout GG O (ush the element O GG endlE 0 ;irst node of
temp the stack1.
cin HH temp-HdataE
temp-Hne4tJ!//E stack
if0stackJ J !//1
stackJtempE
else 5
I
temp-Hne4tJstackE stack
stackJtempE ?
S ?
temp
S
? 5
stack POP O#erationB stack 8 ? 5 :oid sta :: pop01 5*
http://vustudents.ning.com

http://vustudents.ning.com
I temp
node UtempE
if 0stackJ J !//1
cout GG O $tack is empty O GG endlE
else I stack
tempJ stackE
stackJ stack-Hne4tE temp
cout GG O(opped element O GG endlE
cout GG temp-HdataE
delete tempE
S
S
TREE TR-ERS-.B
Chen traversing a binary tree, we want to treat each node and its sub
trees in the same fashion. If we let /, :, and 2 stand for moving left, visiting the
node, and moving right when at a node, then there are si4 possible combinations of tree
traversal: /:2, /2:, :/2, :2/, 2:/, and 2/:. If we adopt the convention that we
traverse left before right, then only three traversals remain : /:2, /2: and :/2. -o these
we assign the names inorder, postorder, and preorder, respectively, because of the
position of the : with respect to the / and the 2.
Proce,ure for Preor,erB
%. :isit the root node.
8. -raverse the /eft sub tree in preorder.
5. -raverse the 2ight sub tree in preorder.
Exam#"eB
)ig&1
-he result is : R + . 5W
http://vustudents.ning.com

http://vustudents.ning.com
-"gorit+mB
void preorder0node Unodeptr1
I
if 0 nodeptr TJ !//1
I
printf0OPdMnN, nodeptr-Hdata1E /U visit the root node U/
preorder0nodeptr-Hleft1E /U -raverse the left sub tree U/
perorder0nodeptr-Hright1E /U -raverse the right sub tree U/
S
S
Proce,ure for Inor,erB
%. -raverse the /eft sub tree in inorder.
8. :isit the root node
5. -raverse the 2ight sub tree in inorder.
)ig&2
-he result is : + R .
void inorder0 node Unodeptr1
I
if 0 nodeptr TJ !//1
I
inorder0nodeptr-Hleft1E /U -raverse the left sub tree U/
printf0OPdMnN, nodeptr-Hdata1E /U :isit the root node U/
inorder0nodeptr-Hright1E /U -raverse the right sub tree U/
S
SProce,ure for Postor,erB %. -raverse the /eft sub tree in postorder. 8. -raverse the 2ight sub tree in postorder. 5. :isit the root node. 5&
http://vustudents.ning.com
http://vustudents.ning.com
)ig&3
-he result is : + . R
void postorder0 node U nodeptr1
I
if 0nodeptr TJ !//1
I
postorder0nodeptr-Hleft1E /U -raverse the left sub tree U/
postorder0nodeptr-Hright1E /U -raverse the right sub tree U/
printf0OPdMnN, nodeptr-Hdata1E /U :isit the root node U/
S
S
;ig.?
(27 #2)72 : +,.,),C,7,+!) ; I! #2)72 : .,),+,7,;,C (#$-#2)72 : ),.,;,7,C,+!) + ?>
http://vustudents.ning.com

http://vustudents.ning.com
;ig.@.
(27#2)72 : U R + . / C )
I!#2)72 : + R . U C / )
(#$-#2)72 : + . R C ) / U
EIN-RJ SE-RCH TREES
DefinitionB
+ binary search tree is a binary tree. It may be empty. If it is not empty
then it satisfies the following properties:
%. 7very element has a key and no two elements have the same key.
8. -he keys in the left sub tree ar e smaller than the key in the root. 5. -he keys in the right sub tree are larger than the key in the root. ?. -he left and right sub trees are also binar y search trees. It has two operations. -hey are, %. Insertion 8. )eletion ?%
http://vustudents.ning.com
http://vustudents.ning.com
Exam#"e )ig&
-o construct 0Insertion1 the .inary search tree for the following
elements:
8@, %@, 8*, %5, %*, 8', 8&, 8W
?8
http://vustudents.ning.com

http://vustudents.ning.com
?5
http://vustudents.ning.com

http://vustudents.ning.com
-o delete a particular node from the .inary search tree:
1& .eaf no,e
)eletion of a leaf node is 6uite easy. -o delete 8W from the
below tree the left child field of its parent is set to > and the node
disposed. -o delete the %* from this tree, the right-child field of %@ is set to > , and the node
containing %* is disposed.
-o delete a leaf node 8W
-o delete a leaf node %* ??
http://vustudents.ning.com
http://vustudents.ning.com
2& Non0"eaf no,eB
-he deletion of a non-leaf element or node that has only one child is
also easy. -he node containing the element to be deleted is disposed, and the single-
child takes the place of the disposed node.
$o, to delete the element %@ from the above tree, we simply change the
pointer from the parent node 08@1 to the single-child node0%51. ?@
http://vustudents.ning.com

http://vustudents.ning.com
3& Root no,eB
Chen the element to be deleted is in a non-leaf node that
has two children, the element is replaced by either the largest element in
its left sub tree or the smallest one in its right sub tree. -hen we proceed to delete this
replacing element from the sub tree from which it was taken.
If we wish to delete the element with key 8@ from the above tree, then
we replace it by
either the largest element, %* , in its left sub tree or the smallest
element , 8' , in its right
sub tree. $uppose we opt for the largest element in the left sub tree. -he
%* is moved in to the root and the following tree is obtained.?'
http://vustudents.ning.com
http://vustudents.ning.com
HE-PS
Priority DueueB
-he priority 6ueue is a data structure in which the intrinsic ordering of
the elements does determine the results of its basic operations. -here are
two types of priority 6ueues:
+n ascending priority 6ueue and a descending priority 6ueue.
+n ascending priority 6ueue is a collection of items into which items
can be inserted arbitrarily and from which only the smallest item can be removed. +
descending priority 6ueue is similar but allows deletion of only the largest item.
Hea#s DefinitionB
+ ma4 0min1 heap is a tree in which the key value in each node is no
smaller 0larger1 than the key values in its children 0if any1. + ma4 heap is a
complete binary tree that is also a ma4 tree. + min heap is a complete binary tree that is also
a min tree.
?*
http://vustudents.ning.com
http://vustudents.ning.com
/ax& Hea#
/in& Hea#
DUEUE
DefinitionB
+ 6ueue is an ordered collection of items from which items may be
deleted at one
end 0 called the front of the 6ueue1 and into which items may be
inserted at the other end
0 called rear of the 6ueue1. -his data structur e is commonly known as
;I;# or first-in- first-out. ?W
http://vustudents.ning.com

http://vustudents.ning.com
)ig&1
5 '
)ig&2
5 ' W
OPER-TION S ON DUEUESB
It has two operations. -hey are
Insertion
)eletion
Insertion an element is popularly known as 7!_ and deleting an
element is known as )7_. + minimum set of useful operations on 6ueue includes the
following.
i. C27+-7_0_1 A which creates _ as an empty _ueue.
ii. 7!_0i1 A which adds the element I to the rear of a 6ueue and returns the
new 6ueue.
iii. )7_0_1- which removes the element at the front end of the 6ueue and
returns the resulting 6ueue as well as the removed element.
iv. 7M(-D0_1- It checks the 6ueue whether it is empty or not and returns
true if it is empty and returns false otherwise.
v. ;2#!-0_1- which returns the front element of the 6ueue without
changing the 6ueue.
vi. _77$I=70_1-which returns the number of entries in the 6ueue.
Ce can obtain the 6ueue by the following se6uence of operations. Ce
assume that the 6ueue in initially empty. ?&
http://vustudents.ning.com

http://vustudents.ning.com
7!_06,W1
@ * W
7!_06,&1
@ * W &
7!_06,?1
@ * W & ?
4 J)7_061 7lement @ is deleted
* W & ?
4 J)7_061 7lement * is deleted W & ? @>
http://vustudents.ning.com

http://vustudents.ning.com
I/P.E/ENTIN* THE DUEUE
-here are two ways to implement 6ueue, one using arrays, and
another is using /inked list.
i& -rray B
/et us implement the 6ueue within an array so that the array holds the
elements of the 6ueue. -here are two variables front and rear to indicate
the positions of the first and last element of the 6ueue within the array.
/et the si<e of the array be ?. Initially let us assume that the 6ueue is
empty which means front J > and rear J -%.
Em#ty DueueB
6K>L 6K%L 6K8L 6K5L
front J >0array position1 rear J -% 0 !//1
InsertionB
-here are two variables front and rear to indicate the positions of the
first and last element of the 6ueue within the array. /et the si<e of the array be ?.
Initially let us assume that the 6ueue is empty which means front J > and rear J
-%.+fter we have added three elements to the 6ueue rear becomes 8 and front becomes >. !ow if
we add one more elements to the 6ueue from the rear, the value of rear changes to 5.
!ow the 6ueue becomes full.
7!_06,51 5 6K>L 6K%L 6K8L 6K5L front J > rear J> @%
http://vustudents.ning.com

http://vustudents.ning.com
7!_06,@1
5 @
6K>L 6K%L 6K8L 6K5L
front J > rear J %
7!_06,*1
5 @ *
6K>L 6K%L 6K8L 6K5L
front J > rear J 8
7!_06,&1 K _ is full L
5 @ * &
6K>L 6K%L 6K8L 6K5L
front J > rear J 5
De"etionB
+t this point, we delete one element. -he element which is deleted is 5.
-his leaves a hole in the first position. -o delete this element we must
increment front, to indicate the true first element of the 6ueue and assign the value of that
slot to 4. -o check whether 6ueue is empty or not, we must check whether front J rear.
-o add an element we must increment rear so that it points to the
location ne4t to the rear and place an element in that slot of the array. If we wish to add another
element, and we
increment rear by %, rear becomes e6ual to front, which indicates that
the 6ueue is full. "J )7_061 @ * & 6K>L 6K%L 6K8L 6K5L @8
http://vustudents.ning.com

http://vustudents.ning.com
front J % rear J 5
4J)7_061
* &
6K>L 6K%L 6K8L 6K5L
front J 8 rear J 5
4J)7_061
&
6K>L 6K%L 6K8L 6K5L
front J 5 rear J 5
4J)7_061 K _ueue is emptyL
6K>L 6K%L 6K8L 6K5L
front J rear J -%0!//1
-herefore, the condition for full 6ueue is that the ne4t slot of rear is
e6ual to front and the condition for empty 6ueue is that front J rear. .efore we )7_ an
element from 6ueue we must make sure that 6ueue is not empty and before we 7!_ an element
we must ensure that the 6ueue is not full.
_ueue implementations in +22+D using CRR
class 6uI (ublic : Int front, rear, n , 6K%>LE void get01I @5
http://vustudents.ning.com

http://vustudents.ning.com
coutGG O 7nter the _ueue si<e O GG endlE
cinHH nE
front J rear J-%E
S
void en601E
void de601E
SE
int I, aK%>LE
void 6u :: en601I
int itemE
if 0 rear HJ n1
I
cout GG O _ueue is full MnNE
returnE
S
else
I
cout GG O 7nter the item to be insertedN GGendlE
cinHHitemE
rear J rearR%E
6KrearL J itemE
iRRE
S
S
void 6u :: de601
I
int tE
if 0 front HJ rear1
I
cout GG O _ueue is 7mptyN GG endlE
returnE
S
else
I
front J fornt R%E
t J 6KfrontL E cout GG O -he deleted element : O GG t GG endlE SS @?
http://vustudents.ning.com

http://vustudents.ning.com
Im#"ementation of Dueue as .in9e, "ist
+nother way of implementing 6ueues is as a linked list.
/et us have two pointers, front to the first element of the list and rear to
the last element of the list.
?
'
front
W
rear
.
class 6ue I
struct node
I
int dataE
node Une4tE
S U front, UrearE
public:
void ins601E
void del601E
6ue01I
front J rear J !//E
S
SE
void 6ue :: ins601
I temp
int nE
?
node UtempE
temp J new nodeE front
cout GG O Insert the element O GG endlE
cin HH nE
temp-data J nE
temp-Hne4t J !//E if 0 front J J !//1 front J rearJtempE else ? I @ rear-Hne4t J tempE front rearJ rear-Hne4tE rear @@
http://vustudents.ning.com

http://vustudents.ning.com
S
S
void 6ue :: del601
I
?
node UtempE
temp J frontE temp
'
W
if 0 front J J !//1 front
cout GG O _ueue is empty O GG endlE
else
I rear
front J front- Hne4tE
cout GG temp-HdataE
delete tempE
S
S
DEDUEB
+ single 6ueue behaves in a ;I;# manner in the sense that each deletion
removes the oldest remaining item in the structure. + double ended 6ueue or de6ue,
in short is a linear list in which insertions and deletions are made to or from either end of
the structure.
)eletion Insertion
Insertion )eletion
;ront 2ear
Ce can have two variations of a de6ue, namely, the input-restricted
de6ue and the output Arestricted de6ue. -he output-restricted de6ue allows deletion from only
one end and input-restricted de6ue allows insertions at only one end.
Dueue -##"icationsB
-he most useful application of 6ueues is the simulation of a real world
situation so that it is possible to understand what happens in a real world
in a particular situation without actually observing its occurrence.
_ueues are also very useful in a time-sharing computer system wher e
many users share
the system simultaneously. Chenever a user re6uests the system to run a
particular
program, the operating system adds the re6uest at the end of the 6ueue
of Bobs waiting to
be e4ecuted. Chenever the C( is free, it e4ecutes the Bob, which is at
the front of the
Bob 6ueue. $imilarly there are 6ueues for sharing I/# devices. 7ach
device maintains its own 6ueue of re6uest. @'
http://vustudents.ning.com

http://vustudents.ning.com
+nother useful application of 6ueues is in the solution of
problems involving searching a nonlinear collection of states. _ueue is
used for finding a path using breadth-first-search of graphs.
.INKED .IST
DefinitionB
+ collection of node is called list. 7ach node or item in a linked list
must contain at least two fields, an information field or data field and the ne4t
address field. -he first, field contains the actual element on the list which may be a
simple integer, a character, a string or even a large record. -he second field, which is a
pointer, contains the address of the ne4t node in the list used to access the ne4t node. +
node of a linked list may be represented by the following figure.
)ata or !e4t
Info
/ist
0 74ternal pointer1
-he entire linked list is accessed from an e4ternal pointer /ist pointing
to the first node in the list. Ce can access the first node through the e4ternal pointer, the
second node through ne4t pointer of the first node, the third node through the ne4t
pointer of the second node till the end of the list.
-he ne4t address field of the last node contains a special value, known
as the !// value. -his is not a valid address. -his only tells us that we have
reached the end of the list. Ce will draw linked lists as an ordered se6uence of nodes with
links being represented by arrows.
/ist
? @ '
OPER-TIONS ON .INKED .IST
-here are five basic types of operations associated with the list
data abstraction:
%. -o determine if the list is empty. 2eturns true
if the list contains no elements. 8. +dd new elements any in the list 5. -o check if a particular element is present in the list. ?. -o delete a particular element from the list placed anywhere in the list. @. -o print all the elements of the list. @*
http://vustudents.ning.com

http://vustudents.ning.com
Ce will introduce some notations to be used in algorithms:
If p is a pointer to a node, then
node0p1 refers to the node pointed to by p
info0p1 refers to the data part of that node
ne4t0p1 refers to the address part of that node
info0ne4t0p11 refers to the data part of the ne4t node which node, which
follows node0p1 in the list if ne4t0p1 is not null.
Ce can initiali<e the list by making the e4ternal pointer null.
/ist J null
+lso, we can check whether the list is empty by checking whether the
e4ternal pointer is null.
if list J null
then return0true1
else return0false1
-his routine will return true if the list is empty, otherwise it will return f
alse. -o traverse or to print the elements of a linked list, we need to use a
temporary pointer, p known as a traversal pointer.
( J list
while list G H null do
begin
print0 info0p11
pJ ne4t0p1
end
Inserting into a .in9e, "ist
-o add a new node containing data value 4 in the beginning of the list
we need to follow the step:
i. -o get a new node which is not in use.
ii. -o set the data field of the new node to 4
iii. -o set the ne4t field of the new node to point to list
iv. -o set pointer list point to the new node. -o do this we can write the following algorithm: getnode0p1 info0p1 J 4 ne4t0p1 J list @W
http://vustudents.ning.com

http://vustudents.ning.com
list J p
Ce are assuming that the operation getnode0p1 obtains an empty node
and sets the contents of a variable named p to the address of that node.
p
9etnode0p1
p
4
Info041 J p
p /ist
4 @ '
ne4t0p1 J list
/ist
? @ '
p
list J p
Sam#"e #rograms B
Ex& No& 1 Stac9
ProgramB
FincludeGstdio.hH
FincludeGconio.hH
int topJ%E int aK8>LE void main01 Iint n,4,b,c,i,tempE clrscr01E printf0V7nter the no of elementsMnV1E @&
http://vustudents.ning.com
http://vustudents.ning.com
scanf0VPdV,Qn1E
do
I
printf0V%.($3MnV1E
printf0V8.(#(MnV1E
printf0V5.)I$(/+DMnV1 E
printf0V?.7"I-MnV1E
breakE printf0Venter your choiceMnV1E
scanf0VPdV,Qb1E
switch0b1
I
case %:
printf0Venter the numberMnV1E
if0topHJnR%1
printf0VMnstack is overflowMnV1E
else
scanf0VPdV,Q41E
aKtopLJ4E
topJtopR%E
breakE
case 8:
if 0topGJ>1
printf0Vstack is under flowMnV1E
else
I
topJtop-%E
tempJaKtopL E
S
breakE
case 5:
for0iJ%EiGtop-%EiRR1
printf0VPd-- HV,aK iL1E
printf0VPdV,aKtop-%L1E
breakE
case ?:
e4it0>1E
Sprintf0VMndo you want to continue0%/>1MnV1E scanf0VPdV,Qc1E Swhile0cJJ%1E getch01E S '>
http://vustudents.ning.com
http://vustudents.ning.com
Ex& No& 2 Dueue
ProgramB
FincludeGstdio.hH
FincludeGconio.hH
int n,4,b,c,i,rJ>,fJ>,teE
int 6K8>LE
void main01
I
clrscr01E
printf0V7nter the no of elementsMnV1E
scanf0VPdV,Qn1E
do
I
printf0V%.insertionMnV1E
printf0V8.deletionMnV1E
printf0V5.displayMnV1E
printf0V?.e4itMnV1E
printf0Venter your choiceMnV1E
scanf0VPdV,Qb1E
switch0b1
I
case %:
insert01E
display01E
breakE
case 8:
delet01E
display01E
breakE
case 5:
display01E
breakE
case ?:
e4it0>1E
Sprintf0VMndo you want to continue0%/>1MnV1E scanf0VPdV,Qc1E Swhile0cJJ%1E getch01E S '%
http://vustudents.ning.com

http://vustudents.ning.com
insert01
I
if0rHJn1
printf0VMn6ueue is overflowMnV1E
else
I
printf0Venter the numberMnV1E
scanf0VPdV,Q41E
rJrR%E
6KrLJ4E
S
if0fJJ>1
fJ%E
return0>1E
S
int delet01
I
int teE
if 0fJJ>1
printf0V6ueue is under flowMnV1E
else if 0fJJr1
I
fJ>ErJ>E
S
else
I
teJ6KfLE
fJfR%E
S
return0te1E
S
display01
I
if0rJJ>1
I
printf0V 6ueue is emptyV1E
S
else Ifor0iJfEiGrEiRR1 printf0VPd-- HV,6KiL 1E printf0VPdV,6KrL1E Sreturn0>1E '8
http://vustudents.ning.com

http://vustudents.ning.com
S
Ex& NoB 3 Sing"y .in9e, "ist
ProgramB
FincludeGstdio.hH
FincludeGconio.hH
Fdefine null >
int a,sE
struct node
I
int dataE
struct node UlinkE
SE
struct node Uhead,Ufirst,Uprevious,UtempE
void main01
I
firstJnullE
headJnullE
clrscr01E
do
I
printf0V%.creationMnV1E
printf0V8.displayMnV1E
printf0V5.insert firstMnV1E
printf0V?.insert lastMnV1E
printf0V@.insert middleMnV1E
printf0V'.delete firstMnV1E
printf0V*.delete lastMnV1E
printf0VW.delete middleMnV1E
printf0Venter your choiceV1E
scanf0VPdV,Qa1E
switch0a1
I
case %:
create01E
display01E breakE case 8: display01E breakE case 5: insfirst01E '5
http://vustudents.ning.com

http://vustudents.ning.com
display01E
breakE
case ?:
inslast01E
display01E
breakE
case @:
insmiddle01E
display01E
breakE
case ':
delfirst01E
display01E
breakE
case *:
dellast01E
display01E
breakE
case W:
delmiddle01E
display01E
breakE
case &:
e4it0>1E
S
printf0VMndo you want to continue0%/>1MnV1E
scanf0VPdV,Qs1E
S
while0sJJ%1E
S
create01
I
int sE
sJsi<eof 0struct node1E
firstJ0struct nodeU1 malloc 0s1E
printf0Venter the dataV1E
scanf0VPdV,Qfirst-Hdata1E
first-HlinkJnullE if0headJJnull1 headJfirstE else IpreviousJheadE while0previous-Hlink TJnull1 '?
http://vustudents.ning.com

http://vustudents.ning.com
previousJprevious-HlinkE
S
previous-HlinkJfirstE
previousJfirstE
return0>1E
S
display01
I
if0headJJnull1
printf0Vnull firstV1E
else
tempJheadE
while0tempTJnull1
I
printf0VPd-HV,temp-Hdata1E
tempJtemp-HlinkE
S
printf0VnullMnV1E
return0>1E
S
insfirst01
I
int sE
if 0headJJnull1
printf0Vlist is nullV1E
else
I
sJsi<eof 0temp1E
tempJ0struct nodeU1 malloc0s1E
printf0Venter dataMnV1E
scanf0VPdV,Qtemp-Hdata1E
temp-HlinkJheadE
headJtempE
S
return0>1E
S
delfirst01 Iint sE if0headJJnull1 printf0Vlist is nullV1E else headJhead-HlinkE '@
http://vustudents.ning.com

http://vustudents.ning.com
return0>1E
S
inslast01
I
int sE
struct node Utemp,UlastE
if 0headJJnull1
printf0Vlist is nullV1E
else
I
sJsi<eof 0last1E
lastJ0struct nodeU1 malloc0s1E
printf0Venter the dataMnV1E
scanf0VPdV,Qlast-Hdata1E
last-HlinkJnullE
tempJheadE
while0temp-HlinkTJnull1
tempJtemp-HlinkE
temp-HlinkJlastE
S
return0>1E
S
dellast01
I
int s,mE
struct node Upre,Une4tE
if0headJJnull1
printf0Vlist is nullV1E
else
I
ne4tJheadE
ne4tJhead-HlinkE
preJheadE
while0ne4t-HlinkTJnull1
I
ne4tJne4t-HlinkE
preJpre-HlinkE
Spre-HlinkJne4t-HlinkE Sreturn0>1E Sinsmiddle01 I ''
http://vustudents.ning.com

http://vustudents.ning.com
int s,f,countE
struct node Une4t,Upre,Une4E
if 0headJJnull1
printf0Vlist is nullV1E
else
I
sJsi<eof 0temp1E
tempJ0struct nodeU1 malloc0s1E
preJheadE
ne4tJpre-HlinkE
countJ8E
printf0Venter the position of the elementV1E
scanf0VPdV,Qf1E
printf0Venter the dataMnV1E
scanf0VPdV,Qne4-Hdata1E
while00countGf1 QQ 0ne4t-HlinkTJnull11
I
ne4tJne4t-HlinkE
preJpre-HlinkE
countJcountR%E
S
if00countGf1 QQ 0ne4t-HlinkJJnull11
I
printf0Vnot possible to insert. the list is contains Pd elementsV,count1E
S
else
I
pre-HlinkJne4E
ne4-HlinkJne4tE
S
S
return0>1E
S
delmiddle01
I
int s,f,countE
struct node Une4t,Upre,Une4E
if 0headJJnull1
printf0Vlist is nullV1E else IsJsi<eof 0temp1E tempJ0struct nodeU1 malloc0s1E preJheadE ne4tJpre-HlinkE '*
http://vustudents.ning.com

http://vustudents.ning.com
countJ8E
printf0Venter the position of the elementV1E
scanf0VPdV,Qf1E
while00countGf1 QQ 0ne4t-HlinkTJnull11
I
ne4tJne4t-HlinkE
preJpre-HlinkE
countJcountR%E
S
if00countGf1 QQ 0ne4t-HlinkJJnull11
I
printf0Vnot possible to insert. the list is contains Pd elementsV,count1E
S
pre-HlinkJne4t-HlinkE
S
return0>1E
S
Ex& No& 8 ,ou!"y "in9e, "ist
ProgramB
8& 1rite a C #rogram to im#"ement t+e Dou!"e .in9e, .ist&
FincludeGconio.hH
FincludeGstdio.hH
FincludeGstdlib.hH
struct student
I
int rollnoE
struct student UprevE
struct student Une4tE
SE
typedef struct student listE
void add0list Uhead,int rollno1
Ilist UnewZelt,UtempJheadE newZeltJ0list U1malloc0si<eof0list11E newZelt-HrollnoJrollnoE newZelt-Hne4tJ!//E 'W
http://vustudents.ning.com

http://vustudents.ning.com
while0temp-Hne4tTJ!//1
tempJtemp-Hne4tE
newZelt-HprevJtempE
temp-Hne4tJnewZeltE
S
void insert0list Uhead,int rollno,int position1
I
int iE
list UnewZelt,UadBZelt,UtempJheadE
newZeltJ0list U1malloc0si<eof0list11E
newZelt-HrollnoJrollnoE
for0iJ%EiGpositionEiRR1
tempJtemp-Hne4tE
adBZeltJtemp-Hne4tE
adBZelt-HprevJnewZeltE
newZelt-Hne4tJadBZeltE
newZelt-HprevJtempE
temp-Hne4tJnewZeltE
S
int find0list Uhead,int rollno1
I
list UtempJhead-Hne4tE
int foundJ>,iJ%EE
while0tempTJ!//1
I
if0temp-HrollnoJJrollno1
I
foundJiE
breakE
S
iRRE
tempJtemp-Hne4tE
S
return foundE Svoid remove7lt0list Uhead,int rollno1 Ilist UdelZelt,Usuccessor,Upredecsor,UtempJhead-Hne4tE int i,foundE foundJfind0head,rollno1E '&
http://vustudents.ning.com

http://vustudents.ning.com
if0foundTJ>1
I
while0temp-HrollnoTJrollno1
tempJtemp-Hne4tE
delZeltJtempE
predecsorJdelZelt-HprevE
successorJdelZelt-Hne4tE
predecsor-Hne4tJdelZelt-Hne4tE
successor-HprevJdelZelt-HprevE
free0delZelt1E
printf0VMn#ne 7lement is deletedV1E
S
else
printf0VMn7lement has not ;oundTCann]t perform )eletionTV1E
S
void printZlist0list Uhead1
I
if0head-Hne4tTJ!//1
I
list UtempJhead-Hne4tE
printf0VMn-he /ist:MnV1E
while0tempTJ!//1
I
printf0VPd-- H V,temp-Hrollno1E
tempJtemp-Hne4tE
S
printf0V!ullV1E
S
else
printf0VMn -he /ist is 7mptyV1E
S
void makeZemptylist0list Uhead1
I
head-HprevJ!//E
head-Hne4tJ!//E
printf0VMn-he /ist has been deletedT V1E
S
void main01 Ilist UheadE int position,rollno,optionE headJ0list U1malloc0si<eof0listU11E head-HprevJ!//E *>
http://vustudents.ning.com

http://vustudents.ning.com
head-Hne4tJ!//E
clrscr01E
while0%1
I
printf0VMnMn%.+ddMn8.Insert a ItemMn5.2emove a ItemMn?.;indMn@.(rint
the
/istMn'.)elete the /istMn*.74itV1E
printf0VMn7nter your Choice:V1E
scanf0VPdV,Qoption1E
switch0option1
I
case %:
printf0VMn7nter 2ollno of the !ew 7lement:V1E
scanf0VPdV,Qrollno1E
add0head,rollno1E
breakE
case 8:
printf0VMn7nter 2ollno of 7lement to be Inserted:V1E
scanf0VPdV,Qrollno1E
printf0VMn7nter (osition to insert:V1E
scanf0VPdV,Qposition1E
insert0head,rollno,position1E
breakE
case 5:
printf0VMn7nter the 2ollno of the element to 2emoved:V1E
scanf0VPdV,Qrollno1E
remove7lt0head,rollno1E
breakE
case ?:
printf0V7nter rollno of Item to be found:V1E
scanf0VPdV,Qrollno1E
positionJfind0head,rollno1E
if0positionTJ>1
printf0VMn7lement has been foundT(ositionJPdV,position1E
else
printf0VMn7lement has not found in the /istTV1E
breakE
case @:
printZlist0head1E
breakE case ': makeZemptylist0head1E breakE case *: e4it0>1E S *%
http://vustudents.ning.com

http://vustudents.ning.com
S getch01E S
7 x& NoB ; Circu"ar Sing"y .in9e, "ist
Program B
FincludeGstdio.hH
FincludeGconio.hH
int a,sE
struct node
I
int dataE
struct node UlinkE
SE
struct node Uhead,Ufirst,Uprevious,Ulast,UtempE
void main01
I
firstJ!//E
headJ!//E
previousJ!//E
clrscr01E
do
I
printf0V%.creationMnV1E
printf0V8.displayMnV1E
printf0V5.insert firstMnV1E
printf0V?.insert lastMnV1E
printf0V@.insert middleMnV1E
printf0V'.delete firstMnV1E
printf0V*.delete lastMnV1E
printf0VW.delete middleMnV1E
printf0Venter your choiceV1E
scanf0VPdV,Qa1E
switch0a1
I
case %: create01E display01E breakE case 8: display01E breakE *8
http://vustudents.ning.com

http://vustudents.ning.com
case 5:
insfirst01E
display01E
breakE
case ?:
inslast01E
display01E
breakE
case @:
insmiddle01E
display01E
breakE
case ':
delfirst01E
display01E
breakE
case *:
dellast01E
display01E
breakE
case W:
delmiddle01E
display01E
breakE
case &:
e4it0>1E
S
printf0VMndo you want to continue0%/>1MnV1E
scanf0VPdV,Qs1E
S
while0sJJ%1E
S
create01
I
int sE
sJsi<eof 0struct node1E
firstJ0struct nodeU1 malloc 0s1E printf0Venter the dataV1E scanf0VPdV,Qfirst-Hdata1E first-HlinkJfirstE if0headJJ!//1 IheadJfirstE *5
http://vustudents.ning.com

http://vustudents.ning.com
previousJfirstE
S
else
I
previousJheadE
while0previous-Hlink TJhead1
previousJprevious-HlinkE
previous-HlinkJfirstE
previousJfirstE
S
lastJfirstE
return0>1E
S
display01
I
if0headJJ!//1
printf0Vlist is nullV1E
else
I
tempJheadE
while0tempTJlast1
I
printf0VPd-HV,temp-Hdata1E
tempJtemp-HlinkE
S
if0tempJJlast1
I
printf0VPd -HV,temp-Hdata1E
tempJtemp-HlinkE
S
S
return0>1E
S
insfirst01
I
int sE if 0headJJ!//1 printf0Vlist is nullV1E else IsJsi<eof 0temp1E tempJ0struct nodeU1 malloc0s1E *?
http://vustudents.ning.com

http://vustudents.ning.com
printf0Venter dataMnV1E
scanf0VPdV,Qtemp-Hdata1E
temp-HlinkJheadE
headJtempE
firstJtempE
last-HlinkJtempE
S
return0>1E
S
delfirst01
I
int sE
if0headJJ!//1
printf0Vlist is nullV1E
else
headJhead-HlinkE
last-HlinkJheadE
if0last-HlinkJJhead1
headJ!//E
return0>1E
S
inslast01
I
int sE
struct node Ulast%,Ufirst%E
if 0headJJ!//1
printf0Vlist is nullV1E
else
I
sJsi<eof 0last%1E
last%J0struct nodeU1 malloc0s1E
printf0Venter the dataMnV1E
scanf0VPdV,Qlast%-Hdata1E
last%-HlinkJ!//E
tempJheadE
while0temp-HlinkTJhead1
tempJtemp-HlinkE temp-HlinkJlast%E last%-HlinkJheadE lastJlast%E Sreturn0>1E S *@
http://vustudents.ning.com

http://vustudents.ning.com
dellast01
I
int s,mE
struct node Upre,Une4tE
if0headJJ!//1
printf0Vlist is nullV1E
else
I
if0headJJlast1
headJlastJ!//E
else
I
ne4tJheadE
while0ne4t-HlinkTJlast1
ne4tJne4t-HlinkE
ne4t-HlinkJheadE
lastJne4tE
S
S
return0>1E
S
insmiddle01
I
int s,f,countE
struct node Une4t,Upre,Une4E
if 0headJJ!//1
printf0Vlist is nullV1E
else
I
sJsi<eof 0temp1E
tempJ0struct nodeU1 malloc0s1E
preJheadE
ne4tJpre-HlinkE
countJ8E
printf0Venter the position of the elemantV1E
scanf0VPdV,Qf1E
printf0Venter the dataMnV1E
scanf0VPdV,Qne4-Hdata1E while00countGf1 QQ 0ne4t-HlinkTJhead11 Ine4tJne4t-HlinkE preJpre-HlinkE countJcountR%E S *'
http://vustudents.ning.com

http://vustudents.ning.com
if00countGf1 QQ 0ne4t-HlinkJJhead11
I
printf0Vnot possible to insert. the list is contains Pd elementsV,count1E
S
else
I
pre-HlinkJne4E
ne4-HlinkJne4tE
S
S
return0>1E
S
delmiddle01
I
int s,f,countE
struct node Une4t,Upre,Une4E
if 0headJJ!//1
printf0Vlist is nullV1E
else
I
sJsi<eof 0temp1E
tempJ0struct nodeU1 malloc0s1E
preJheadE
ne4tJpre-HlinkE
countJ8E
printf0Venter the position of the elemantV1E
scanf0VPdV,Qf1E
while00countGf1 QQ 0ne4t-HlinkTJhead11
I
ne4tJne4t-HlinkE
preJpre-HlinkE
countJcountR%E
S
if00countGf1 QQ 0ne4t-HlinkJJhead11
I
printf0Vnot possible to insert. the list is contains Pd elementsV,count1E
S
pre-HlinkJne4t-HlinkE
Sreturn0>1E S **
http://vustudents.ning.com

http://vustudents.ning.com
Ex& NoB < O#erations On Einary Trees
Program B
FincludeGstdio.hH
FincludeGmalloc.hH
struct node
I
int dataE
struct node UlchildE
struct node UrchildE
S
void creation01
I
printf0VMn 7nter the value of the root node MnV1E
tJ0struct nodeU1malloc0si<eof0struct node11E
scanf0VPdV,Qt-Hdata1E
t-HlchildJ!//E
t-HrchildJ!//E
S
void insert0int n,struct node Ua1
I
struct node U4E
if0a-Hdata TJ>1
I
if0a-HdataHn1
insert0n,a-Hlchild1E
else
insert0n,a-Hrchild1E
S
4J0struct nodeU1 malloc0si<eof0struct node11E
4-HdataJnE
if0a-HdataHn1
I
if00a-Hlchild1JJ!//1
Ia-HlchildJ4E a-Hlchild-HlchildJ!//E a-Hlchild-HrchildJ!//E SS *W
http://vustudents.ning.com

http://vustudents.ning.com
else
if0a-HrchildJJ!//1
I
a-HrchildJ4E
a-Hrchild-HlchildJ!//E
a-Hrchild-HrchildJ!//E
S
S
void inorder0struct nodeU a1
I
if0aTJ!//1
I
inorder0a-Hlchild1E
printf0V P%>d V,a-Hdata1E
inorder0a-Hrchild1E
S
S
void preorder0struct node Ua1
I
if0aTJ!//1
I
printf0V P%>dV,a-Hdata1 E
preorder0a-Hlchild1E
preorder0a-Hrchild1E
S
S
void postorder0struct node Ua1
I
if0aTJ!//1
I
postorder0a-Hlchild1E
postorder0a-Hrchild1E
printf0V P%>dV,a-Hdata1E
S
S
void main01
Iint num,cE clrscr01E creation01E doI printf0VMn %. Insertion Mn8. Inorder Mn5. preorder Mn?.postorder V1E printf0VMn for e4it give choice greater than fourV1E *&
http://vustudents.ning.com

http://vustudents.ning.com
printf0V Mn7nter your choice V1E
scanf0VPdV,Qc1E
switch0c1
I
case %:printf0V Mn )ata to be inserted V1E
scanf0VPdV,Qnum1E
insert0num,t1E
breakE
case 8: inorder0t1E
breakE
case 5: preorder0t1E
breakE
case ?: postorder0t1E
breakE
S
Swhile0cG@1E
S
Ex& No& = !inary tree o#eration
ProgramB
*. Crite a C program to implement the binary tree operations A insert,
delete, and search.
FincludeGconio.hH
FincludeGstdio.hH
FincludeGstdlib.hH
struct bstree
I
int dataE
struct bstree UleftE
struct bstree UrightE
SE
struct bstree Uroot,UtempE
struct bstreeU insertbst0struct bstree Uroot,int 41
I
if0 root JJ !//1 IrootJmalloc0si<eof0struct bstree11E root-HdataJ4E root-HleftJroot-HrightJ!//E S W>
http://vustudents.ning.com

http://vustudents.ning.com
else if04 G root-Hdata1
root-HleftJinsertbst0root-Hleft,41E
else if04 H root-Hdata1
root-HrightJinsertbst0root-Hright,41E
return rootE
S
struct bstreeU findMin0struct bstree Ut1
I
if0tJJ!//1
return !//E
else
if0t-Hleft TJ !//1
return findMin0t-Hleft1E
else
return tE
S
struct bstreeU findMa40struct bstree Ut1
I
if0tJJ!//1
return !//E
else
if0t-Hright TJ !//1
return findMa40t-Hright1E
else
return tE
S
int find0struct bstree Utemp,int key1
I
if 0tempJJ!//1
I
return !//E
S
else
I
if0key G temp-Hdata1
return find0temp-Hleft,key1E
else if 0key H temp-Hdata1
return find0temp-Hright,key1E else return tempE SSint findZmin0struct bstree Utemp1 I W%
http://vustudents.ning.com

http://vustudents.ning.com
if0temp-Hleft JJ !//1
return temp-HdataE
else
return findZmin0temp-Hleft1E
S
int findZma40struct bstree Utemp1
I
if0temp-Hright JJ !//1
return temp-HdataE
else
return findZma40temp-Hright1E
S
struct bstreeU remove7lt0struct bstree Ut,int key1
I
struct bstree UtempE
if 0tJJ!//1
printf0VMn!ode is not availableV1E
else if0key G t-Hdata1
t-HleftJremove7lt0t-Hleft,key1E
else if0key H t-Hdata1
t-HrightJremove7lt0t-Hright,key1E
else if0t-Hleft TJ !// QQ t-Hright TJ !//1
I
tempJfindMin0t-Hright1E
t-HdataJtemp-HdataE
t-HrightJremove7lt0t-Hright,t-Hdata1E
S
else
I
tempJtE
if0t-HleftJJ!//1
tJt-HrightE
else if0t-HrightJJ!//1
tJt-HleftE
free0temp1E
Sreturn tE Svoid printZlist0struct bstree Uroot1 Iif0rootTJ!//1 I W8
http://vustudents.ning.com

http://vustudents.ning.com
if0root-Hleft TJ !//1
printZlist0root-Hleft1E
printf0V PdV,root-Hdata1E
if0root-Hright TJ !//1
printZlist0root-Hright1E
S
S
void main01
I
struct bstree UnewZeltE
int option,rollno,infoE
rootJ!//E
clrscr01E
while0%1
I
printf0VMnMn%.Insert a ItemMn8.2emove a ItemMn5.;indMn?.;ind Minimum
:alueMn@.;ind Ma4imum :alueMn'.(rint the /istMn*.74itV1E
printf0VMn7nter your Choice:V1E
scanf0VPdV,Qoption1E
switch0option1
I
case %:
printf0VMn7nter 2ollno of 7lement to be Inserted:V1E
scanf0VPdV,Qrollno1E
rootJinsertbst0root,rollno1E
breakE
case 8:
printf0VMn7nter the 2ollno of the element to 2emoved:V1E
scanf0VPdV,Qrollno1E
rootJremove7lt0root,rollno1E
breakE
case 5:
printf0V7nter rollno of Item to be found:V1E
scanf0VPdV,Qrollno1E infoJfind0root,rollno1E if0infoTJ>1 printf0VMn7lement has been foundT at (ositionJPdV,info1E if0info JJ >1 printf0VMn7lement has not found in the /istTV1E W5
http://vustudents.ning.com

http://vustudents.ning.com
breakE
case ?:
if0root JJ !//1
printf0VMn-ree is emptyV1E
else
I
infoJfindZmin0root1E
printf0VMn -he Minimum :alue is:PdV,info1E
S
breakE
case @:
if0root JJ !//1
printf0VMn-ree is emptyV1E
else
I
infoJfindZma40root1E
printf0VMn -he Ma4imum :alue is:PdV,info1E
S
breakE
case ':
if0root JJ !//1
printf0VMn-ree is emptyV1E
else
printZlist0root1E
breakE
case *:
e4it0>1E
S
S
getch01E
S
Ex& No& > Duic9 Sort
ProgramB
Finclude Gstdio.hH
FincludeGconio.hH
int n,aK5>L,passJ%E void 6uicksort0int low, int high1 Iif0lowGhigh1 Iint k,iE kJpartition0low,high1E W?
http://vustudents.ning.com

http://vustudents.ning.com
printf0Vpass PdMnV,passRR1E
for0iJ%EiGJnEiRR1
printf0VP'dV,aKiL1E
printf0VMnV1E
6uicksort0low,k-%1E
6uicksort0kR%,high1E
S
S
int partition0int low,int high1
I
int v,i,tE
vJaKlowLE
iJlowE
do
I
while0aKiLGJv1
iRRE
while0aKhighLHv1
high--E
if0iGhigh1
I
tJaKiLE
aKiLJaKhighLE
aKhighLJtE
S
S
while0iGhigh1E
aKlowLJaK highLE
aKhighLJvE
return highE
S
void main01
I
int low,high,iE
clrscr01E
printf0V 7nter the array si<e MnV1E
scanf0VPdV,Qn1E
printf0V7nter the elements MnV1E
for0iJ%EiGJnEiRR1
scanf0VPdV,QaKiL1E lowJ%E highJnE 6uicksort0low,high1E getch01E S W@
http://vustudents.ning.com

http://vustudents.ning.com
Ex& No& ? Hea# Sort
ProgramB
FincludeGconio.hH
FincludeGstdio.hH
int 4K8>L,n,n%E
void heapsort01E
void adBust01E
void heapify01E
void main01
I
int iE
clrscr01E
printf0V7!-72 -37 !#. #; 7/7M7!-$ :V1E
scanf0VPdV,Qn1E
n%JnE
printf0O7!-72 -37 7/7M7!-$ MnN1E
for0iJ%EiGJnEiRR1
scanf0VPdV,Q4KiL1E
clrscr01E
printf0V Mn +22+D .7;#27 $#2- :V1E
for0iJ%EiGJnEiRR1
printf0VPdMtV,4KiL1E
heapsort01E
getch01E
S
void heapsort01
I
int i,t,BE
heapify01E
for0iJnEiHJ8Ei--1
I
tJ4KiLE
4KiLJ4K%LE
4K%LJtE adBust0%,i-%1E printf0VMnpass Pd MnV,n-0i-%11E for0BJ%EBGJn%EBRR1 printf0V PdMtV,4KBL 1E W'
http://vustudents.ning.com

http://vustudents.ning.com
S
S
void adBust0int i,int n1
I
int BE
int tE
BJ8UiE
tJ4KiLE
while0BGJn1
I
if0BGn QQ 4KBL G 4KBR%L1
BRRE
if0tHJ4KBL1
breakE
4KB/8LJ4K BLE
BJ8UBE
S
4KB/8LJtE
S
void heapify01
I
int i,BE
for0iJn/8EiHJ%Ei--1
adBust0i,n1E
S
Ex& No& 1@ De#t+ first searc+
ProgramB
%>. Crite a C program to implement the )epth ;irst $earch.
FincludeGconio.hH
FincludeGstdio.hH
int graphK%>LK%>LE
int visitedK%>LE
void Intili<eZ9raph0int noZv1
Iint i,BE for0iJ%EiGJnoZvEiRR1 //Intiali<e the 9raph IvisitedKiLJ>E for0BJ%EBGJnoZvEBRR1 graphKiLKBLJ>E W*
http://vustudents.ning.com

http://vustudents.ning.com
S
S
void printZgraph0int noZv1
I
int i,BE
printf0VMn-he 9raph0Matri4 2epresentation1:MnV1E
for0iJ%EiGJnoZvEiRR1
printf0VMt:PdV,i1E
for0iJ%EiGJnoZvEiRR1
I
printf0VMn:PdV,i1E
for0BJ%EBGJnoZvEBRR1
I
printf0VMtPdV,graphKiLKBL1E
S
S
S
void );$0int startZv,int noZv1
I
int iE
visitedKstartZvLJ%E
printf0VPd-- HV,startZv1E
for0iJ%EiGJnoZvEiRR1
I
if0iTJstartZv QQ visitedKiLJJ> QQ graphKstartZvLKiL JJ%1
I
);$0i,noZv1E
S
S
S
void main01
I
int noZv,noZeE
int sZv,eZv,startZvE
int i,BE
clrscr01E
printf0VMn7nter the !o of :ertices in the 9raph:V1E scanf0VPdV,QnoZv1E printf0V7nter the no of 7dges in the 9raph:V1E scanf0VPdV,QnoZe1E printf0VMn7nter the +dBacent vertices of each edgeV1E for0iJ%EiGJnoZeEiRR1 WW
http://vustudents.ning.com

http://vustudents.ning.com
I
printf0VMn7dge:Pd--H$tartZ: Q 7ndZ::V,i1E
scanf0VPd PdV,QsZv,QeZv1E
graphKsZvLKeZvLJ%E
graphKeZvLKsZvLJ%E
S
printZgraph0noZv1E
printf0VMn)epth ;irst $earch:Mn7nter the $tarting :erte4 for
$earching:V1E scanf0VPdV,QstartZv1E
printf0V)epth ;irst $earch -ree:MnV1E
);$0startZv,noZv1E
getch01E
S
Ex& No& 11 s+ortest #at+ of t+e gra#+
ProgramB
%%. Crite a C program to find the shortest path of a graph.
FincludeGconio.hH
FincludeGstdio.hH
int startZ:K8>L,endZ:K8>L,weightK8>LE
int noZv,noZeE
struct :erte4Info
I
int knownE
int distanceE
int prevZverte4E
Sverte4K8>LE
void Intili<eZ:erte4Info01
I
int i,BE
for0iJ%EiGJnoZvEiRR1 //Intiali<e the 9raph Iverte4KiL.knownJ>E verte4KiL.distanceJ%>>>E verte4KiL.prevZverte4J>E SS W&
http://vustudents.ning.com

http://vustudents.ning.com
void printZ(ath0int eZv1
I
int tempJeZvE
if0verte4KeZvL.prevZverte4JJ>1
printf0VMn!o path from $ource to 9iven )estinationTV1E
else
I
printf0VMn$hortest (ath:Pd V,eZv1E
while0verte4KeZvL.prevZverte4TJ>1
I
printf0VPd V,verte4KeZvL.prevZverte41E
eZvJverte4KeZvL .prevZverte4E
S
printf0VMn-he )istance is:PdV,verte4KtempL.distance1E
S
S
void main01
I
int sZv,eZv,startZvE
int i,BE
int v,w,inde4E
int min,6w,ne4tZvE
char chE
clrscr01E
printf0VMn7nter the !o of :ertices in the 9raph:V1E
scanf0VPdV,QnoZv1E
printf0V7nter the no of 7dges in the 9raph:V1E
scanf0VPdV,QnoZe1E
printf0VMn7nter the +dBacent vertices of each edgeV1E
for0iJ%EiGJnoZeEiRR1
I
printf0VMn7dge:Pd--H$tartZ: Q 7ndZ: Q Ceight:V,i1E
scanf0VPd Pd PdV,QstartZ:KiL,QendZ:KiL,QweightKiL1E
S
Intili<eZ:erte4Info0 1E printf0VMn7nter :ertices to find the $hortest (ath:V1E scanf0VPd PdV,QsZv,QeZv1E verte4KsZvL.distanceJ>E ne4tZvJsZvE &>
http://vustudents.ning.com

http://vustudents.ning.com
while0ne4tZv1
I
vJne4tZvE
verte4KvL.knownJ%E
for0iJ%EiGJnoZeEiRR1
I
if0startZ:KiLJJv1
I
wJendZ:KiLE
if0verte4KvL.distanceRweightKiL G verte4KwL.distance1
I
verte4KwL.distanceJverte4KvL.distanceRweightKiLE
verte4KwL.prevZverte4JvE
S
S
S
minJ%>>>E
for0BJ%EBGJnoZvEBRR1
I
if0verte4KBL.knownJJ> QQ minHverte4KBL.distance1
I
minJverte4K BL.distanceE
ne4tZvJBE
S
S
if0minJJ%>>>1
ne4tZvJ>E
S
printZ(ath0eZv1E
while0%1
I
printf0VMn)o you want shortest to one more destination:V1E
fflush0stdin1E
chJgetchar01E
if0chJJ]y] X chJJ]D]1
I
printf0VMn7nter the )estination :erte4:V1E scanf0VPdV,QeZv1E printZ(ath0eZv1E Selse breakE S &%
http://vustudents.ning.com

http://vustudents.ning.com
getch01E
S