0% found this document useful (0 votes)
43 views47 pages

Compiler Design Exercise Soft

Compiler Design

Uploaded by

fotawan235
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views47 pages

Compiler Design Exercise Soft

Compiler Design

Uploaded by

fotawan235
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Practical 1

AIM:
Tostudyaboutlexicalanalyzer.

EXERCISE
1.ImplementationofFiniteAutomataforStringValidationforgivenRE.
#include<stdio.h>
#include<string.h>
#defineNO_OF_CHARS256

intgetNextState(char*pat, intM, intstate, intx)


{

if (state < M && x ==


pat[state])returnstate+1;
intns, i;
for(ns =state; ns > 0; ns--)
{
if(pat[ns-1] ==x)
{
for(i =0; i <ns-1; i++)
f(pat[i]!=pat[state-
ns+1+i])break;if(i ==ns-1)return
ns;
}
}
return0;
}
voidcomputeTF(char*pat,intM,intTF[][NO_OF_CHARS])
{
intstate, x;
for(state=0;state<=M; ++state)for(x=0;x
<NO_OF_CHARS;++x)TF[state][x] =getNextState(pat, M, state, x);
}
voidsearch(char*pat,char*txt)
{
intM=strlen(pat);intN=strlen(txt);int
TF[M+1][NO_OF_CHARS];
computeTF(pat,M,TF);
//ProcesstxtoverFA.inti,state=0;for(
i =0; i <N; i++)
{
state=TF[state][txt[i]];if (state==M)

GandhinagarInstituteofTechnology 3170701CD
printf("\nPatternfoundatindex%d",i-M+1);
}
}
intmain()
{
char*txt="AABAACAADAABAAABAA";
char*pat="AABA";s
earch(pat,txt);return0
;
}

Output:

GandhinagarInstituteofTechnology 3170701CD
Practical 2
AIM:
Tostudyaboutpredictiveparser.

EXCERSICE:
1. ImplementationofRecursiveDescentParserwithoutbacktrackingforgivengrammar.

#include<stdio.h>
#include<string.h>
#include<ctype.h>
charinput[10];
int
i,error;voi
dE();
voidT();

void
Eprime();void
Tprime();void
F();main()
{i=
0;
error=0;

printf("Enteranarithmeticexpression:");//Eg:a+a*agets(
input);
E();

if(strlen(input)==i&&error==0)
printf("\nAccepted..!!!\n");
elseprintf("\nRejected..!!!\n");

GandhinagarInstituteofTechnology 3170701CD
}

void E()

T();

Eprime();

voidEprime()

if(input[i]=='+')

