Week - 4 Top Down Parsing 4.1) Develop An Operator Precedence Parser For A Given Language. Program

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

Exp No: Page No:

Date:
Week – 4 Top Down Parsing
4.1) Develop an operator precedence parser for a given language.
Program:
#include<stdio.h>
#include<string.h>
char stack[20],temp;
int top=-1;
void push(char item)
{
if(top>=20)
{
printf("STACK OVERFLOW");
return;
}
stack[++top]=item;
}
char pop()
{
if(top<=-1)
{
printf("STACK UNDERFLOW");
return;
}
char c;
c=stack[top--];
printf("Popped element:%c\n",c);
return c;
}
char TOS()
{
return stack[top];
}
int convert(char item)
{
switch(item)
{
case 'i':return 0;
case '+':return 1;
case '*':return 2;
case '$':return 3;
}
}
int main()
{

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0521


Exp No: Page No:
Date:
char pt[4][4]={
{'-','>','>','>'},
{'<','>','<','>'},
{'<','>','>','>'},
{'<','<','<','1'}};
char input[20];
int lkh=0;
printf("Enter input with $ at the end\n");
scanf("%s",input);
push('$');
while(lkh<=strlen(input))
{
if(TOS()=='$'&&input[lkh]=='$')
{
printf("SUCCESS\n");
return 1;
}
else if(pt[convert(TOS())][convert(input[lkh])]=='<')
{
push(input[lkh]);
printf("Push---%c\n",input[lkh]);
lkh++;
}
else
{
pop();
}
}
return 0;
}
Output:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0521


Exp No: Page No:
Date:

4.2) Construct a recursive descent parser for an expression.

Program:

#include<stdio.h>
#include<ctype.h>
#include<string.h>
void Tp();
void Ep();
void E();
void T();
void check();
int count,flag;
char expr[10];
int main()
{
count=0;
flag=0;
printf("\nEnter an Algebraic Expression:\t");
scanf("%s",expr);
E();
if((strlen(expr)==count)&&(flag==0))
printf("\nThe expression %s is valid\n",expr);
else
printf("\nThe expression %s is invalid\n",expr);
return 0;
}
void E()
{
T();
Ep();
}
void T()
{
check();
Tp();
}
void Tp()
{
if(expr[count]=='*')
{
count++;
check();
Tp();

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0521


Exp No: Page No:
Date:
}
}
void check()
{
if(isalnum(expr[count]))
count++;
else if(expr[count]=='(')
{
count++;
E();
if(expr[count]==')')
count++;
else
flag=1;
}
else
flag=1;
}
void Ep()
{
if(expr[count]=='+')
{
count++;
T();
Ep();
}
}

Output:

ADITYA ENGINEERING COLLEGE(A) Roll No: 20A91A0521

You might also like