CD Lab File

You might also like

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

Ac

cur
ateIns
tit
uteofManag
ementandTec
hno
log
y
Gr
eaterNoi
da,Ut
tarPr
adesh

De
par
tme
nto
fCo
mput
erSc
ienc
eandEng
ine
eri
ng

Se
ssi
on2020-
21(
OddSe
mes
ter
)

B.
Tec 5TH SEMESTER)
hCSE(

Co
mpi
lerDe
sinLa
g b(
KCS-
552)

SubmittedTo : Submit
tedBy:
Ms.Shahi naAnjum Name:
Assi
stantPr of
e s
sor Rol
lNo:182251
0
CSEDe part
me nt Se
ctio
n:
INDEX
SNO LISTOF DATEOF DATEOF SIGNATURE REMARK
. EXPERIMENT EXPERIMENT SUBMISSIO
N
1. Wr itea
pro grami nCt o
i
mpl e me nt
Le xi
c al
Anal yze rand
i
de nt i
f yt okens
froman
arithme tic
expr ession.
2. Toc he c k
whe the rt he
ent ereds tr
ing
i
sani de nti
fier
ork eywo rd.
3.  
Tor e mo veLe f
t
Re cur si
o nf r
om
Gr ammar .
4. Toi mpl eme nt
Shi f
tRe duce
Par ser.
5. Wr itea
pro grami nC
i
mpl e me nt
Ope rat or
Pr ecede nc e
Par ser.
6. WAPi nCt o
i
mpl e me nt
Re cur si
ve
De centPar ser.
7. Wr itea
pro gramt of i
nd
fi
r st.
8. Wr itea
pro grami nCt o
dol ef t
fac t
o ring .
9. Impl e me ntati
on
ofl exical
analys e rfor
given
arithme tic
expr ession.
Ex
per
ime
nt1
Object
ive-Wri
teaprogr
ami
nCt
oimpl
eme
ntLe
xic
alAnal
yze
randi
dent
ifyt
oke
nsf
roman
ar
ithmeti
cexpr
ess
ion.

Bri
efThe o
ry-Le xicalAnalysis
 i
st hef i
rstphaseofcompil
eral
sokno
wnasscanne
r.It
co
nvertsthei nputpr ogrami ntoas eque nceofTokens.
ACpr ogramc o nsi
stso fvarioustok ensandat okeniseit
herakeywor
d,ani
denti
fi
er,a
co
nstant,as tringlit
e r
al,oras ymb ol
.
Example
-Ke ywo rds:f or,while,ifet c.
Ide ntif
ier:Variablename ,funct
ionnamee tc
.
Ope rators:' +'
,' ++',' -
'e tc.
Se parators:','' ;
'e tc.

Procedure-
-Starttheprogram.
-InputAr i
thmeti
ce xpr
essi
on.
-Identif
yt hetokens.
-Pri
ntTo kensands peci
alchar
act
ers
.
-Endt heprogram.

Pro
g r
am-
#i
nclude <stdio .
h>
i
ntmai n()
{
i
nti =0, j
=0, ne =1,k=0;
charo p[1 00], key[1 00], c;
while(1)
{
scanf("%c ", &c );
i
f (
c =='\n' )
{
scanf ("%c ", &c);
if(c==' \n')
{
printf("\n");
bre ak
;
}
else
ne++;
}
else
{
if(c =='+'| |c==' -
'||c=='
*'|
|c=='
/'|
|c=='
=')
{
op[j ]=c ;
j++;
}
else
{
ke y[i]=c ;
i++;
}
}
}
pri
ntf("Theke ywordsandi dent
ifi
ersar
e:\n")
;
for
(k=0;k<i;
k++)
printf(
"%ci sanidentif
ier
\n",key[k]);
pri
ntf("Speci
alc haract
e r
sare");
for
(k=0;k<j;
k++)
printf(
"%c ",op[k]);
pri
ntf("\nTotalno.o fl
inesare:
%d", ne);
re
turn0;
}

Re
sul
t-
Ex
per
ime
nt2

Obje
ctive
-Wr
iteapr
ogr
ami
nCt
oche
ckwhe
the
rthee
nte
reds
tri
ngi
sani
dent
ifi
ero
r
ke
ywo r
d.

Br i
ef The or
y-C i denti
fier

repr
e sentt henamei nthe 
C program,fore xample,variabl
es,
funct i
ons ,arrays,st
r uct
ures,unions,labels,etc.An i
denti
fi
e r
 
c anbec o
mpo sedofl e
tter
ss uch
asuppe rcase,lowercaselett
ers,unde rs
core,digits
,b utthes tart
inglet
tershouldb eei
theran
alphab eto ranunde rscor
e.
Ke ywo r
d isapr edef
inedo rr eser
ve d wo rd whichi savail
ablei nC++ l i
brary wit
haf ixe
d
me aningandus edtope rf
orm ani nternalo pe
ration.C++Lang uagesuppo r
tsmo rethan64
keywo rds .
Eve ry 
Ke yword ex
ist
si nlowercaseletterslik
eaut o,b r
eak,case,co ns
t,cont
inue,intetc
.

Procedure-
-Starttheprogr
am.
-Inputstri
ng.
-Nowc heckforide
ntif
ier
sandkeywor
ds.
-Pri
ntalltheident
ifi
ersandk
eywords
.
-Endt heprog
ram.

Pr
ogr
am-
#i
ncl
ude<s
tdi
o.h>
#i
ncl
ude<s
tri
ng.h>

i
ntspe c
ial
_char(chars t
r)
{
if
(str=='~'||s t
r=='!'||str=='
#'||s tr
=='$'||str=='
%'| |s t
r=='^'||s
tr=='
&'||s t
r=='
*'
|
|str=='('||str==')'||str
=='_'||str=='+'||str
=='='||str=='|'|
|s t
r=='
-'||str
=='='||
s
tr=='{'||str=='}'||s t
r=='['||str
==']'| |st
r==';
'| |s
tr==':'||st
r=='"'||st
r=='<'||
s
tr=='>'||str=='?'| |st
r==','||st
r=='.'||st
r=='/')
r
eturn1 ;
return0;
}

i
ntchec
k(chars
tr)
{
i
f(!((s
tr>='
a'&&s
tr<='
z')|
|(s
tr>='
A'&&s
tr<='
Z')|
|st
r=='
_')
)
ret
urn0;
r
eturn1;
}

i
ntcheck_for
_ide nti
fi
er(charstr
[])
{
i
f( !
((st
r[0]>=' a'&&s t
r[0]<='z'
)||(s
tr[0]>='
A'&&s
tr[0]<='
Z')|
|st
r[0]=='
_')
)
r
eturn0;
f
o r(i
nti=1 ;i<s tr
len(str
);i++){
i
f(!((s
tr[i]>=' a'&&s tr
[i]<='z'
)
||(str[i]>=' A'&&s tr[i
]<='Z')
||(str[i]>=' 0'&&s tr[i
]<='9')
||str[i]==' _'))
re
turn0;
}
r
etur
n1;
}

i
ntmai n( ){
intl e n;
chark eywo rd[32][1 0]={
"aut o", "do ub le", "int ","s tr
uc t","break","else","l
o ng",
"s wi tch", "c ase", "e num", "regist
e r",
"type def","char",
"e xt ern", "re tur n", "uni on","c onst","fl
o at","short",
"uns igne d", "c ontinue ","f or","signed","vo i
d","def ault
",
"g ot o", "s ize of", "vo l
t i
le","do ","if","s
tatic","while"
};
chars tr[20];
sc anf ("%s ",s tr);
inti ,
flag 1=0;
pr intf( "\n") ;
pr intf( "Thek eywo rdsandi dentifie
rsar e:
\n") ;
fo r(i=0;i<32;i ++){
if(st rcmp( st r,keywo rd[i]) ==0){
}
}
len=s trlen( s tr);
if( che ck_f or_ide nt i
f ier( s
tr) )
{
flag 1=1 ;
print f( "%si sani de nti
f ier
\n", str);
}
if( fl
ag 1==0)
{
for (i=0; i
<le n;i++)
{
i
f (c hec k(s t
r [i]) )
pr i
nt f("%ci sani dentifier
\n", s
tr[i]);
}
}
pr intf ("Spe c i
alc har ac tersar e :
\n") ;
if( fl
ag 1==0)
{
for (i=0; i
<le n;i++)
{
i
f (spe c i
al _char (str[i]) )
pr i
nt f("%c \n", str[i]);
}
}
pr i
nt f( "To talno .o fl inesar e:1");
}
Re
sul
t-
Ex
per
ime
nt3

Obj
ect
ive
-Wr
iteapr
ogr
amt
ore
moveLe
ftRe
cur
sio
nfr
omGr
ammar
.

BriefThe ory-Aproducti
ono fg r
ammari ssai
dt ohave 
l
eftre
cursi
on 
i
fthel
e f
t mostvari
abl
eo f
i
tsRHSi ssameasvar i
abl
eo fitsLHS.
Ifal eftrecursi
onispres
enti nanyg r
ammart hen,duri
ngpars
inginthethes yntaxanalys
is
partofc ompil
ati
ontherei
sac hancethatthegrammarwi l
lcr
eateinf
ini
tel
oop.Thisisbecause
ate veryt i
meo fpro
ductio
no fg rammarS wi llpro
duceanotherS wit
ho utc heck
ingany
condit
ion.

Procedure
-
-Supposewehaveag rammarwhi
chcontai
nsleftrec
urs
ion:
S-->Sa/Sb/c/d
Checkifthegi
vengrammarcont
ainsl
eftrecur
sion,i
fprese
ntt
hens
epar
atet
hepr
oduc
tio
n
andstartwor
kingo
ni t.

-Intr
oduceanewnonter
minalandwr i
teitatt
hel
asto
feve
ryt
ermi
nal
.Wepr
oduc
eane
w
nonte
rminalS’
andwri
tenewpr oduc
tionas,
S-->cS'/dS'

-Writene wlyproducednont
erminali
nLHSandi nRHSi tcane
itherpr
oduceoritc
anpr
oduce
newpr oductio
ninwhi cht
het er
minal
so rnont
erminal
swhi
chfol
lowedthepre
vio
usLHSwil
lbe
re
placedb yne wno nt
ermi
nalatlast.
S'-->?/aS'/b S'
Soaf t
erc onvers
ionthenewe qui
valentpro
duc
tio
ni s
S-->cS'/dS'
S'-->?/aS'/b S'

Pr
ogr
am-
#i
ncl
ude
<st
dio
.h>
#i
ncl
ude
<st
ring
.h>
#de
fineSIZE1
0

i
ntmai
n()
{
c
harno
n_t
ermi
nal
;
c
harbe
ta,
alpha;
i
ntnum;
c
harpr
oduc
tio
n[1
0][SIZE];
i
nti
nde
x=3;/*s
tar
tingo
fthes
tri
ngf
oll
owi
ng"-
>"*/
pr
int
f("Ent
erNumbe
rofPr
oduc
tio
n:")
;
s
canf
("%d",
&num)
;
pr
int
f("Ent
ert
heg
rammar
:\n")
;
f
or(
inti
=0;
i<num;
i++)
{
s
canf
("%s
",pr
oduc
tio
n[i
]);
}
f
or(
inti
=0;
i<num;
i++)
{
pr
int
f("\nGRAMMAR:::%s
",pr
oduc
tio
n[i
]);
no
n_t
ermi
nal
=pr
oduc
tio
n[i
][0];
i
f(no
n_t
ermi
nal
==pr
oduc
tio
n[i
][i
nde
x]){
al
pha=pr
oduc
tio
n[i
][i
nde
x+1
];
pr
int
f("i
sle
ftr
ecur
sive
.\n")
;
whi
l
e(pr
oduc
tio
n[i
][i
nde
x]!
=0&&pr
oduc
tio
n[i
][i
nde
x]!
='|
')
i
nde
x++;
i
f(pr
oduc
tio
n[i
][i
nde
x]!
=0){
be
ta=pr
oduc
tio
n[i
][i
nde
x+1
];
pr
int
f("Gr
ammarwi
tho
utl
eftr
ecur
sio
n:\n")
;
pr
int
f("%c
->%c
%c\'
",no
n_t
ermi
nal
,be
ta,
non_t
ermi
nal
);
pr
int
f("\n%c
\'-
>%c
%c\'
|E\n",
non_t
ermi
nal
,al
pha,
non_t
ermi
nal
);
}
e
lse
pr
int
f("c
an'
tber
educ
ed\n")
;
}
e
lse
pr
int
f("i
sno
tle
ftr
ecur
sive
.\n")
;
i
nde
x=3;
}
}

Re
sul
t-
Ex
per
ime
nt4
Obj
ect
ive
-Wr
iteapr
ogr
ami
nCt
oimpl
eme
ntShi
ftRe
duc
ePar
ser
.

Bri
ef The o
ry-ShiftReduceparserattemptsforthec ons
truc
tio
no fpar
seinasimi
l
armanner
asdo neinb o
ttom upparsi
ngi.e.thepar setreeisc ons
truc
tedf r
omleaves
(bo
tto
m)tot he
roo
t(up).Amo regene
ralfo
rmo fshiftreduceparserisLRparser.
Thi
spar s
errequir
essomedatas t
ructuresi.
e.
-Ainputbufferforst
ori
ngtheinputs t
ring.
-Astackforstori
ngandaccess
ingthepr oduct
ionrule
s.

Pro
c edur e-
-St
ar tt hepr o
gr am.
-Gett hei npute xpres
sionands tor
eitint heinputbuffer
.
-Readt hedat af ro
mt heinputb uff
ero neatat i
me.
-Usi
ngs tackpus handpo ps hif
taandr educes ymbolswit
hre
s pec
ttoproduct
ionrule
savail
abl
e.
-Continuet hepr ocessti
llsymb o
lshif
tandpr oducti
onrul
ereducere
achesthestartsymbo
l.
-Di
splayt hestac kimple
me ntati
ontablewi t
hc orr
espondi
ngs
t ac
kacti
onswithinputsymbol
s.
-St
o pt hepr ogram.

Program-
#incl
ude <s
tdio.
h>
#incl
ude <s
tdli
b.h>
#incl
ude <s
tri
ng.h>
i
ntk =0,z=0,i
=0,j=0,
c=0;
chara[16],ac[20],s
tk[1
5],
act
[10];

vo
idcheck()
{
fo
r(z=0;z<c ;z++)
{
if
(s t
k[z]=='i
'&&s t
k[z+1]=='d')
{
stk[z]='E';
stk[z+1]='
\0';
j++;
}
}
fo
r(z=0;z<c ;z++)
{
if
(s t
k[z]=='E'&&stk[z+1]=='+'&&s
tk[z+2]=='
E')
{
stk[z]='E';
stk[z+1]='
\0';
stk[z+2]='\0'
;
i=i-
2;
}
}
fo
r(z=0;z<c ;z++)
{
if
(s t
k[z]=='E'&&stk[z+1]=='*'&&s
tk[z+2]=='
E')
{
stk[z]='E';
stk[z+1]='
\0';
stk
[z+1]='
\0'
;
i=i
-2;
}
}
f
or(
z=0;z<c ;z++)
{
i
f(st
k[z]=='('&&st
k[z+1
]=='
E'&&s
tk[z+2]=='
)')
{
stk[z]='E';
stk[z+1]='
\0';
stk[z+1]='
\0';
i=i-
2;
}
}
}
i
ntmai n()
{
printf("GRAMMARi sE- >E+E\nE- >E*E\nE-
>(E)\nE-
>id\n")
;
printf("e nteri nputs tri
ng") ;
scanf("%s ",a) ;
c=s t
rlen(a) ;
strcpy(ac t,"SHIFT- >");
printf("\ns tac k\ti nput\tac ti
on")
;
for(k=0, i
=0;j <c;k ++,i++,j
++)
{
if(
a[j ]==' i'&&a[j +1]=='d')
{
stk[i]=a[j ];
stk[i+1]=a[j +1];
stk[i+2]=' \0' ;
a[j]='' ;
a[j+1]='' ;
chec k();
}
else
{
stk[i]=a[j ];
stk[i+1 ]='\0' ;
a[j ]='' ;
}
chec k();
}
}
Re
sul
t-
Ex
per
ime
nt5
Obj
ect
ive
-Wr
iteapr
ogr
ami
nCi
mpl
eme
ntOpe
rat
orPr
ece
denc
ePar
ser
.

Brief Theo r
y-An o per
atorpr e
cedencepar
serisa b ot
tom-up parserthatinterpr
etsan
operato
rg rammar.Ano per
at o
r-pre
cedencepar
serisa s i
mples hi
ft-
reducepar se
rt hatis
capableofpar si
ngas ubse
to fLR(1)g r
ammars
.Mo r
epr e
cis
ely,theo perat
or-prec
edenc
e
parsercanpar s
eallLR(1)grammarswhe r
etwoc ons
ecuti
venont ermi
nalsande psi
lonnever
appearintheright
-handsi
deo fanyrule
.

Proc
edur e
-
-Gettheinputase xpres
sion.
-Checkthepr e
fer
enc eofeachs ymb oli
nthegivenexpr
essi
onwi
thal lothers
ymb o
lsinthe
i
npute x
pressio
n.
-Aft
erc heck
ingdispl
ayt heOpe rat
o rPrece
dencematri
xwithco
rrespondingsymbolcompari
son
andspecif
yi tusi
ngt herel
atio
nalo perat
ors<(Lesst
han),>(Great
e rthan)and=( e
quals)
.

Program-
#include<stdio .
h>
#include<string.h>
#include<ctype .h>
charq[9][9]={
{'>','>','
<','<','<',
'<','
>',
'<'
,'>'},
{'>','>','
<','<','<',
'<','
>',
'<'
,'>'},
{'>','>','
>','>','<',
'<','
>',
'<'
,'>'},
{'>','>','
>','>','<',
'<','
>',
'<'
,'>'},
{'>','>','
<','<','<',
'<','
>',
'<'
,'>'},
{'<','<','
<','<','<',
'<','
=',
'<'
,'E'},
{'>','>','
>','>','>',
'E','
>',
'E',
'>'},
{'>','>','
>','>','>',
'E','
>',
'E',
'>'},
{'<','<','
<','<','<',
'<','
E',
'<'
,'A'}
};
chars [30],s t[30],qs[30];
i
ntt op=- 1
,r=-1 ,
p=0;
voidpus h(chara)
{
top++;
st[top]=a;
}
charpo p()
{
chara;
a=st[t o
p];
top--;
returna;
}
i
ntf ind(chara)
{
switch(a)
{
case' +':
retur n0;
case' -':
return1 ;
case' *':
retur n2;
case' /':return3;
case' ^':ret
urn4;
case' (':r
eturn5;
case' )':r
eturn6;
case' a':ret
urn7;
case' $':ret
urn8;
def ault: ret
urn- 1;
}
}
voiddi spl
ay( c
hara)
{
print f
( "\nShi ft%c ",a);
}
voiddi spl
ay1(chara)
{
i
f(is al
pha( a))
print f
( "\nRe duc eE- >%c ",a);
elsei f((a=='+')||(a=='-')|
|(a=='*')|
|(a=='/'
)||
(a=='^'
))
print f
( "\nRe duc eE- >E%c E",a);
elsei f(a==')')
print f
( "\nRe duc eE- >(E)") ;
}
i
ntr el(chara,charb ,
chard)
{
i
f(is al
pha( a)!=0)
a=' a';
i
f(is al
pha( b)!=0)
b=' a';
i
f(q[f ind(a)][find(b)]==d)
retur n1 ;
else
retur n0;
}
i
ntmai n()
{
chars [100];
i
nti =-1;
print f
( "Ope ratorPr ecedingPar se
r\n");
print f
( "\nEnt ert heArithme ti
cEx pre
s s
ionEndwith$..
");
scanf ("%s ",s);
pus h('$' );
whi le(i)
{
i
f(( s[p]==' $')&&( st[top]=='$'))
{
print f
( "\n\nAc cepted");
break ;
}
elsei f(rel
(st[top], s
[p],'<')||
rel
(st[top],s
[p],'
='))
{
display( s[p]);
pus h(s[p]) ;
p++;
}
elsei f(rel
(st[top], s
[p],'>'))
{
do
{
r++;
qs[r]=pop(
);
dis
play1(
qs[r])
;
}
whil
e (
!re
l(s
t[top],
qs[r
],'
<')
);
}
}
}

Re
sul
t-
Ex
per
ime
nt6
Obj
ect
ive
-WAPi
nCt
oimpl
eme
ntRe
cur
siveDe
centPar
ser
.

Brief Theor
y- Recur
s i
vedes centi
sat op-downpar s
ingtechniquethatconst
ructsthepars
e
tre
ef romt hetopandt heinputisreadf ro
ml ef
tt oright.Itus espro
c e
dur esforever
y
ter
minalandnon-t
erminalentit
y.Thispars
ingtechni
quer e
cursi
ve l
yparsest
hei nputtomakea
parsetree,whi
chmayo rmayno tr
equir
ebac k-
tracki
ng.Butt heg r
ammaras soci
ate
dwi thit
(i
fno tlef
tfact
ore
d)c annotavoidback-t
racki
ng.

Procedure-
-Startthepr ogram.
-Forapr oductionf uncti
o nA,Iterateoveral
ltheAproduct
ions
.
-ForanApr oduc ti
ono ft hefor
mA- >X1 X2X3X4….Xk,Iter
atefro
m1t okandf
oll
ows
teps
4tos tep6.
-IfXi snon- ter
mi nal,callpr
ocedureX( )
,els
eg o
tostep5.
-IfXe qualst oc urrentinputsymbolARe adnextsymbol
,el
segotoste
p6.
-Backtr
acki nputandr esetthepointer
.
-Stopthepr ogram.

Prog r
am-
#include <stdi
o .
h>
#include <stdl
ib.h>
#include <stri
ng.h>
chari p_sym[1 5];
i
nti p_pt r=0;
voide _pr i
me (
);
voidt ();
voide ();
voidt _prime();
voidf ();
voidadvanc e();
voide ()
{
pri
nt f("\nE' ------->TE'");
t();
e_prime ();
}
voide _pr i
me (
)
{
i
f (
ip_s ym[ip_ptr]==' +'
)
{
pri
nt f("\nE' ------->+TE'");
advanc e
() ;
t();
e_prime ();
}
els
e
pri
nt f("\nE' ----->e'");
}
voidt ()
{
pri
nt f("\nT' -
- -
- -
- -
>FT' ");f
();
t_prime ();
}
voidt _prime ()
{
i
f (
ip_sym[i p_pt r
]==' *')
{
pri
nt f("\nT- ----->*FT' ");advance()
;
f();
t_prime ();
}
els
e
{
pri
nt f("\nT' - -
- -->e") ;
}
}
voidf ()
{
i
f (
(ip_s ym[i p_ptr]==' i
' )||
(ip_s
ym[ip_ptr]=='j
'))
{
pri
nt f("\n\t \tF- ----- >i");advance();
}
els
e
{
i
f (
ip_sym[i p_pt r
]==' (')
{
advanc e (
);
e();
i
f (
ip_sym[i p_pt r
]==' )')
{
advanc e (
);
pri
nt f("\nF- ---->(E) ") ;
}
els
e
{
pri
nt f("\nSynt axEr ror ");
exit(1
) ;
}
}
}
}
voidadvanc e()
{
i
p_pt r++;
}
i
ntmai n()
{
i
nti ;
pri
nt f("GRAMMERWITHOUTRECURSION") ;
pri
nt f("\nE- ----->TE' \nE' /e\nT----->FT");
pri
nt f("\nT- ----->*FT/e \nF- --
--->(E)/id");
pri
nt f("\nEnt ertheInputSymb ol
:");
for(i
=0;i <1 5;i ++)
{scanf ("%c ",&ip_sym[i ]);
}
pri
nt f("\nSe quenc eofPr oducti
onRules");
e(); }
Re
sul
t-
EXPERIMENT7

OBJECTIVEWr
iteapr
ogr
am t
oco
mput
efi
rst
.

BRIEFTHEORY:FIRST(X)fo
rag
rammars
ymb
olXi
sthes
eto
fte
rmi
nal
sthatbe
gin
thest
ring
sde
rivabl
efr
omX.

PROGRAM:
#i
ncl
ude<s
tdi
o.
h>

#i
ncl
ude
<ct
ype
.h>

vo
idFIRST(
char)
;intc
ount
,n=0;

c
harpr
odn[1
0][1
0],f
irs
t[1
0];i
ntmai
n()

{i
nti
;

charc,
ch;
pri
ntf
("Howmanypr
oduc
tio
ns?:
");s
canf
("%d",
&co
unt
);

pr
int
f("Ent
er %d pr
oduc
tio
ns e
psi
l
on= $ :
\n\n",
count
);f
or(
i=0;
i<c
ount
;i
++)

s
canf
("%s
%c",
pro
dn[i
],&c
h);f
or(
i=0;
i<c
ount
;i
++)

{
n=0;
pri
ntf
("El
eme
nt:
");s
canf
("%c
",&c
);

FIRST(c)
;
pri
ntf
("\nFIRST(
%c)
={",
c);f
or(
i=0;
i<n;
i++)pr
int
f("%c",
fir
st[i
]);pr
int
f("}\n")
;

}
}
vo
idFIRST(
charc
)
{intj
;

i
f(!
(is
uppe
r(c
)))
fir
st[n++]=c
;fo
r(j
=0;
j<c
ount
;j++)

{
i
f(pr
odn[j][0]==c)
{
i
f(pr
odn[j][2]=='$'
)f i
rst[n++]='$';
e
lseif(
isl
ower(pr
odn[j][2]))fi
rst[n++]=pr
odn[j
][2];e
lseFIRST(
pro
dn[j
][2])
;

}
}
}
Re
sul
t-
EXPERIMENT8

OBJECTIVE:Wr
iteapr
ogr
ami
nCt
odol
eftf
act
ori
ng.

BRIEF THEORY:Le ftFactori


ngisag rammartr
ans
format
iont
echni
que.Itconsi
sts
i
n "facto
ringo ut" pref
ixeswhich arec ommontotwoo rmoreproduct
ions
.Le ft
fact
ori
ng:apr o c
esso ftransfo
rmation,turni
ngt
heg r
ammarfrom aleft-
recur
sive
for
mt oane qui
valentnonleft
-recur
siveform.

PROGRAM:
#inc
lude
<st
dio
.h>

#i
ncl
ude
<st
ring
.h>

i
ntstr
lens
(chars
[])
intI; f or(i=0;s[i
]!='
\0'
;++i
); r
etur
ni;

}
i
nt

g
etSt
ring
(char

s
[]){ c
har

c
h;

i
nti=0;
whi
l
e ((c
h=g etc
har(
))!
='\n' && c
h!=EOF){
s
[i]=c h;++i
;}
s[i
]=' \0';
]

f
flus
h(s
tdi
n); r
etur
ni;

}
intmain(
)
{
charg r
am[20],
part
1[20],
par
t2[20],mo
dif
iedGram[20],newGram[20];
inti,
j=0,k=0,po
s;pri
ntf
("Ente
rProduc
tio
n:A- >"); ge
t Str
ing
(gr
am);

f
or(
i=0;
gram[i
]!='
|';
i++,
j++) par
t1[j
]=g
ram[i
]; par
t1[j
]='
\0'
;

f
or(
j=++i
,i
=0;
gram[j
]!='
\0'
;j++,
i++) par
t2[i
]=g
ram[j
];

par
t2[i
]='
\0'
;

f
or(
i=0;
i<st
rle
ns(part1
)||
i<s
trle
ns(
par
t2)
;i++)
{
if
(part1
[i]==par
t2[i])
{
mo
dif
iedGram[k]=par
t1[i
];
k
++; pos=i+1
;
}
}

f
or(
i=po
s,j
=0;
par
t1[i
]!='
\0'
;i
++,
j++)
{

ne
wGr
am[j
]=par
t1[i
];

}
ne
wGr
am[j
++]='
|';

f
or(
i=po
s;par
t2[i
]!='
\0'
;i
++,
j++)
{

ne
wGr
am[j
]=par
t2[i
];

mo
dif
iedGr
am[k
]='
X';

mo
dif
iedGr
am[++k
]='
\0'
;

ne
wGr
am[j
]='
\0'
;

pr
int
f("\nA

-
>%s
",mo
dif
iedGr
am)
;

pr
int
f("\nX

-
>%s
\n",
newGr
am)
;

Re
sul
t-
EXPERIMENT9

OBJECTIVE:Impl
eme
ntat
iono
fle
xic
alanal
yze
rfo
rgi
venar
ithme
tice
xpr
ess
ion.

BRIEF THEORY:Le x
icalanal
ysisisthef i
rstphaseo fa c
ompil
er.Ittak
esthe
mo di
fiedsour
cecodef romlanguageprepr
ocess
orsthatarewrit
tenintheformof
sentences
.Thelexi
calanalyzerb re
aksthesesyntaxesint
oas eri
esoftoke
ns,by
re
mo vinganywhi
tespaceorcomme nt
sinthesour
cec o
de.

PROGRAM:
#i
ncl
ude<s
tri
ng.
h>
#i
ncl
ude<c
type.
h>

#i
ncl
ude
<st
dio
.h>

vo
idk
eywo
rd(
chars
tr[1
0])

{
i
f(s
trc
mp(
"fo
r",
str
)==0|
|st
rcmp(
"whi
l
e",
str
)==0|
|st
rcmp(
"do
",s
tr)
==0|
|st
rcmp(
"int
",
s
tr
)
==0|
|st
rcmp(
"fl
oat
",s
tr)
==0|
|st
rcmp(
"char
",s
tr)
==0|
|st
rcmp(
"do
ubl
e",
str
)==0|
|st
r
c
mp(
"st
ati
c",
str
)==0|
|st
rcmp(
"swi
tch",
str
)==0|
|st
rcmp(
"cas
e",
str
)==0)
pr
int
f("\n%si
sak
eywo
rd",
str
);
e
lse
pr
int
f("\n%si
sani
dent
ifi
er",
str
);
}
i
ntmain(
)
{
FILE*f1
,*f
2,*f
3; c
harc
,st
r[1
0];

i
ntnum[1
00],li
neno
=0,t
oke
nval
ue=0,
i=0,j
=0,k
=0;
f
1=f
open(
"input
","w")
; whi l
e((
c=getc
har(
))!=EOF)

put
c(c
,f1
); f
clo
se(
f1)
; f
1=f
ope
n("i
nput
","r
");

f
2=f
ope
n("i
dent
ifi
er",
"w")
; f
3=f
ope
n("s
pec
ial
char
","w")
;

whi
l
e((
c=g
etc
(f1
))!
=EOF)

{ i
f(i
sdi
gi
t(c
))

{
t
oke
nval
ue=c
-'0'
; c
=ge
tc(
f1)
; whi
l
e(i
sdi
gi
t(c
))

{
t
oke
nval
ue*=1
0+c
-'0'
; c
=ge
tc(
f1)
;
}
num[i++]=to
kenval
ue;
unge
tc (
c,f
1);
}
e
lseif
(is
alpha(c
))
{
putc
(c,f2); c
=ge
tc(
f1)
;

whi
l
e(i
sdi
gi
t(c
)||
is
alpha(
c)|
|c=='
_'|
|c=='
$')

{
put
c(c
,f2)
; c
=ge
tc(
f1)
;

} put
c(''
,f2)
; ung
etc
(c,
f1)
;

}
e
lsei
f(c
==''
||c
=='
\t'
) pr
int
f("")
; e
lsei
f(c
=='
\n'
)

l
i
neno
++; e
lse put
c(c
,f3)
;

}
f
clo
se(
f2)
; f
clo
se(
f3)
; f
clo
se(
f1)
; f
or(
j=0;j
<i;j
++)

pr
int
f("%d",
num[j
]); pr
int
f("\n")
; f
2=f
ope
n("i
dent
ifi
er",
"r")
; k
=0;

pr
int
f("Thek
eywo
rdsandi
dent
ifi
ers
are
:")
; whi
l
e((
c=g
etc
(f2)
)!=EOF)

{ i
f(c
!=''
)

s
tr[k
++]=c
; e
lse { s
tr[k
]='
\0'
;

k
eywo
rd(
str
); k
=0;

}
}
f
clo
se(
f2)
; f
3=f
ope
n("s
pec
ial
char
","r
"); pr
int
f("\nSpe
cialc
har
act
ersar
e")
;

whi
l
e((
c=g
etc
(f3)
)!=EOF)

pr
int
f("%c
",c
); pr
int
f("\n")
; f
clo
se(
f3)
; pr
int
f("To
talno
.ofl
i
nes

ar
e:%d",
li
neno
);

Re
sul
t-

You might also like