PCD Practicals

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

PRACTI

CALSET-
1
PROGRAM-
1

AI
M:Pr
ogr
am t
oimpl
ementLexi
cal
Anal
yzer
.

i
nclude<st dio.h>
#i
ncl ude<st dl i
b.h>
#i
ncl ude<st ring.h>
#i
ncl ude<ct y pe.h>
#i
ncl ude<coni o.h>
i
ntisKey wor d(charbuf fer[]
){
charkey wor ds[ 32][10]={ "aut o" ,
"break","
case" ,
"char"
,"
const",
"conti
nue"
,"
def
aul
t"
,
"do","doubl e" ,
"else" ,
"enum" ,"
extern","
fl
oat",
"for
",
"goto"
,
"i
f","
int ",
"long","register",
"return"
,"short"
,"
signed",
"sizeof ","
stat i
c","struct",
"switch","
typedef",
"uni
on",
"unsi gned" ,"void" ,
"volati
le",
"while"};
i
nti , fl
ag=0;
for(i =0; i<32; ++i) {
if(strcmp( key wor ds[ i
],buffer )==0) {
f l
ag=1;
br eak;
}
}
retur nf lag;
}
i
ntmai n( ){
charch, buf fer[15], oper ators[ ]=" +-*/
%=" ;
FILE* fp;
i
nti ,j=0;
fp=f open( "a1.txt","r");
i
f(fp==NULL) {
pr intf("errorwhi leopeni ngt hef il
e\n");
exi t(0) ;
}
whi le((ch=f getc(fp) )!=EOF) {
f or(i =0; i<6; ++i ){
if(ch==oper at ors[i
])
pr i
nt f
("%ci soper ator\ n",ch);
}
if (
isalnum( ch) ){
buf fer[j++]=ch;
}
elsei f((ch==' '||ch==' \n')&&( j
!=0) ){
buf fer[j
]=' \ 0';
j =0;
if(isKey wor d(buf fer)==1)
printf("
%si skey wor d\n",buffer);
else
printf("
%si sindent ifier\n",buffer)
;
}}
fcl
ose(f
p);
ret
urn0;
getch(
);

OUTPUT:

PROGRAM-
2

AI
M:Pr
ogr
am t
ocountdi
git
s,v
owel
sandsy
mbol
sinC.

#include<stdi
o.h>
#include<coni
o.h>
voidmai n()
{
cl
rscr (
);
charline[
150];
inti,vowel
s,consonant
s,di
git
s,spaces;

v
owel
s=consonant
s=di
git
s=spaces=0;

pri
ntf
("Ent
erali
neofst
ri
ng:
");
scanf
("%[^
\n]
",l
i
ne)
;

f
or(i
=0;li
ne[
i]!
='\
0';++i)
{
i
f(
li
ne[i
]=='
a'||
line[
i]
=='
e'|
|li
ne[
i]=='i
'|
|
l
ine[
i]
=='o'|
|li
ne[i
]=='
u'|
|li
ne[
i]=='
A'||
l
ine[
i]
=='E'|
|li
ne[i
]=='
I
'||
li
ne[i
]=='O'|
|
l
ine[
i]
=='U'
)
{
++vowel s;
}
el
seif((l
ine[i
]>='a'
&&l
ine[
i]
<='
z'
)||
(li
ne[
i]
>='
A'
&&l
i
ne[
i]
<='
Z'
))
{
++consonant s;
}
el
seif(li
ne[i]
>='0'&&l
i
ne[i
]<='
9'
)
{
++digit
s;
}
el
seif( l
i
ne[ i
]=='')
{
++spaces;
}
}
pri
ntf(
"Vowels:%d",
vowels);
pri
ntf(
"\nConsonant
s:%d",consonants)
;
pri
ntf(
"\nDigi
ts:%d"
,di
git
s);
pri
ntf(
"\nWhit
espaces: %d",spaces)
;
getch(
);
}

OUTPUT:
PROGRAM-
3

AI
M:Pr
ogr
am t
ocheckv
ali
dat
ionofUser
nameandPasswor
dinC.

#incl ude<stdi
o.h>
#incl ude<conio.h>
#incl ude<stri
ng.h>
voidmai n()
{
cl
rscr (
);
charUser Name[ ]="kuldeep";
scanf (
"%s",&UserName) ;
printf("Pl
easeent eryourpasswor d:
\ n"
);
charPassWor d[]="12345" ;
scanf (
"%s",&PassWor d);
// if
..
.el
sest atementtot estift
heinputist
hecorr
ectusername.
if( UserName==" kuldeep")
{
if(PassWor d=="12345" ){
pr i
ntf(
"Welcome. \n"
);
}}
el se
{
pr i
ntf(
"Theusernameorpasswor dy ouenter
edi
sinval
id.\
n")
;
}
get ch();
}

OUTPUT:
PRACTI
CALSET-
2
PROGRAM-
1

AI
M:Pr
ogr
am t
oimpl
ementPr
edi
cti
vePar
singLL(
1)i
nC.

#incl
ude<stdio.h>
#incl
ude<conio.h>
#incl
ude<stri
ng. h>
voidmain()
{
charfi
n[10][
20],st[
10]
[20],
ft
[20]
[20]
,
fol
[20]
[20]
;
i
nta=0,e,i
,
t,
b,c,n,k,
l
=0,
j,
s,m,p;
cl
rscr(
);
printf("entertheno.ofcoor dinat
es\
n")
;
scanf ("%d" ,
&n);
printf("enterthepr oduct
ionsinagrammar
\n"
);
for(i=0;i<n;i
++)
scanf ("%s" ,
st[i
])
;
for(i=0;i<n;i
++)
fol[i]
[0]='\0'
;
for(s=0; s<n;s++)
{
for(i=0;i<n;i
++)
{
j
=3;
l
=0;
a=0;
l
1: i
f (
!((st[i
][
j]
>64)&&(st[
i]
[j
]<91))
)
{
for(m=0; m<l;m++)
{
i
f(ft [
i]
[m] ==st[i
][
j]
)
got os1;
}
ft[
i][l
]=st [
i]
[j
];
l
=l +1;
s1: j
=j+1;
}
else
{
i
f(s>0)
{
whi le(st[i]
[j
]!
=st[
a][0]
)
{
a++;
}
b=0;
whi le(ft[
a][b]!
='
\0')
{
for(m=0; m<l;m++)
{
i
f(ft [
i]
[m] ==ft[
a][
b])
got os2;
}
ft[
i][l
]=ft[a][
b];
l
=l +1;
s2: b=b+1;
}
}
}
whi le(st[i]
[j
]!
='\
0')
{
i
f(st [i
][
j]=='|
')
{
j
=j +1;
got ol 1;
}
j
=j +1;
}
ft[
i][l
]=' \0';
}
}
printf ("fi
r stpos\ n");
for(i=0; i<n; i
++)
printf ("FIRS[ %c] =%s\ n",
st[i
][
0],
ft
[i
])
;
fol[0][0] ='$';
for(i=0; i<n; i
++)
{
k=0;
j
=3;
i
f(i==0)
l
=1;
else
l
=0;
k1:whi le( (st[
i][0]!=st [
k][
j])
&&(k<n)
)
{
i
f(st [k][j]
==' \0')
{
k++;
j
=2;
}
j
++;
}
j
=j +1;
i
f(st [i
][0] ==st [k][j-
1])
{
i
f((st [k][j]!
='|'
)&&( st[k]
[j]
!='
\0'
))
{
a=0;
i
f(!((st [k][j]
>64) &&( st[k]
[j]
<91))
)
{
for(m=0; m<l ;m++)
{
i
f(fol [i
][m] ==st [k][j
])
got oq3;
}
fol[i
][l]=st [k][
j];
l
++;
q3:
}
else
{
whi le( st[k][j
]!=st [a][
0])
{
a++;
}
p=0;
whi le(ft[
a] [
p]!='
\0'
)
{
i
f(ft [
a][p]!='@')
{
for(m=0; m<l ;m++)
{
i
f(fol [
i]
[m] ==f t[
a][
p])
got oq2;
}
fol[i]
[l
]=ft[a] [
p];
l
=l +1;
}
else
e=1;
q2: p++;
}
i
f(e==1)
{
e=0;
got oa1;
}
}
}
else
{
a1: c=0;
a=0;
whi le(st[k][0]!
=st[
a][
0])
{
a++;
}
whi le((fol[a][
c]!
='\0'
)&&(
st[
a][
0]!
=st
[i
][
0])
)
{
for(m=0; m<l ;m++)
{
i
f(fol [
i]
[m] ==f ol
[a]
[c]
)
got oq1;
}
fol[i]
[l
]=fol [a]
[c]
;
l
++;
q1: c++;
}
}
got ok1;
}
fol[i]
[l
]='\0';
}
printf
("followpos\ n");
for(i
=0; i
<n;i++)
printf
("FOLLOW[ %c] =%s\n",
st[
i][
0],
fol[
i]
);
printf
("\n" )
;
s=0;
for(i
=0; i
<n;i++)
{
j
=3;
whi l
e(st[i][
j]
!='\
0')
{
i
f((st[
i][j
-1]=='|'
)|
|(
j==3))
{
for(p=0;p<=2; p++)
{
fi
n[s][p]=st[i][
p];
}
t=j;
for(p=3;((st[i]
[j
]!
='|
')
&&( st[
i]
[j
]!
='
\ 0'
));
p++)
{
fi
n[s][p]=st[i][
j]
;
j
++;
}
fi
n[s][p]='\0';
i
f(st[i
][k]=='@')
{
b=0;
a=0;
whi l
e(st[a][0]!
=st[i
][0])
{
a++;
}
whi l
e(fol[a][b]!
='
\0')
{
printf
("M[ %c, %c]=%s\ n",
st[
i]
[0]
,fol
[a][
b],
fi
n[s]
);
b++;
}
}
elseif(!((st[
i][
t]
>64) &&(st[
i]
[t
]<91)))
printf
("M[ %c, %c]=%s\ n",
st[
i]
[0]
,st[
i]
[t]
,
fin[
s]);
else
{
b=0;
a=0;
whi l
e(st[a][0]!
=st[i
][3])
{
a++;
}
whi l
e(ft[a][
b] !
='\
0')
{
pri
ntf(
"M[ %c,%c]
=%s\
n",
st[
i]
[0]
,
ft[
a][
b],
fi
n[s]
);
b++;
}
}
s++;
}
i
f(st[
i]
[j
]=='|
'
)
j
++;
}
}
getch()
;
}

OUTPUT:
PROGRAM-
2

AI
M:Pr
ogr
am t
oimpl
ementRecur
siv
eDecentPar
singi
nC.

#include<st dio.h>
#include<coni o.h>
i
ntc=0;
charp[ 20];
voids( );
voidl();
voidlprime( );
voidl()
{
s();
l
pr ime();
}
voidlprime( )
{
i
f(p[c]==',
')
{
c++;
s();
l
pr ime();
}
}
voids( )
{
i
f(p[c]=='a'
)
c++;
elseif(p[c]=='('
)
{
c++;
l
();
i
f(p[c]==')'
)
c++;
else
c--;
}
else
printf
("\nInvalidExpressi
on")
;
}
voidmai n()
{
cl
r scr(
);
printf
("\nImpl ementati
onofRECURSIVEDESCENTPARSER\
n")
;
printf
("\nEnt ertheExpressi
on:\
n")
;
scanf ("%s" ,
p);
s();
i
f(p[c]=='$'
)
pri
nt f
("\nTheSt
ri
ngi
saccepted")
;
el
se
pri
nt f
("\nThest
ri
ngi
srej
ected")
;
getch( )
;
}

OUTPUT:

Pr
act
ical
Set
-3
Pr
ogr
am-
1

AI
M:Pr
ogr
am t
oimpl
ementOper
atorPr
ecedencePar
singi
nC.

#i
ncl
ude<i
ost
ream.
h>
#i
ncl
ude<coni
o.h>
#i
ncl
ude<st
dli
b.h>
st
ructnode
{
charsy
mbol
;
st
ructnode*
lef
t;
st
ructnode*
right
;
}
;
t
ypedefst
ructnodenode;
st
ructst
ack
{
charop;
node*
op_
poi
nter
;
}
;
t
ypedefst
ructst
ackst
ack;
i
ntTOS=-
1;
st
acks[
10]
;
/
*Thi
sist
heoper
atorpr
ecedencet
abl
est
oredasi
tisi
nthe
f
orm ofmat
ri
xandoper
ator
sar
eassi
gnedv
aluesasf
oll
ows:
NULL=0,
Equal
(=)=1,
lesst
han(
<)=2,
great
ert
han(
>)=3.*
/
/
/ +,
*,
(,
),
<>,
-
,/,
^
i
ntm[
8][
8]={{
3,2,
2,
3,
3,
3,
2,
2}, /
/+
{
3,3,
2,
3,
3,
3,
2,
2}, /
/*
{
2,2,
2,
1,
0,
2,
2,
2}, /
/(
{
3,3,
0,
3,
3,
3,
3,
3}, /
/)
{
2,2,
2,
0,
1,
2,
2,
2}, /
/><
{
3,2,
2,
3,
3,
3,
2,
2}, /
/-
{
3,3,
3,
3,
3,
3,
3,
2}, /
//
{
3,3,
3,
3,
3,
3,
3,
2}}
; /
/^
v
oidmai
n()
{
cl
rscr
();
i
ntcomp(
char)
;
v
oidpush(
char
);
v
oidpop(
);
v
oiddi
spl
ay(
node*
);
node*
temp;
charst
r[
20]
;
i
nti
=0;
cout<<"
Ent
ert
hest
ri
ng:
";
ci
n>>st
r;
push(
'<'
);
i
++;
whi
l
e(st
r[
i]
!='
\0'
)
{
i
f(
(st
r[
i]
>='
a'
&&st
r[
i]
<='
z'
))
{
t
emp=newnode;
t
emp-
>sy
mbol
=st
r[
i]
;
t
emp-
>lef
t=NULL;
t
emp-
>ri
ght
=NULL;
s[
TOS]
.op_
poi
nter=t
emp;
}
el
se
{
i
ntp_
index
,q_
index;
p_
index=comp(
s[TOS]
.op)
;
q_
index=comp(
str
[i
])
;
whi
l
e(m[
p_i
ndex
][q_
index]
==3)
{
t
emp=newnode;
t
emp-
>sy
mbol
=s[
TOS]
.op;
t
emp-
>lef
t=s[
TOS-
1].
op_
poi
nter
;
t
emp-
>ri
ght
=s[
TOS]
.op_
poi
nter
;
pop(
);
s[
TOS]
.op_
poi
nter
=temp;
p_
index=comp(
s[TOS]
.op)
;
q_
index=comp(
str
[i
])
;
}
i
f(
m[p_
index]
[q_
index]
==2)
{
push(
str
[i
])
;
}
i
f(
m[p_
index]
[q_
index]
==1)
{
i
f(
comp(
s[TOS]
.op)
==4)
br
eak;
i
f(
comp(
s[TOS]
.op)
==2)
{
t
emp=s[
TOS]
.op_
poi
nter
;
pop(
);
s[
TOS]
.op_
poi
nter
=temp;
}
}
i
f(
m[p_
index]
[q_
index]
==0)
{
cout<<"
Inv
ali
dst
ri
ng.
";
get
ch(
);
exi
t(
1);
}
}
i
++;
}
di
spl
ay(
s[TOS]
.op_
poi
nter
);
get
ch(
);
}
/
/funct
iont
ogett
hei
ndexoft
heoper
atort
hatcomesi
ntheTOS
/
/andal
sof
ort
hecur
rentoper
atort
hatcomei
nthest
ri
ng.
i
ntcomp(
charx)
{
i
nty
;
swi
tch(
x)
{
case'
+'
:
y
=0;
br
eak;
case'
*'
:
y
=1;
br
eak;
case'
('
:
y
=2;
br
eak;
case'
)'
:
y
=3;
br
eak;
case'
>'
:
case'
<'
:
y
=4;
br
eak;
case'
-
':
y
=5;
br
eak;
case'
/'
:
y
=6;
br
eak;
case'
^'
:
y
=7;
br
eak;
}
r
etur
ny;
}
v
oidpush(
charx)
{
TOS++;
s[
TOS]
.op=x;
}
v
oidpop(
)
{
TOS-
-;
}
v
oiddi
spl
ay(
node*
s)
{
i
f(
s==NULL)
r
etur
n;
i
f(
s->l
eft
!=NULL)
di
spl
ay(
s->l
eft
);
i
f(
s->r
ight
!=NULL)
di
spl
ay(
s->r
ight
);
cout<<s-
>sy
mbol
;
}
Out
put
:

PROGRAM-
2

AI
M:Pr
ogr
am t
oimpl
ementLALRPar
singi
nC.

#i
ncl
ude<st
dio.
h>
#i
ncl
ude<st
ri
ng.h>
voidmai n( )
{
chart able[20] [
20][20] ,
ter[20],
stack[20],
ip[20]
,st
1[20],
pro[
20]
[20]
,
num;
i
nti ,j
,t,
k,top=0, st,
col ,
row, pop,np,no,l
en;
printf("Entert henoofpr oductions:")
;
scanf ("
%d" ,
&np) ;
printf("Entert hepr oduct i
ons:");
for(i=0;i<np;i++)
{
scanf ("
%s" ,
pr o[i
]);
}
printf("Entert heno. ofst ates:
");
scanf ("
%d" ,
&st );
printf("Entert hest at es:");
scanf ("
%s" ,
st 1);
printf("Entert henooft er minals:"
);
scanf ("
%d" ,
&t );
printf("Entert het ermi nals:");
scanf ("
%s" ,
ter )
;
for(i=0;i<st;i
++)
{
for(j=0; j
<t;
j++)
{
printf("
\nEnt ert hev aluef or%c%c: "
,st1[i
],
ter
[j
]);
scanf ("%s" ,
table[i]
[j]
);
}
}
printf("\nLALRTABLE: \n");
for(i=0;i<t;
i++)
{
printf("\t
%c" ,t
er [
i])
;
}
for(i=0;i<st;i
++)
{
pr i
nt f(
"\n\n%c" ,
st1[i]);
for(j=0; j
<t;
j++)
{
printf("
\t%s" ,t
abl e[i]
[j
]);
}
}
stack[ top]='$';top++;
stack[ top]='0';
printf("\nEnt erthei nputst ri
ng:")
;
scanf ("
%s" ,
ip) ;
i
=0;
printf("\n\nSTACK\ t
\tINPUTSTRI NG\t\tACTION\ n"
);
printf("\n%s\ t\t%s\ t\t",
stack,i
p) ;
whi l
e(i
<=st rl
en( ip))
{
for(j
=0;j<st ;j
++)
{
if(
stack[ top] ==st 1[j]
)
col=j;
}
for(j
=0;j<t ;
j++)
{
if(
ip[i
]==t er[j])
{
row=j ;
}
}
i
f((stack[ top]==' 1')&&(ip[i]
=='$'
))
{
printf
("\ nStr i
ngaccept ed");
break;
}
el
sei f(t
abl e[col ][
row] [0]=='s'
)
{
top++;
stack[top] =t er[row] ;
top++;
stack[top] =t able[col ]
[row][1];
i++;
printf
("Shi ft%c%c\ n",
ter[r
ow] ,
tabl
e[col
][
row]
[1]
);
}
elseif(tabl e[col ]
[row] [
0]=='r'
)
{
no=( i
nt )table[ col][
row] [1]
;
no=no- 49;
len=strlen( pr o[no] )
;
len=len- 3;
pop=2* len;
printf
("POP%d" ,
pop) ;
for(j
=0; j
<pop; j++)
{
top=t op- 1;
}
top++;
stack[top] =pr o[no] [0];
k=top;
k=k-1;
printf
("Push[ %c, "
,pro[no][
0]);
for(j
=0; j
<st ;j
++)
{
if(stack[ k]==st1[j])
{
col=j ;
}
}
k++;
for (
j=0; j
<t;j
++)
{
i
f(stack[ k]==ter [
j])
{
row=j ;
}
}
top++;
stack[ t
op] =table[col ]
[r
ow][0]
;
print f("
%c] \n",t
abl e[col]
[r
ow][0]
);
}
else{ printf
("\nEr r
or \nThest ri
ngnotaccept
ed.
")
;br
eak;
}
pri
nt f("\n");
for(j
=0; j<=top;j++)
{
printf("%c" ,
stack[ j
]);
}
pri
nt f("\t\t
");
for(j
=i ;
j<strl
en( ip);
j++)
{
printf("%c" ,
ip[j]
);
}
pri
nt f("\t\t
");
}
}

OUTPUT:
AI
M:-ToStudyaboutLexi
cal
Anal
yzerGener
ator
(LEX)andFl
ex(
Fast
Lexi
cal
Analyzer
)

Lex-ALexi
cal
Anal
yzerGener
ator
:-

Lexi saprogram gener atordesignedforlexi


calprocessingofcharacterinput
streams.Itacceptsahi gh-lev
el,probl
em or i
ent
edspeci fi
cati
onforchar act
er
stri
ngmat ching,andpr oducesapr ogram inagener alpurposel
anguagewhi ch
recognizesregularexpressions.Theregularexpressionsarespecifi
edbyt heuser
i
nt hesour cespecifi
cationsgiventoLex.TheLexwr itt
encoderecogni zesthese
expressionsinani nputst r
eam andpar t
it
ionstheinputst r
eam i
ntostrings
mat chi
ngt heexpressions.

Thegr ammari ntheabov edi agram isat extfi


leyoucreatewithat extedt i
or.Yacc
wil
lready ourgrammarandgener at
eCcodef orasy nt
axanal yzerorpar ser
.The
synt
axanal yzerusesgrammarr ulesthatallowittoanalyzetokensf rom thelexi
cal
anal
y zerandcreateasy ntaxt ree.Thesy ntaxtreeimposesahi erarchicalstr
ucture
thet
okens.Forexampl e, oper atorprecedenceandassoci ati
vit
yar eappar entinthe
synt
axt ree.Thenextst
ep, codegener ation,doesadept h-f
ir
stLexical Analyzer
Synt
axAnaly
zera=b+c*di d1=id2+id3*id4=+*i d1sourcecodet okenssynt
ax
tr
eeid2id3i
d4loadi
d3muli
d4addid2stor
ei d1CodeGeneratorgeneratedcode
LexYaccpat
ter
nsgrammar5walkoft
hesyntaxtreetogeneratecode.Some
compil
erspr
oducemachi
necode,
whil
eothers,asshownabov e,out
putassembly
l
anguage.

Whati
sFl
ex?
 Fl
exi
sapower
ful
,opensour
ceappl
i
cat
ionf
ramewor
kwhi
chal
l
owst
obui
l
dtr
adi
ti
onal
appl
i
cat
ionsf
orbr
owser
,mobi
l
eanddeskt
opusi
ngt
hesamepr
ogr
ammi
ngmodel
,tool
,
andcodebase.

 Fl
expr
ovi
desFLEXSDKconsi
sti
ngoft
heFl
excl
assl
i
brar
y(Act
ionScr
iptcl
asses)
,the
Fl
excompi
l
ers,t
hedebugger
,theMXMLandAct
ionScr
iptpr
ogr
ammi
ngl
anguages,and
ot
herut
il
it
iest
obui
l
dexpr
essi
veandi
nter
act
iver
ichi
nter
netappl
i
cat
ions(
RIA)

 Fl
ext
akescar
eoft
heuseri
nter
face(
UI)ort
hecl
i
ent
-si
def
unct
ional
i
tyofaweb
appl
i
cat
ion.Ser
ver
-si
def
unct
ional
i
tydependentonser
ver
-si
decomponent
swr
it
teni
na
t
radi
ti
onal
scr
ipt
ingl
anguage

Howt
ouseFLEX?

FLEX( FastLEXicalanalyzergenerat
or)isatoolforgenerat
ingscanners.Inst
eadof
writ
ingascannerf r
om scr atch,y
ouonl yneedtoidentif
ythevocabul
aryofacer tai
n
l
anguage( e.g.
Simple),wri
teaspeci f
icati
onofpat t
ernsusingregularexpr
essions(e.
g.DIGIT[0-
9])
,andFLEXwi l
lconstructascannerf oryou.FLEXisgenerall
yusedint hemanner
depict
edher e:

Fi
r st
,FLEXreadsaspeci f
icat
ionofascannereit
herfr
om aninputf i
le*.
lex,orfr
om
standardi
nput,anditgenerat
esasout putaCsourcefi
lelex.
yy.
c.Then, l
ex.yy.
cis
compi l
edandlinkedwiththe"-l
fl
"li
brar
ytoproduceanexecutablea.out
.Finall
y,a.
out
analyzesi
tsinputstr
eam andt r
ansformsiti
ntoasequenceoft okens.

*.
lexi
sinthef or
m ofpair
sofregul
arexpressi
onsandCcode.(
sample1.
lex,
sample2.
lex)
l
ex.yy
.cdefinesarout
ineyyl
ex()t
hatusesthespeci
fi
cat
iont
orecogni
zetokens.
outi
a. sact
ual
l
ythescanner
!

Howt
oCompi
l
e&RunLEX/YACCPr
ogr
amsonWi
ndows?
I
fyouareinst
all
ingUbuntu( oranyLinuxbasedOS)ony oursystem ei
thert
hrough
Vir
tual
Boxorbymaki ngy oursystem Mult
i-
Bootabl
e,j
usttoexecuteyourLex&
Yaccprogr
ams;theny oumi ghtbewastingyourHDDspace&y ourval
uableti
me.
Youcaneasil
yskipthisannoy i
ngprocessandrunyourprogramsinWi ndowsOS
wit
houtanyhassles.

Her
e'showy
oucandoi
t:

I
nst
all
i
ngSof
twar
es:
1. Downl oadFlex2. 5.4a
2. Downl oadBi son2.4.1
3. Downl oadDev C++
4. Inst
allFlexat" C:\
GnuWi n32"
5. Inst
allBisonat" C:\GnuWin32"
6. Inst
allDev C++at" C:\Dev-
Cpp"
7. OpenEnv i
ronmentVar i
ables.
8. Add" C:\GnuWi n32\bin;
C:\Dev-
Cpp\
bin;
"topat
h.

Compi
l
ati
on&Execut
ionofy
ourPr
ogr
am:

1. OpenCommandpr omptandswi tchtoyourwor kingdi


rect
ory
whereyouhav est
oredy ourlexfil
e(".
l"
)andy accf i
le("
.y")
2. Lety ourlexandy accf i
lesbe"hell
o.l
"and" hell
o.y
".Now,
fol
l
owthepr ecedi
ngstepst ocompi l
eandr uny ourprogram.
1. ForCompi l
ingLexf i
leonly:
1. f l
exhel lo.
l
2. gccl ex.yy
.c
2. ForCompi l
ingLex&Yaccf il
eboth:
1. f l
exhel lo.
l
2. bi son- dyhell
o.y
3. gccl ex.yy
.cy.t
ab.c
3. ForExecut ingtheProgram
1. a. exe
AI
M:-CreateaLexert
otakeinputf
rom t
extf
il
eandcountnoof
charact
ers,
no.ofl
ines&no.

CODE

%{

#i
ncl
ude<st
dio.
h>

i
ntl
i
nes=0,
wor
ds=0,
s_l
ett
ers=0,
c_l
ett
ers=0,
num=0,
spl
_char
=0,
tot
al=0;

%}

%%

\
n{l
i
nes++;

wor
ds++;
}[\
t''
]

wor
ds++;

[
A-Z]

c_
let
ter
s++;
[a-
z]

s_
let
ter
s++;[
0-

9]num++;

.spl
_char
++;

%%

mai
n(v
oid)

y
yin=f
open(
"p6.
txt
",
"r
");

y
ylex(
);

t
otal
=s_
let
ter
s+c_
let
ter
s+num+spl
_c

har
;pr
int
f("Thi
sFi
l
econt
ains.
..
")
;

pr
int
f("
\n\
t%dl
i
nes"
,li
nes)
;

pr
int
f("
\n\
t%dwor
ds"
,wor
ds)
;

pr
int
f("
\n\
t%dsmal
ll
ett
ers"
,

s_
let
ter
s);
pri
ntf
("\
n\t
%dcapi
tal

l
ett
ers"
,c_
let
ter
s);
pri
ntf
("\
n\t
%d
di
git
s",
num)
;
pr
int
f("
\n\
t%dspeci
al

char
act
ers"
,spl
_char
);pr
int
f("
\n\
tInt
otal

%dchar
act
ers.
\n"
,t
otal
);

i
nty
ywr
ap(
)

r
etur
n(1)
;

TEXTFI
LE

Hi
im pr
agnesh

hi
im

har
dik786@gmai
l
.com hi
i

mv
ikash

OUTPUT:
-
AI
M:-Wr
it
eaLexprogram t
ocountnumberofv
owel
sandconsonant
sin
agiv
eni
nputstr
ing.

CODE:
-

%{

i
ntv
ow_
count
=0;

i
ntconst
_count

=0;

%}

%%

[
aei
ouAEI
OU]

{
vow_
count
++;
}[a-
zA-
Z]

{
const
_count
++;
}

%%

mai
n()

y
yin=f
open(
"C:
\p6.
txt
",
"r
");

y
ylex(
);

pr
int
f("
Thenumberofv
owel
sar
e:%d\
n",
vow_
count
);

pr
int
f("
Thenumberofconsonant
sar
e:%d\
n",
const
_count
);

r
etur
n0;

y
ywr
ap(
)

r
etur
n1;

TEXTFI
LE:
-
Hi
im pr
agnesh

hi
im

har
dikgmai
l
com hi
i

mv
ikash

OUTPUT:
-
AI
M:-Wr
it
eaLexpr
ogr
am t
opr
intoutal
lnumber
sfr
om t
hegi
venf
il
e.

CODE:
-
%{
#i
ncl
ude<st
dio.
h>i
ntnum=0;
%}
%%
[
0-9]num++;
ECHO;
%%
mai
n(v
oid)
{
y
yin=fopen(
"C:
\p6.
txt
",
"r
");
y
ylex(
);
pr
int
f("
\n\
t%ddi
git
s",
num)
;
}
i
nty
ywr
ap(
)
{
r
etur
n(1)
;
}

OUTPUT:
-
AI
M:-I
mpl
ementf
oll
owi
ngpr
ogr
amsusi
ngLex.
2)Wr
it
eaLexpr
ogr
am t
opr
int
outal
lHTMLt
agsi
nfi
l
e.

Pr
ogram:
Pr
a7b.l
%{

i
nti
=0;

%}

%%

[
a-zA-
Z]+{
pri
ntf
("%d:
%s"
,i
,
yyt
ext
);
i++;
}

%%

mai
n()

ext
ernFI
LE*yyi
n;
yyi
n=f
open(
"new.t
xt"
,"
r"
);
yyl
ex(
);

y
ywr
ap(
)

r
etur
n(1)
;

New.
txt
<ht
ml>

<head
>
HELLO

</
head>

<body
>

</
body
>

</
html
>

Out
put
:-
AI
M:I
mpl
ementf
oll
owi
ngpr
ogr
amsusi
ngLex.
2)Wri
teaLexprogr
am whichaddsli
nenumberst
othegi
venf
il
eand
di
splayt
hesameontothestandar
doutput
.
Pr ogram:
%{
intlines=1;
%}
LINE\ n
%%
{LINE}{ ECHO;pri
ntf(
"%d",
li
nes++)
;}
%%
mai n()
{yy i
n=f open("j
b.t
xt"
,"
r"
);
printf(
"%d",
li
nes++);
yylex();
return0;
}
i
nty ywrap()
{
return1;
}

Out
put
:
AI
M:Wri
teaLexprogr
am t
ocountthenumberofcommentl
inesi
na
giv
enCprogram.Al
soel
iminatet
hem andcopyt
hatpr
ogram i
nto
separ
atef
il
e.

Pr
ogr
am:

%{#include<st dio.
h>intcom=0;
%}
%sCOMMENT
%%
"/*
"{BEGI NCOMMENT; }
<COMMENT>" */"{ BEGIN0;com++;}
<COMMENT>\ n{ com++; }
<COMMENT>.{ ;}
\/\/
.*{ ;com++; }
.|
\n{fprintf(
yyout ,"%s",
yyt
ext);
}
%%
i
ntmai n(i
ntar gc, char*argv[
])
{
i
f(argc!=3)
{
pri
ntf("usage: .
/a.outin.t
xt
out.
txt\n");exit(
0) ;
}
yyi
n=f open(argv [1],"
r"
);
yyout=fopen( argv [2]
,"
w")
;yyl
ex( );
pri
ntf("\nnumberofcomment sar
e=%d\
n",
com)
;
}
i
nty ywr ap()
{
ret
urn1;
}

OUT.
txt
#i
ncl
ude<st
dio.
h>
i
ntmai n()
{
i
nta,b,c;
pri
ntf(
“entertwo
number s”)
;scanf(“
%d
%d” ,
&a,&b);c=a+b;
pri
ntf(
“sum is
%d”,c);ret
urn0;
}

Out
put
:
AI
M:-ToSt
udyaboutYetAnot
herCompi
l
er-
Compi
l
er(
YACC)
.

Yacc( YetAnotherCompi l
er-
Compiler)i
sacomput erpr ogram fortheUnixoper ati
ng
system.I ti
saLookAheadLef t
-t
o-Right(LALR)par sergenerator,gener
atingapar ser
,
thepar tofacompilerthatt
ri
estomakesy ntacti
csenseoft hesour cecode,
specifical
lyaLALRpar ser
,basedonananal y
ticgrammarwr itt
eni nanotation
similartoBackus–NaurFor m(BNF) .
Yacci tsel
fusedt obeav ai
lableasthedef ault
parsergeneratoronmostUni xsystems, t
houghi thassi ncebeensuppl anted[
citat
ion
needed]ast hedefaultbymorerecent,largelycompat i
ble,pr
ogr ams.

St
ruct
ureofaYACCsour
cepr
ogr
am:
AYACCsour ceprogram isst
ruct
urall
ysimil
artoa
LEXone.declarat
ions
%%
rules
%%
routi
nes
Thedeclarat
ionsecti
onmaybeempt y.Moreover,i
fther
outi
nessecti
onis
omi t
ted,
thesecond%%mar kmaybeomi t
tedalso.
Blanks,t
abs,andnewlinesar
eignoredexceptt
hatt heymaynotappeari
nnames.

THEDECLARATI
ONSSECTI
ONmaycont
aint
hef
oll
owi
ngi
tems:
Declar
ati
onsoft okens.Yaccrequi
restokennamest
obedecl
aredassuchusi
ngt
he
keyword
%token.
Declar
ati
onoft hestartsymbolusingthekeywor
d
%startCdeclarati
ons:incl
udedfil
es,global
vari
abl
es,types.
Ccodebet ween%{and%} .

RULESSECTI
ON:
Arulehast heform:
nonter
mi nal:sentent
ialfor
m
|sententi
alform
.
...
...
..
..
..
..
..
|sententi
alform
;
Acti
onsmaybeassoci at
edwit
hrul
esandar
eexecut
edwhent
heassoci
ated
sent
entialformismat ched.

LEXCODE:
%{
#include
<stdli
b.h>
#include" y.
tab.h"
%}
%%
("
hi"|
"oi")"
\n" {r et
urnHI;
}
("
tchau" |"
bye")"
\n"{retur
nBYE;
}
. {yyerr
or();
}
%%
i
ntmai n(voi
d)
{
y y
par se()
; r
eturn0;
}
i
nty ywr ap(voi
d)
{
return0;
}
i
nty yerror(v
oid)
{
pri
ntf("Err
or\n")
;
exit(
1) ;
}

YACC:

%t
okenHIBYE
%%
hiby
e
;
hi
:
HI {pr
int
f("
Hel
l
oWor
ld\
n")
;}
;
by
e:
BYE {pr
int
f("
ByeWor
ld\
n")
;exi
t(
0);
}
;
Out
put
:

AI
M:Cr
eateYaccandLexspeci
fi
cati
onfi
lest
orecogni
zes
ar
it
hmeti
cexpressi
onsi
nvol
ving+,
-,*and/.

Pr
ogr
am:

%{
#i
nclude<stdi
o.
h>
#i
nclude"y.
tab.
h
" ext er
n i nt
yy
lval
;
%}

%%
[0-
9] +{
y y
lval
=at
oi(y
ytex
t)
; r
etur
nNUM;
}
[\t
];
\nr eturn0;
.returny yt
ext
[0]
;
%%
yywr ap()
{
return(1);
}
%{
#include<st
dio.
h>
%}
%tokenNUM
%lef t'+' '
-'
%lef t'*' '
/'
%lef t'('')'
%%
expr :e{
pr intf(
"result:
%d\
n",
$$)
;
ret urn0;
}
e:e'+'e{ $$=$1+$3; }
|e'-'
e{ $$=$1- $3;}
|e'*'e{ $$=$1* $3;
}
|e'/'
e{ $$=$1/ $3;}
|'
('e')'{$$=$2; }
|NUM { $$=$1; }
;
%%

main()
{
pri
ntf(
"\nenterthearithematic
expression:
\n"
);yyparse();
pri
ntf(
"\nval
idexpression\n");
}
yy
error()
{
pri
ntf(
"\ninval
idexpression\n")
;
exit
(0);
}

Out
put
:
AI
M:-CreateYaccandLexspeci
fi
cati
onf i
l
esareusedt
ogenerat
ea
calcul
atorwhi
chaccept
s,i
ntegerandfl
oatt
ypeargument
s.

PROGRAM:

/
/cal
c.l
%{
#include" y
.tab.h"
#def ineYYSTYPE
doubl eex t
er n
YYSTYPEy ylval;
%}
%%
[0-
9] +|[
0-9]*
\ .
[0-9]
+{
yylval =
atof(y yt
ext)
; r
eturn
NUMBER;
}
[\t]+{ ;
}
.{returny yt
ext [
0];
}
\n{ r
et urn0;}
%%
i
nty ywr ap(
)
{retur n1;
}

/
/cal
c.y
%{
#i
ncl
ude<st
dio.
h
>
#i
ncl
ude<st
dli
b.
h>

#defi
neYYSTYPE
doubleextern
YYSTYPEy y
lval
;
i
ntyyl
ex();
i
ntyyerr
or()
;
i
ntresult
=0,fl
ag=0;
%}

%t
okenNUMBER
%l
eft'
+''
-'
%l
eft'
*''
/'

%%
stmt: expr{pr i
ntf(
"\n\nResult=
%f ",
$1) ;
};expr:expr'+'
expr{$$=$1+$3;
}
|
expr '
-'
expr { $$=$1- $3;}
|
expr '
*'expr { $$=$1* $3;
}
|
expr '
/'expr
{i
f($3==0)f lag=1;
else
$$=$1/ $3;}
|
'('
expr '
)'{
$$=$2; }
|
NUMBER;
%%

i
ntmai
n()
{
pri
ntf(
"EntertheAri
thmet
icExpr
essi
on:
");
if(
fl
ag!=1)
{
yyparse(
);
}
retur
n1;
}

i
nty
yer
ror
()
{
pri
ntf(
"Inval
i
dArit
hmet i
c
Expression\
n\n"
);exi
t(
0);
}
OUTPUT:
00

You might also like