Design and implement a Non-recursive Predictive Parser (NPP) for the following g
ID: 3696562 • Letter: D
Question
Design and implement a Non-recursive Predictive Parser (NPP) for the following grammar: rightarrow . vertical line rightarrow A vertical line rightarrow vertical line 0 vertical line 1 vertical line 2 vertical line 3 vertical line 4 vertical line 5 vertical line 6 vertical line 7 vertical line 8 vertical line 9 Where A is an exponentiation operator (associate to right). This grammar generates statements of the form 2^2^3, 15. 20^2 for which the parser outputs 256 15 400. Solution: In order to implement this NPP. The parse table must be constructed by using first sets and follow sets. The parse table for this parser is shown as follows:Explanation / Answer
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
void err(const char* s)
{
perror(s);
exit(0);
}
int factor()
{
int val,i;
char ch[0];
scanf("%s",ch);
switch(ch[0])
{
case '(':
val=expr();
scanf("%s",ch);
if(ch[0]!=')')
err("Missing closing paranthesis in factor.");
break;
default :{
for(i=0;i<strlen(ch);i++)
{
if((ch[i]>'0')&&(ch[i]<='9'))
continue;
else
err("Illegal character sequence in place of factor.");
}
val=atoi(ch);
}
}
return val;
}
int term()
{
int val;
char ch[10];
val=factor();
while(1)
{
scanf("%s",ch);
if(ch[0]=='*')
{
val=val*factor();
}
else
break;
}
ungetc(ch[0],stdin);
return val;
}
int expr()
{
int val;
char ch[10];
val=term();
while(1)
{
scanf("%s",ch);
if(ch[0]=='+')
val=val+term();
else
break;
}
ungetc(ch[0],stdin);
return val;
}
main()
{
printf(" Enter the expression: ");
printf(" Result: %d ",expr());
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.