Monday , December 18 2017
Home / C / C Program for Recursive Descent Parser

C Program for Recursive Descent Parser

C Program for implementation of Recursive Descent Parser for language given below

E-> TE’
E’-> +TE’ | -TE’ | null
T-> FT’
T’-> *FT’| /FT’ | null
F-> id/ (E)/ num

Here ‘id’ can be a single letter. And ‘num’ can be a single digit number.

#include "stdio.h"
#include "conio.h"
char input[100];
char prod[100][100];
int pos=-1,l,st=-1;
char id,num;
void E();
void T();
void F();
void advance();
void Td();
void Ed();
void advance()
{
pos++;
if(pos<l)
{
if(input[pos]>='0'&& input[pos]<='9')
{
num=input[pos];
id='\0';
}
if((input[pos]>='a' || input[pos]>='A')&&(input[pos]<='z' || input[pos]<='Z'))
{id=input[pos];
num='\0';
}
}
}
void E()
{
strcpy(prod[++st],"E->TE'");
T();
Ed();
}
void Ed()
{
int p=1;
if(input[pos]=='+')
{
p=0;
strcpy(prod[++st],"E'->+TE'");
advance();
T();
Ed();
}
if(input[pos]=='-')
{   p=0;
strcpy(prod[++st],"E'->-TE'");
advance();
T();
Ed();
}

                                   // Recursive Descent Parser
if(p==1)
{
strcpy(prod[++st],"E'->null");
}
}

void T()
{
strcpy(prod[++st],"T->FT'");
F();
Td();
}
void Td()
{
int p=1;
if(input[pos]=='*')
{
p=0;
strcpy(prod[++st],"T'->*FT'");
advance();
F();
Td();
}
if(input[pos]=='/')
{   p=0;
strcpy(prod[++st],"T'->/FT'");
advance();
F();
Td();
}
if(p==1)
strcpy(prod[++st],"T'->null");
}
void F()
{
if(input[pos]==id) {
strcpy(prod[++st],"F->id");
advance();          }
if(input[pos]=='(')
{
strcpy(prod[++st],"F->(E)");
advance();
E();
if(input[pos]==')')   {
//strcpy(prod[++st],"F->(E)");
advance();             }
}
if(input[pos]==num)
{
strcpy(prod[++st],"F->num");
advance();
}
}
int main()
{
int i;
printf("Enter Input String ");
scanf("%s",input);
l=strlen(input);
input[l]='$';
advance();
E();
if(pos==l)
{
printf("String Accepted\n");
for(i=0;i<=st;i++)
{
printf("%s\n",prod[i]);
}
}
else
{
printf("String rejected\n");
}
getch();
return 0;
}

OUTPUT:

If you like this then please share this page. You can comment you queries here. Or you can also ask for a program. We are happy to help you.
tags: C program for Recursive Decsent parser, compiler design programs, parsing techniques
Also See:   Program in C to draw a TRIANGLE

Check Also

How to Solve Linear Equation in One Variable In C Programming?

C Program to Solve any Linear Equation in One Variable Find complete C program to ...

One comment

  1. thanku so much it is very helpfull to me

Leave a Reply

Your email address will not be published. Required fields are marked *