{i+
+;
T();
Eprime();

void T()

F();

Tprime();

voidTprime()

if(input[i]=='*')

{i+
+;

GandhinagarInstituteofTechnology 3170701CD
F();

Tprime();

voidF()

if(isalnum(input[i]))i++;
elseif(input[i]=='(')
{i+
+;
E();
if(input[i]==')')
i++;
elseerror=1;

elseerror=1;

Output:

GandhinagarInstituteofTechnology 3170701CD
2. ImplementaCprogramtofind“First”and"Follow"setforgivengrammar.

//Cprogramtocalculate theFirstand
//Followsetsofagivengrammar#in
clude<stdio.h>#include<ctype.h
>#include<string.h>

//FunctionstocalculateFollowv
oid followfirst(char, int,
int);voidfollow(charc);

// Function to calculate
Firstvoidfindfirst(char,int,in
t);

int count, n = 0;

//Storesthefinalresult
//of theFirst Sets
charcalc_first[10][100];

//Storesthefinalresult
//of theFollow Sets
charcalc_follow[10][100];i
nt m = 0;

// Stores the production


ruleschar
production[10][10];charf[10
], first[10];
GandhinagarInstituteofTechnology 3170701CD
int
k;char
ck;int e;

intmain(intargc,char**argv)
{
int jm =
0;int km =
0;int i,
choice;char
c,
ch;count=8;

// The Input
grammarstrcpy(production[0],
"E=TR");strcpy(production[1],
"R=+TR");strcpy(production[2],
"R=#");strcpy(production[3],
"T=FY");strcpy(production[4],
"Y=*FY");strcpy(production[5],
"Y=#");strcpy(production[6],
"F=(E)");strcpy(production[7],"
F=i");

intkay;
char
done[count];int
ptr =-1;

//Initializingthecalc_firstarrayfo
r(k=0; k<count;k++) {
for(kay=0;kay<100;kay++){calc
GandhinagarInstituteofTechnology 3170701CD
_first[k][kay]='!';
}

GandhinagarInstituteofTechnology 3170701CD
}
intpoint1 =0, point2,xxx;

for(k=0; k<count; k++)


{
c=production[k][0];p
oint2 =0;
xxx=0;

//CheckingifFirst ofchas
// already been
calculatedfor(kay=0;kay<=ptr;
kay++)
if(c==done[kay])
xxx=1;

if(xxx==1)
continue;

// Function
callfindfirst(c,0,
0);
ptr+=1;

// Adding c to the calculated


listdone[ptr] =c;
printf("\n First(%c) = { ",
c);calc_first[point1][point2++]=c;

//PrintingtheFirstSetsofthegrammarfor(
i=0+jm; i <n;i++){
int lark =0, chk=0;
GandhinagarInstituteofTechnology 3170701CD
for(lark =0;lark<point2;lark++){

if(first[i]==calc_first[point1][lark])
{
chk=1;
break;
}
}
if(chk==0)
{
printf("%c,",first[i]);calc_first[point1][p
oint2++]=first[i];
}
}
printf("}\n");
jm =
n;point1++;
}
printf("\n");
printf("
\n\n");
chardonee[count];
ptr=-1;

//Initializingthecalc_followarrayfo
r(k=0; k<count; k++){
for(kay=0;kay<100;kay++){calc
_follow[k][kay]='!';
}
}
point1 =
0;intland=0
GandhinagarInstituteofTechnology 3170701CD
;

GandhinagarInstituteofTechnology 3170701CD
for(e=0;e<count; e++)
{
ck=production[e][0];p
oint2 =0;
xxx=0;

//CheckingifFollowofck
// has already been
calculatedfor(kay=0;kay<=ptr;
kay++)
if(ck==donee[kay])
xxx=1;

if(xxx==1)
continue;
land+=1;

//Functioncallf
ollow(ck);
ptr+=1;

// Adding ck to the calculated


listdonee[ptr] =ck;
printf(" Follow(%c) = { ",
ck);calc_follow[point1][point2++]=ck;

//PrintingtheFollowSetsofthegrammarfor(
i=0+km; i < m;i++) {
int lark=0, chk=0;
for(lark=0;lark<point2;lark++)
{
if(f[i]==calc_follow[point1][lark])
GandhinagarInstituteofTechnology 3170701CD
{
chk=1;
break;
}
}
if(chk==0)
{
printf("%c,",f[i]);calc_follow[point1
][point2++]=f[i];
}
}
printf("
}\n\n");km =
m;point1++;
}
}

voidfollow(charc)
{
int i, j;

//Adding"$"tothe follow
// set of the start
symbolif(production[0][0]==c){
f[m++]='$';
}
for(i=0; i <10;i++)
{
for(j=2;j <10; j++)
{
if(production[i][j]==c)

GandhinagarInstituteofTechnology 3170701CD
{
if(production[i][j+1]!='\0')
{
//Calculatethefirstof thenext
// Non-Terminal in the
productionfollowfirst(production[i][j+1],i,(j+2));
}

if(production[i][j+1]=='\0'&&c!=production[i][0])
{
//Calculatethefollowof theNon-Terminal
//intheL.H.S.oftheproductionfoll
ow(production[i][0]);
}
}
}
}
}

voidfindfirst(charc,intq1,intq2)
{
int j;

//Thecasewhere we
//encounteraTerminalif
(!(isupper(c))){
first[n++]=c;
}
for(j=0;j <count;j++)
{
if(production[j][0]==c)

GandhinagarInstituteofTechnology 3170701CD
{
if(production[j][2]=='#')
{
if(production[q1][q2] ==
'\0')first[n++]='#';
elseif(production[q1][q2]!='\0'
&&(q1 !=0||q2!=0))
{
//Recursiontocalculate FirstofNew
//Non-
Terminalweencounterafterepsilonfindfirst(
} production[q1][q2],q1,(q2+1));
else

} first[n++]='#';
elseif(!isupper(production[j][2]))
{
first[n++]=production[j][2];
}
else
{
//Recursiontocalculate First of
//NewNon-Terminalweencounter
// at the
beginningfindfirst(production[
} j][2],j,3);
}
}
}

voidfollowfirst(charc,int c1,intc2)

GandhinagarInstituteofTechnology 3170701CD
{
int k;

//Thecasewhereweencounter
// a
Terminalif(!(is
upper(c)))
f[m++]=c;
else
{
int i = 0, j =1;
for(i=0;i <count;i++)
{
if(calc_first[i][0] ==
c)break;
}

//Includingthe Firstsetofthe
//Non-Terminal intheFollowof
// the original
querywhile(calc_first[i][j]!
='!')
{
if(calc_first[i][j]!='#')
{
f[m++]=calc_first[i][j];
}
else
{
if(production[c1][c2]=='\0')
{
//Casewherewereachthe
GandhinagarInstituteofTechnology 3170701CD
//endofaproduction

GandhinagarInstituteofTechnology 3170701CD
follow(production[c1][0]);
}
else
{
//Recursion tothenextsymbol
// in case we encounter a
"#"followfirst(production[c1][c2],c1,c2+1);
}
}j+
+;
}
}
}
Output:

GandhinagarInstituteofTechnology 3170701CD
3. ImplementaCprogramforconstructingLL(1)parsingforgivengrammar.

#include<stdio.h>

#include<conio.h>

#include<string.h>

chars[20],stack[20];

voidmain()

charm[5][6][3]={"tb","","","tb","","","","+tb","","","n","n","fc","","","fc","","","","n","
*fc","a","n","n","i"," "," ","(e)"," "," "};

intsize[5][6]={2,0,0,2,0,0,0,3,0,0,1,1,2,0,0,2,0,0,0,1,3,0,1,1,1,0,0,3,0,0};

int

i,j,k,n,str1,str2;clr

scr();

printf("\nEntertheinputstring:");sc

anf("%s",s);

strcat(s,"$");

n=strlen(s)st

ack[0]='$';

stack[1]='e';

i=1;

j=0;

printf("\nStack

Input\n");p

rintf("

\n");while((

GandhinagarInstituteofTechnology 3170701CD
stack[i]!='$')&&(s[j]!='$')

GandhinagarInstituteofTechnology 3170701CD
if(stack[i]==s[j])

i--

;j++

switch(stack[i])

case 'e':

str1=0;break;

case'b':str1=1;brea

k;

case't':str1=2;break

case 'c':

str1=3;break;

case'f':str1=4;brea

k;

switch(s[j])

case'i':str2=0;break

case '+':

str2=1;break;

case'*':str2=2;
GandhinagarInstituteofTechnology 3170701CD
break;

case'(':str2=3;brea

k;

case')':str2=4;brea

k;

case'$':str2=5;brea

k;

if(m[str1][str2][0]=='\0')

printf("\nERROR");

exit(0);

else

if(m[str1][str2][0]=='n')i--;

else

if(m[str1][str2][0]=='i')stac

k[i]='i';

else

for(k=size[str1][str2]-1;k>=0;k--)

stack[i]=m[str1][str2][k];i+

+;

i--;
GandhinagarInstituteofTechnology 3170701CD
}

for(k=0;k<=i;k++)pri

ntf("

%c",stack[k]);printf("

");for(

k=j;k<=n;k++)printf(

"%c",s[k]);printf("\n"

);

printf("\n

SUCCESS");getch();

Output:

GandhinagarInstituteofTechnology 3170701CD
Practical 3
AIM:
TostudyaboutLRParsers.

EXCERSICE:
1.WriteaCprogramtoimplement LALR(1)parser.

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

voidpush(char*,int*,char);
charstacktop(char*);voidis
product(char,char);intister
(char);intisnter(char);intis

state(char);voiderror();voi
disreduce(char,char);charp

op(char*,int*);

voidprintt(char*,int*,char[],int);v
oidrep(char[],int);
structaction
{

charrow[6][5];
};
conststructactionA[12]={

GandhinagarInstituteofTechnology 3170701CD
{"sf","emp","emp","se","emp","emp"},
{"emp","sg","emp","emp","emp","acc"},

{"emp","rc","sh","emp","rc","rc"},
{"emp","re","re","emp","re","re"},
{"sf","emp","emp","se","emp","emp"},

{"emp","rg","rg","emp","rg","rg"},
{"sf","emp","emp","se","emp","emp"},
{"sf","emp","emp","se","emp","emp"},

{"emp","sg","emp","emp","sl","emp"},
{"emp","rb","sh","emp","rb","rb"},
{"emp","rb","rd","emp","rd","rd"},
{"emp","rf","rf","emp","rf","rf"}
};
structgotol

{
charr[3][4];
};
conststructgotolG[12]={
{"b","c","d"},
{"emp","emp","emp"},
{"emp","emp","emp"},

{"emp","emp","emp"},
{"i","c","d"},
{"emp","emp","emp"},
{"emp","j","d"},
{"emp","emp","k"},
{"emp","emp","emp"},

GandhinagarInstituteofTechnology 3170701CD
{"emp","emp","emp"},

};charter[6]={'i','+','*',')','(','$'

};
charnter[3]={'E','T','F'};charstates[12]={'a','b','c','d','e','f','g','
h','m','j','k','l'};charstack[100];

inttop=-
1;chartemp[10
];structgramm

ar

{
charleft;char
right[5];
};
conststructgrammarrl[6]={

{'E',"e+T"},
{'E',"T"},
{'T',"T*F"},

{'T',"F"},
{'F',"(E)"},
{'F',"i"},
};

voidmain()
{
charinp[80],x,p,dl[80],y,bl='a';inti
=0,j,k,l,n,m,c,len;

clrscr();printf("Enterthe
input:");

GandhinagarInstituteofTechnology 3170701CD
scanf("%s",inp);
len=strlen(inp);i

np[len]='$';

inp[len+1]='\0';push(stac
k,&top,bl);printf("\nstack
\t\t\tinput");printt(stack,&
top,inp,i);do
{
x=inp[i];p=stacktop(stack);
isproduct(x,p);if(strcmp(te
mp,"emp")==0)error();if(st

rcmp(temp,"acc")==0)brea
k;
else
{
if(temp[0]=='s')
{
push(stack,&top,inp[i]);p
ush(stack,&top,temp[1]);i

++;

}
else
{
if(temp[0]=='r')

GandhinagarInstituteofTechnology 3170701CD
j=isstate(temp[1]);strcpy

(temp,rl[j-
2].right);dl[0]=rl[j-
2].left;

dl[1]='\0';

n=strlen(temp);for(k=0;k
<2*n;k++)pop(stack,&to

p);for(m=0;dl[m]!='\0';m
++)

push(stack,&top,dl[m]);l
=top;
y=stack[l-
1];isreduce(y,dl[0]);for(m=0
;temp[m]!='\0';m++)push(sta
ck,&top,temp[m]);
}

}
printt(stack,&top,inp,i);
}while(inp[i]!='\0');if(strc
mp(temp,"acc")==0)printf

("\naccepttheinput");else
printf("\ndonotaccepttheinput");
getch();
}
voidpush(char*s,int*sp,charitem)

GandhinagarInstituteofTechnology 3170701CD
if(*sp==100)printf(

"stackisfull");else
{

*sp=*sp+1;s
[*sp]=item;
}

}
charstacktop(char*s)
{

chari;i=s
[top];ret
urni;

}
voidisproduct(charx,charp)
{

intk,l;k=iste
r(x);l=isstat
e(p);
strcpy(temp,A[l-1].row[k-1]);

}
intister(charx)
{

inti;for(i=0;i<6;
i++)

GandhinagarInstituteofTechnology 3170701CD
if(x==ter[i])
returni+1;re

turn0;
}
intisnter(charx)

{
inti;for(i=0;i<3;
i++)if(x==nter[i
])returni+1;retu
rn0;
}
intisstate(charp)
{

inti;for(i=0;i<12;
i++)if(p==states[
i])returni+1;retur
n0;
}
voiderror()
{

printf("errorintheinput");
exit(0);
}
voidisreduce(charx,charp)
{

GandhinagarInstituteofTechnology 3170701CD
intk,l;k=isst
ate(x);l=isnt

er(p);
strcpy(temp,G[k-1].r[l-1]);
}

charpop(char*s,int*sp)
{
charitem;if
(*sp==-1)

printf("stackisempty");
else
{
item=s[*sp];
*sp=*sp-1;

}
returnitem;
}

voidprintt(char*t,int*p,charinp[],inti)
{
intr;printf("
\n");

for(r=0;r<=*p;r++)
rep(t,r);printf("\t\t\t
");

for(r=i;inp[r]!='\0';r++)

printf("%c",inp[r]);
}

GandhinagarInstituteofTechnology 3170701CD
voidrep(chart[],intr)
{

charc;c=t
[r];switc
h(c)

case'a':printf("0");b
reak;case'b':printf("
1");break;case'c':pr
intf("2");break;cas
e'd':printf("3");brea
k;case'e':printf("4")
;break;case'f':printf
("5");break;case'g':
printf("6");break;c
ase'h':printf("7");br
eak;case'm':printf("
8");break;case'j':pri
ntf("9");break;case'
k':printf("10");

GandhinagarInstituteofTechnology 3170701CD
break;case'l':printf("11"
);break;default:printf("
%c",t[r]);break;

}
}

Output:

GandhinagarInstituteofTechnology 3170701CD
Practical 4
AIM:Tostudyaboutoperatorprecedenceparser.

EXCERSICE:
1.ImplementaCprogramtoimplementoperatorprecedenceparsingforgiven grammar.

#include<stdlib.h>

#include<stdio.h>

#include<string.h>

voidf()

printf("Not operator

grammar");exit(0);

voidmain()

char grm[20][20],

c;inti,n,j=2,flag=0;sc

anf("%d",&n);

for(i =0; i <n; i++)

scanf("%s",grm[i]);

for(i =0; i <n; i++) {

c=grm[i][2];

while(c!= '\0'){

if(grm[i][3] =='+'||grm[i][3]=='-'

||grm[i][3]=='*'||grm[i][3]=='/')

GandhinagarInstituteofTechnology 3170701CD
flag=1;

else{

flag=0;f();

if(c=='$'){

flag =

0;f();

c=grm[i][++j];

if(flag==1)

printf("Operatorgrammar");

Output:

GandhinagarInstituteofTechnology 3170701CD
Practical 5
AIM:
Tostudyaboutlexicalanalyzergenerator(lex)andflex(fastlexicalanalyzer).

EXCERSICE:
1. ImplementfollowingProgramsUsingLex
a. GenerateHistogramofwords
#include<stdio.h>
#defineIN_WORD1/*pointinword */#defineOUT_WORD0/*
pointoutofword*/#defineMAX_LEN 20 /* maxword length to consider*/
intmain()
{
inti,j;/*iterators */intc;/*character*/
int len; /* word length */ int state; /* in/out of word */ int
top_count;inthistogram[MAX_LEN];
i = j = c = len = top_count = 0; state =
OUT_WORD;for(i =0; i<MAX_LEN; ++i)
histogram[i]=0;
/*processinput*/
while((c=getchar())!=EOF){
if(c==' '||c=='\t' ||c=='\n'){ if(state==IN_WORD){
/*incrementhistogramentryforcurrentwordlength*/ if(len<MAX_LEN)j=len;
else
j=MAX_LEN;
++histogram[j-1];
/* keep a record of the highest count */ if (histogram[j-1] > top_count) top_count
=histogram[j-1];
}
/*resetstate*/len=0;sta
te=OUT_WORD;
}else {
/*keeptrackofcurrentwordlength*/
++len;
state= IN_WORD;
}}
/*printhistogram fromtop tobottom*/for(i =top_count; i>0; --i){
/*printY-axis*/ printf("%3d|",i);
/*printentriesforeachwordlength*/for(j=0;j
<MAX_LEN;++j){if(histogram[j]<i) printf(" ");
elseprintf(".");
}
putchar('\n');

GandhinagarInstituteofTechnology 3170701CD
}
printf("");
/*printX-axis*/
for (i = 0; i < MAX_LEN; ++i) printf("--
");putchar('\n');
return0;
}

Output:

b. CaesarCypher
%%
[a-
z]{charcipher_char=yytext[0];ciph
er_char+=3;
if(cipher_char>'z')cipher_char-=('z'+1-
'a');printf("%c",cipher_char );
}
[A-
Z]{charcipher_char=yytext[0];cipher
_char+=3;
if(cipher_char>'Z')cipher_char-=('Z'+1-
'A');printf("%c",cipher_char);
}
%%
Output:

GandhinagarInstituteofTechnology 3170701CD
c. ExtractsingleandmultilinecommentsfromCProgram
/*DefinitionSection*/
%{
%}

/*Startingcharactersequenceformultilinecomment*/sta
rt\/\*
/*Endingcharactersequenceformultilinecomment*/en
d\*\/

/*RuleSection*/
%%

/*Regularexpressionfor singlelinecomment*/
\/\/(.*);
/*Regularexpressionformultilinecomment*/
{start}.*{end};

%%

/*Driverfunction*/
intmain(intk,char**argcv)
{
yyin=fopen(argcv[1],"r");
yyout=fopen("out.c","w");
/*call the yylex
function.*/yylex();
return0;
}
Output:

GandhinagarInstituteofTechnology 3170701CD
2. ImplementfollowingProgramsUsingLex
a. ConvertRomantoDecimal
#include<stdio.h>#include<string.h>
int convert(char);//functionprototypeofconversionfunctionint main()
{
int i = 0, num =0;
charromanNumber[100];//arrayforstoringromannumberprintf("EnterRomannumber:");
scanf("%s",
romanNumber);while(roma
nNumber[i])
{
//ifcondition forcheckingvalidityof romannumber if(convert(romanNumber[i ]) < 0)
{
printf("\nInvalidRomanNumber.\n");return0;
}
//ifcondition forcheckingvalidityof romannumberif((strlen(romanNumber)-i)>2)
{
if(convert(romanNumber[i])<convert(romanNumber[i +2]))
{
printf("\nInvalidRomanNumber.\n");return0;
}
}
//if condition for converting roman number into decimal
numberif(convert(romanNumber[i])>=convert(romanNumber[i
+1]))
//trueisfirst romannumberisgreaterorequalto secondnum
=num+convert(romanNumber[i]);
else
{
num=num+(convert(romanNumber[i+1])- convert(romanNumber[i]));i++;
}i++;
}
//displaying converted number printf("\nEquivalent decimal number: %d\n", num);
return0;
}
//convertingromannumberintoequivalentdecimalvalueint convert(charch)
{
intvalue=0;switch(
ch)
{
case 'I': value = 1;
break;case 'V': value = 5;
break;case 'X': value = 10;
break;case'L': value=50;
break;

GandhinagarInstituteofTechnology 3170701CD
case 'C': value = 100;
break;case 'D': value = 500;
break;case'M':value=1000;br
eak;case '\0': value = 0;
break;default:value=-1;
}
returnvalue;

Output:

b. Checkweathergivenstatementiscompoundorsimple

%{

#include<stdio.h>

intis_simple=1;

%}

%%

[\t\n]+[aA][nN][dD][\t\n]+{is_simple=0;}

[\t\n]+[bB][uU][tT][\t\n]+{is_simple=0;}

[\t\n]+[oO][rR][\t\n]+{is_simple=0;}

. {;}

%%

main()

printf("Enterthesentence:");

GandhinagarInstituteofTechnology 3170701CD
yylex();if(is_sim

ple==1)

printf("\n the given sentence is simple

sentence\n");else

printf("\nthegivensentenceiscompoundsentence\n");

intyywrap()

return1;

Output:

c. Extracthtmltagsfrom.html file

/*Declarationsection*/

%{

%}

GandhinagarInstituteofTechnology 3170701CD
%%

"<"[^>]*>{printf("%s\n",yytext);}

. ;// elsedo nothing

%%

intyywrap(){}

intmain(intargc,char*argv[])

externFILE*yyin=fopen("tags.txt","r");y

ylex();

return0;

Input:

Output:

GandhinagarInstituteofTechnology 3170701CD
Practical 6
AIM:
Tostudyaboutyetanothercompiler-compiler(yacc).

EXCERSICE:
1.CreateyaccandlexspecificationfiletogenerateCalculatorProgram.

LEXPART:

%{

#include<stdio.h>

#include

"y.tab.h"externint

yylval;

%}

%%

[0-9]+{

yylval=atoi(yytext);

returnNUMBER;

[\t];

[\n]return0;

.returnyytext[0];

%%

intyywrap()

return1;

GandhinagarInstituteofTechnology 3170701CD
YACCPART:

%{

#include<stdio.h>

intflag=0;

%}

%tokenNUMBER

%left'+''-'

%left'*''/''%'

%left'('')'

%%

ArithmeticExpression:

E{printf("\nResult=%d\n",$$);

return0;

};

E:E'+'E{$$=$1+$3;}

|E'-'E{$$=$1-$3;}

|E'*'E{$$=$1*$3;}

|E'/'E{$$=$1/$3;}

|E'%'E{$$=$1%$3;}

|'('E')'{$$=$2;}

|NUMBER{$$=$1;}

%%

voidmain()

printf("\nEnterAnyArithmetic Expression which can have operations Addition, Subtraction,

GandhinagarInstituteofTechnology 3170701CD
Multiplication, Divison, Modulus and Round

brackets:\n");yyparse();

if(flag==0)

printf("\nEnteredarithmeticexpressionisValid\n\n");
}

voidyyerror()

printf("\nEnteredarithmeticexpressionisInvalid\n\n");

flag=1;
}

Output:

GandhinagarInstituteofTechnology 3170701CD
GandhinagarInstituteofTechnology 3170701CD

You might also like