Question

Please write a recursive descent parser (including a lexical analyzer) for the following EBNF in C....

Please write a recursive descent parser (including a lexical analyzer) for the following EBNF in C. Your program codes should be runnable.

<exprs> -> <expr>; {<expr>;}

<expr> -> <term> { (+ | -) <term> }

<term> -> <factor> { (*|/ ) <factor> }

<factor> -> <exp> {^ <exp>}

<exp> -> id | int_lit | real_lit | (<expr>)

where,

^ indicates the power operation, id is a legal identifier name, int_lit represents any positive integer number, and real_lit represents any positive floating-point number.

Input and output examples:

Input:

x ^ (y+1) - x/2.5 + z;

sum + total * 10;

Output:

parsing succeed

Input:

3 + x*y);

Output:

parsing fail

Note 1: Please name your input file as “input.txt”

Note 2: Try adding some error messages in output such as “lack of right parenthesis”.

Note 3: Try to rewrite the grammar to allow negative numbers.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include<stdio.h>
void E();
void T();
void V();
int flag=0,i,r=1;
char s[100];
void E()
{
   T();
   if(s[i]=='+' || s[i]=='^' || s[i]=='/' || s[i]=='-' || s[i]=='*')
   {
   if(s[i]=='('){
      flag=0;
      i++;
      r++;
      E();
   }
   else if(s[i]==')')
      {
          r--;  
       }
   }
   else if(s[i]==';' && r==1)
   flag=1;
}
void T()
{
   V();
   if(s[i]=='*' || s[i]=='+' || s[i]=='^' || s[i]=='/' || s[i]=='-')
   {
      if(s[i]=='('){
      flag=0;
      i++;
      r++;
      T();
      }
      else if(s[i]==')')
      {
          r--;  
       }
     
   }
   else if(s[i]==';' && r==1)
   flag=1;
}
void V()
{
   if(s[i]>='a' && s[i]<='z')
   i++;
   else
   flag=1;
}
int main()
{
   printf("Enter a valid expression:\n");
   gets(s);
   E();
   if(flag==1)
   printf("parsing succeed");
   else
   printf("parsing fail");
}

Add a comment
Know the answer?
Add Answer to:
Please write a recursive descent parser (including a lexical analyzer) for the following EBNF in C....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT