0% found this document useful (0 votes)
100 views42 pages

CD Lab File 181

Here is the C program to find the FIRST sets for a given grammar: #include <stdio.h> #include <string.h> // Production rule structure struct Production { char lhs; char rhs[20]; }; // Function to find FIRST set of a non-terminal void findFirst(struct Production rules[], int n, char X, char result[]) { int i; for(i=0; i<n; i++) { if(rules[i].lhs == X) { if(rules[i].rhs[0] == '+' || rules[i].rhs[0] == '|') { findFirst(rules, n,

Uploaded by

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

CD Lab File 181

Here is the C program to find the FIRST sets for a given grammar: #include <stdio.h> #include <string.h> // Production rule structure struct Production { char lhs; char rhs[20]; }; // Function to find FIRST set of a non-terminal void findFirst(struct Production rules[], int n, char X, char result[]) { int i; for(i=0; i<n; i++) { if(rules[i].lhs == X) { if(rules[i].rhs[0] == '+' || rules[i].rhs[0] == '|') { findFirst(rules, n,

Uploaded by

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

SRM INSTITUTE OF SCIENCE & TECHNOLOGY, NCR

CAMPUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

LAB RECORD FILE

Name : Harshit Varshney

Registration No : RA1811003030181

Section : D

Subject Code : 18CSC304J

Title : COMPILER DESIGN LAB

Semester : VI

Academic year 2020 - 2021


SRM INSTITUTE OF SCIENCE & TECHNOLOGY, NCR CAMPUS,
MODINAGAR, GHAZIABAD, U.P – 201204

Register No.:
RA1811003030181

BONAFIDE CERTIFICATE

This is to certify that Lab Report of Compiler Design Laboratory (18CSC304J),


which is submitted by Harshit Varshney in partial fulfillment of the requirement for
the award of degree of B. Tech. in Department of Computer Science & Engineering
of SRM Institute of Science & Technology, NCR Campus, Modinagar, is a record of
the candidate own work carried out by him/her under our supervision during the
academic year 2020-2021.

Student Registration No. – RA1811003030238


2
HEAD OF DEPARTMENT LAB IN-CHARGE

Submitted for the university examination held on_______05/06/2021___________.

List of Experiments

Experiment 1: Transition Diagram to Transition Table 4

Experiment 2: Implementation of Lexical Analyzer 7

Experiment 3: Computation of FIRST Sets 10

Experiment 4: Computation of FOLLOW Sets 14

Experiment 5: Intermediate Code Generation 16

Experiment 6: Computation of Leading Sets 20

Experiment 7: Computation of Trailing Sets 24

Experiment 8: Intermediate code generation - Postfix expression 28

Experiment 09: Intermediate code generation - Prefix Expression 30

Experiment 10: Implementation of Shift Reduce Parsing 32


Student Registration No. – RA1811003030238
3
Experiment 11: Construction of DAG 35

Experiment 12: Recursive Descent Parsing 36

Experiment 1: Transition Diagram to Transition Table


Aim: Write a program in C/C++ to show the transition table from a given transition diagram.

Algorithm:
1. Start
2. Enter the number of states.
3. Enter the number of input variables.
4. Enter the state and its information.
5. Enter the input variables.
6. Enter the transition function information i.e., transition value from a state with an input
variable.
7. Show the Transition Table.
8. Stop

Program (tt.c):
#include<stdio.h>
#include<stdlib.h>
struct setStates
{
int state;
int final;
int start;
};
typedef struct setStates sstate;
void main()
{
int s,v,i,j;

Student Registration No. – RA1811003030238


4
int

**sv,*var;
sstate *states;
printf("\nInput the number of finite set of states : ");
scanf("%d",&s);
printf("\nInput the number of finite set of input variables : ");
scanf("%d",&v);
sv = (int **)malloc(v*sizeof(int));
for(i=0;i<s;i++)
{
sv[i]=(int *)malloc(sizeof(int));
}
states = (sstate *)malloc(s*sizeof(sstate));
printf("\nInput the states and its info (state start final): \n");
for(i=0;i<s;i++)
{
scanf("%d%d%d",&states[i].state,&states[i].start,&states[i].final);
}
var = (int *)malloc(v*sizeof(int));
printf("\nInput the variables : \n");
for(i=0;i<v;i++)
{
scanf("%d",&var[i]);
}
for(i=0;i<s;i++)
{
for(j=0;j<v;j++)
{
printf("\nThe states %c with input variable %c move to state : ",states[i].state,var[j]);
scanf("%d",&sv[i][j]);
}
}
printf("\nThe Transition Table : \n");
printf("\t");
for(i=0;i<v;i++)
{

Student Registration No. – RA1811003030238


5
printf("%c\t",var[i]);
}
printf("\n------------------------------------------------");
for(i=0;i<s;i++)
{
printf("\n%c %c %c\t",states[i].state,(states[i].start==0)?' ':'$',(states[i].final==0)?' ':'*');
for(j=0;j<v;j++)
{
printf("%c\t",sv[i][j]);
}
printf("\n");
}
}

Student Registration No. – RA1811003030238


6
Output:

Input the number of finite set of states : 4


Input the number of finite set of input variables : 2

Input the states and its info (state start final):


97 1 1
98 0 0
99 0 0
100 0 0

Input the variables :


48
49

The sates a with input variable 0 move to state : 98


The sates a with input variable 1 move to state : 99
The sates b with input variable 0 move to state : 100
The sates b with input variable 1 move to state : 97
The sates c with input variable 0 move to state : 97
The sates c with input variable 1 move to state : 100
The sates d with input variable 0 move to state : 100
The sates d with input variable 1 move to state : 98

The Transition Table :


0 1
------------------------------------------------
a $ *b c

b d a

c a d

d d b

Result: The Program Executed successfully

Student Registration No. – RA1811003030238


7
Experiment 2: Implementation of Lexical Analyzer
Aim: Write a program in C/C++ to implement a lexical analyzer.

Algorithm:
1. Start
2. Get the input expression from the user.
3. Store the keywords and operators.
4. Perform analysis of the tokens based on the ASCII values.
5.
ASCII Range TOKEN TYPE
97-122 Keyword else identifier
48-57 Constant else operator
Greater than 12 Symbol

6. Print the token types.


7. Stop

Program (lexi.c):

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
int main()
{
char key[11]
char oper[13]={'+','-','*','/','%','&','<','>','=',';',':','!'};
char a[20],b[20],c[20];
int i,j,l,m,k,flag;
printf("\n Enter the expression: ");
gets(a);
i=0;
while(a[i])
{ flag=0;
j=0;
l=0;
b[0]='\0';
if((toascii(a[i]>=97))&&(toascii(a[i]<=122)))
{ if((toascii(a[i+1]>=97))&&(toascii(a[i+1]<=122)))
{ while((toascii(a[i]>=97))&&(toascii(a[i]<=122)))
{ b[j]=a[i];
Student Registration No. – RA1811003030238
8
j++; i++;

b[j]='\0';
}
else
{ b[j]=a[i];
i++;
b[j+1]='\0';
}
for(k=0;k<=9;k++)
{ if(strcmpi(b,key[k])==0)
{ flag=1;
break;
}
}
if(flag==1)
printf("\n %s is the keyword",b);
else
printf("\n %s is the identifier",b);
}
else if((toascii(a[i]>=48))&&(toascii(a[i]<=57)))
{ if((toascii(a[i+1]>=48))&&(toascii(a[i+1]<=57)))
{ while((toascii(a[i]>=48))&&(toascii(a[i]<=57)))
{ c[l]=a[i];
l++; i++;
}
}
else
{ c[l]=a[i];
i++;l++;
}
c[l]='\0';
printf("\n %s is the constant",c);
}
else
{for(m=0;m<13;m++)
{ if(a[i]==oper[m])
{ printf("\n %c is the operator",a[i]);
break;
}}
if(m>=13)
printf("\n %c is the symbol",a[i]);
i++;
} }
return 0;
Student Registration No. – RA1811003030238
9
}

Output:

Result: The Program Executed successfully

Student Registration No. – RA1811003030238


10
Experiment 3: Computation of FIRST Sets
Aim: Write a program in C/C++ to find the FIRST set for a given set of production rule of a
grammar.

Algorithm:
Procedure First
1. Input the number of production N.
2. Input all the production rule PArray
3. Repeat steps a, b, c until process all input production rule i.e. PArray[N]
a. If Xi ≠ Xi+1 then
i. Print Result array of Xi which contain FIRST(Xi)
b. If first element of Xi of PArray is Terminal or ε Then
i. Add Result = Result U first element
c. If first element of Xi of PArray is Non-Terminal Then
i. searchFirst(i, PArray, N)
4. End Loop
5. If N (last production) then
a. Print Result array of Xi which contain FIRST(Xi)
6. End

Procedure searchFirst(i, PArray, N)


1. Repeat steps Loop j=i+1 to N
a. If first element of Xj of PArray is Non-Terminal Then
i. searchFirst(j, of PArray, N)
b. If first element of Xj of PArray is Terminal or ε Then
i. Add Result = Result U first element
ii. Flag=0
2. End Loop
3. If Flag = 0 Then
a. Print Result array of Xj which contain FIRST(Xj)
4. End

Program:
#include<bits/stdc++.h>
using namespace std;
void searchFirst(int n, int i, char pl[], char r[], char result[], int k)
{
int j,flag;
for(j=i+1;j<n;j++)
{
if(r[i]==pl[j])
Student Registration No. – RA1811003030238
11
{
if(isupper(r[j]))
{
searchFirst(n,j,pl,r,result,k);
}
if(islower(r[j]) || r[j]== '+' || r[j]=='*' || r[j]==')' || r[j]=='(')
{
result[k++]=r[j];
result[k++]=','; flag=0;
}
}
}
if(flag==0)
{
for(j=0;j<k-1;j++)cout<<result[j];
}
}
int main()

{
char pr[10][10],pl[10],r[10],prev,result[10];
int i,n,k,j;
cout<<"\nHow many production rule : ";
cin>>n;
if(n==0) exit(0);
for(i=0;i<n;i++)
{
cout<<"Input left part of production rules : ";
cin>>pl[i];
cout<<"Input right part of production rules : ";
cin>>pr[i];
r[i]=pr[i][0];
}
cout<<"\nProduction Rules are :\n";
for(i=0;i<n;i++)
{
cout<<pl[i]<<"->"<<pr[i]<<"\n";//<<";"<<r[i]<<"\n";
}
cout<<"\n---O U T P U T---\n";
prev=pl[0];k=0;
for(i=0;i<n;i++)
{
if(prev!=pl[i])
Student Registration No. – RA1811003030238
12
{
cout<<"\nFIRST("<<prev<<")={";
for(j=0;j<k-1;j++)cout<<result[j];
cout<<"}";
k=0;prev=pl[i];
}
if(prev==pl[i])
{
if(islower(r[i]) || r[i]== '+' || r[i]=='*' || r[i]==')' || r[i]=='(')
{
result[k++]=r[i];
result[k++]=',';
}
if(isupper(r[i]))
{
cout<<"\nFIRST("<<prev<<")={";
searchFirst(n,i,pl,r,result,k);
cout<<"}";
k=0;prev=pl[i+1];
}
}
}
if(i==n)
{
cout<<"\nFIRST("<<prev<<")={";
for(j=0;j<k-1;j++)cout<<result[j];
cout<<"}";
k=0;prev=pl[i];
}
return 0;
}

Student Registration No. – RA1811003030238


13
Output:

Result: The Program Executed successfully

Student Registration No. – RA1811003030238


14
Experiment 4: Computation of FOLLOW Sets
Aim: Write a program in C/C++ to find a FOLLOW set from a given set of production rule.

Algorithm:
1. Declare the variables.
2. Enter the production rules for the grammar.
3. Calculate the FOLLOW set for each element call the user defined function follow().
4. If x->aBb
a. If x is start symbol then FOLLOW(x)={$}.
b. If b is NULL then FOLLOW(B)=FOLLOW(x).
c. If b is not NULL then FOLLOW(B)=FIRST(b).
END.
Program:

#include<stdio.h>
#include<string.h>
#include<ctype.h>
int n,m=0,p,i=0,j=0;
char a[10][10],f[10];
void follow(char c);
void first(char c);
void main()
{
int i,z;
char c,ch;
printf("Enter the no.of productions:");
scanf("%d",&n);
printf("Enter the productions(epsilon=$):\n");
for(i=0;i<n;i++)
scanf("%s%c",a[i],&ch);
do
{
m=0;
printf("Enter the element whose FOLLOW is to be found:");
scanf("%c",&c);
follow(c);
printf("FOLLOW(%c) = { ",c);
for(i=0;i<m;i++)
printf("%c ",f[i]);
printf(" }\n");
printf("Do you want to continue(0/1)?");
Student Registration No. – RA1811003030238
15
scanf("%d%c",&z,&ch);
}
while(z==1);
}
void follow(char c)
{
if(a[0][0]==c)f[m++]='$';
for(i=0;i<n;i++)

{
for(j=2;j<strlen(a[i]);j++)
{
if(a[i][j]==c)
{
if(a[i][j+1]!='\0')first(a[i][j+1]);
if(a[i][j+1]=='\0'&&c!=a[i][0])
follow(a[i][0]);
}
}
}
}
void first(char c)
{
int k;
if(!(isupper(c)))f[m++]=c;
for(k=0;k<n;k++)
{
if(a[k][0]==c)
{
if(a[k][2]=='$') follow(a[i][0]);
else if(islower(a[k][2]))f[m++]=a[k][2];
else first(a[k][2]);
}
}
}

Student Registration No. – RA1811003030238


16
Output:

Result: The Program Executed successfully

Student Registration No. – RA1811003030238


17
Experiment 5: Intermediate Code Generation
Aim: Write a program in C/C++ to generate intermediate code from a given syntax tree statement.

Algorithm:
1. Start the process.
2. Input an expression EXP from user.
3. Process the expression from right hand side to left hand side.
4. FLAG:=0; TOP = -1;
5. IF EXP = ‘=’ then
i. IF EXP(index – 1) = 0 then
1. PRINT EXP element from index to (index – 1) and POP
STACK[TOP]. Terminate
Else
i. PRINT Wrong Expression
[EndIF]
IF an operator is found and FLAG = 0 then
i. TOP:= TOP + 1
ii. add to STACK[TOP].
iii. FLAG:=1
Else
i. pop twice the STACK and result add to the newID(identifier) and PRINT.
ii. TOP:=TOP-2. Save newID to STACK[TOP]
iii. FLAG:=0
[EndIF]
6. IF an operand is found then
i. TOP:=TOP+1
ii. move to STACK [TOP]
iii. IF TOP > 1 then
1. pop twice the STACK and result add to the newID(identifier) and
PRINT.
2. TOP:=TOP-2. Save newID to STACK[TOP]
3. FLAG:=0
[End]
7. End the process

Program (icgen.cpp):

/* Intermediate Code Generator */


// Here consideration is any input expression
// only contain digits at the end
#include<iostream>
Student Registration No. – RA1811003030238
18
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
using namespace std;
int main()
{
char g,exp[20],stack[20];
int m=0,i,top=-1,flag=0,len,j;
cout<<"\nInput an expression : ";
gets(exp);
cout<<"\nIntermediate code generator\n";
len=strlen(exp);

//If expression contain digits


if(isdigit(exp[len-1]))
{
cout<<"T = inttoreal(";
i=len-1;
while(isdigit(exp[i]))
{
i--;
}
for(j=i+1;j<len;j++)
{
cout<<exp[j];
}
cout<<".0)\n";
exp[i+1]='T';len=i+2;
}
else //If expression having no digit
{
cout<<"T = "<<exp[len-1]<<"\n";
exp[len-1]='T';
}
for(i=len-1;i>=0;i--)
{
if(exp[i]=='=')
{
if((i-1)==0)
{
// If expression contains unary operator in RHS near = operator
Student Registration No. – RA1811003030238
19
if(isalpha(stack[top]))

cout<<exp[i-1]<<" "<<exp[i]<<" "<<stack[top];


}
else
{
cout<<exp[i-1]<<" "<<exp[i]<<" "<<stack[top]<<stack[top-1];
}
break;
}
else
{
cout<<"\nWrong Expression !!!";
break;
}
}
if(exp[i]=='+'||exp[i]=='/'||exp[i]=='*'||exp[i]=='-'||exp[i]=='%')
{
if(flag==0)
{
flag=1;top=top+1;
stack[top]=exp[i];
}
else
{
g=char('A' + m);m++;
cout<<g<<" = "<<stack[top]<<stack[top-1]<<"\n";
stack[top-1]=g;
stack[top]=exp[i];
flag=0;
}
}
else
{
top=top+1;
stack[top]=exp[i];
if(top>1)
{
g=char('A' + m);m++;
cout<<g<<" = "<<stack[top]<<stack[top-1]<<stack[top-2]<<"\n";
top=top-2;
stack[top]=g;flag=0;
}
}
}
Student Registration No. – RA1811003030238
20
return 0;
}

Output:

Result: The Program Executed successfully

Student Registration No. – RA1811003030238


21
Experiment 6: Computation of Leading Sets
Aim: Write a program in C/C++ to detect the leading edges of the given set of productions of a
grammar.

Algorithm:
1. Start the program.
2. Get the Set of Productions for the grammar from the user. No redundant & cyclic
productions must be given.
3. The conditions to be checked are:
Conditions Inclusions in result
S->Sa add a
S->Aa add a, production of A
S->ab add a
S->AB Production of A
S->SA none
S->a take a
S->SA* none taken
S->*a take * leave a
4. Print the Leading edges.
5. Stop the program.

Program (leading.cpp):

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
char av[100],av1[100];
int v=0,j=0,v1=0;
void disp(int);
struct pro
{
char h,t,t1;
}p[100];
int search(char x)
{
for(int i=0;i<v;i++)
if(av[i]==x) return 1;
return 0;
}
int search1(char x)
Student Registration No. – RA1811003030238
22
{
for(int i=0;i<v1;i++)
if(av1[i]==x) return 1;
return 0;
}
void disp1(char x)
{
for(int i=0;i<j;i++)
if(p[i].h==x) disp(i);
}
void disp(int px)
{
if(int(p[px].t)>=65 && int(p[px].t)<=90)
{
if(p[px].t1!='\0' && search1(p[px].t1)==0)
{
if(p[px].t1!='\n')
cout<<p[px].t1;
av1[v1]=p[px].t1;
v1++;
}
disp1(p[px].t);
}
else if(p[px].t!='#')
{
if(search1(p[px].t)==0)
{
cout<<"\t"<<p[px].t;
av1[v1]=p[px].t;
v1++;
}}}
int main()
{ int i,k;
cout<<"Enter the production: end with ~"<<endl<<endl;
char a1[100];
for(i=0;(a1[i]=getc(stdin))!='~';i++);
a1[i]='\0';
cout<<a1;
for( k=0;k<i;k++)
{
if(a1[k]=='-' && a1[k+1]=='>')
{
Student Registration No. – RA1811003030238
23
p[j].h=a1[k-1];
p[j].t=a1[k+2];
p[j].t1='\0';

if(p[j].h==p[j].t)
{
p[j].t=a1[k+3];
if(int(p[j].t)>=65 && int(p[j].t)<=90)
p[j].t='#';
p[j].t1='\0';
}
else if(int(p[j].t)>=65 && int(p[j].t)<=90)
{
p[j].t1=a1[k+3];
if((int(p[j].t1)>=65) && (int(p[j].t1)<=90))
p[j].t1='\0';
}
j++;
}
}
cout<<endl<<"The Leading edges r as follows: "<<endl;
for(i=0;i<j;i++)
{
if(search(p[j].h)==0)
{
av[v]=p[i].h;
cout<<endl<<av[v]<<": {";
disp1(av[v]);
cout<<" }"<<endl<<endl;

for(k=0;k<v1;k++)
av1[k]='\0';
v1=0;
v++;
}
}
return 0;}

Student Registration No. – RA1811003030238


24
Output:

Result: The Program Executed successfully

Student Registration No. – RA1811003030238


25
Experiment 7: Computation of Trailing Sets
Aim: Write a program in C/C++ or Java to detect the trailing edges of the given set of productions
of a grammar.

Algorithm:
1. Start the program.
2. Get the Set of Productions for the grammar from the user. No redundant & cyclic
productions must be given.
3. Reverse each input productions and print it.
4. The conditions to be checked according to the reversed inputs are:
Conditions Inclusions in result
S->Sa add a
S->Aa add a, production of A
S->ab add a
S->AB Production of A
S->SA none
S->a take a
S->SA* none taken
S->*a take * leave a
5. Print the Trailing edges.
6. Stop the program.

Program (trailing.cpp):
#include<iostream>
#include<stdio.h>
#include<conio.h>
#include<string.h>
using namespace std;
char b1[100];
char a1[100];
char av[100],av1[100];
int v=0,j=0,v1=0;

void disp(int);

struct pro
{
char h,t,t1;
}p[100];

Student Registration No. – RA1811003030238


26
void revpro(int l)
{
int k1,k2,j;
for(int i=0;i<=l;i++)
{
a1[i]=b1[i];
if(b1[i]=='>')
{
for(j=i+1;;j++)
{
if(int(b1[j])==10)
{
a1[j]=b1[j];
break;
}
}
for(k1=i+1,k2=j-1;k1<j;k1++,k2--)
a1[k1]=b1[k2];
i=j;
}
}
}

int search(char x)
{
for(int i=0;i<v;i++)
if(av[i]==x) return 1;
return 0;
}

int search1(char x)
{
for(int i=0;i<v1;i++)
if(av1[i]==x) return 1;
return 0;
}

void disp1(char x)

Student Registration No. – RA1811003030238


27
{
for(int i=0;i<j;i++)
if(p[i].h==x) disp(i);
}

void disp(int px)


{
if(int(p[px].t)>=65 && int(p[px].t)<=90)
{
if(p[px].t1!='\0' && search1(p[px].t1)==0)
{
if(p[px].t1!='\n')
cout<<p[px].t1;
av1[v1]=p[px].t1;
v1++;
}
disp1(p[px].t);
}
else if(p[px].t!='#')
{
if(search1(p[px].t)==0)
{
cout<<"\t"<<p[px].t;
av1[v1]=p[px].t;
v1++;
}
}
}
int main()
{int i,k;
cout<<"Enter the production: end with ~"<<endl<<endl;
for(i=0;(b1[i]=getc(stdin))!='~';i++);

b1[i]='\0';
revpro(i);
cout<<a1;

for(int k=0;k<i;k++)
{

Student Registration No. – RA1811003030238


28
if(a1[k]=='-' && a1[k+1]=='>')
{
p[j].h=a1[k-1];
p[j].t=a1[k+2];
p[j].t1='\0';

if(p[j].h==p[j].t)
{
p[j].t=a1[k+3];
if(int(p[j].t)>=65 && int(p[j].t)<=90)
p[j].t='#';
p[j].t1='\0';
}
else if(int(p[j].t)>=65 && int(p[j].t)<=90)
{
p[j].t1=a1[k+3];
if((int(p[j].t1)>=65) && (int(p[j].t1)<=90))
p[j].t1='\0';
}
j++;
}
}
cout<<endl<<"The Trailing edges r as follows: "<<endl;
for(i=0;i<j;i++)
{
if(search(p[j].h)==0)
{
av[v]=p[i].h;
cout<<endl<<av[v]<<": {";
disp1(av[v]);
cout<<" }"<<endl<<endl;

for(k=0;k<v1;k++)
av1[k]='\0';
v1=0;
v++;
}
}
return 0;

Student Registration No. – RA1811003030238


29
}

Output:

Result: The Program Executed successfully

Student Registration No. – RA1811003030238


30
Experiment 8: Intermediate code generation - Postfix expression
Aim: Write a program in C/C++ or Java to generate Intermediate Code (Postfix Expression) from
given syntax tree.

#include<stdio.h>
char stack[20];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
}
int main()
{
char exp[20];
char *e, x;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')

Student Registration No. – RA1811003030238


31
printf("%c", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c",pop());
}
return 0;
}

Output:

Result: The program executed successfully.

Student Registration No. – RA1811003030238


32
Experiment 09: Intermediate code generation - Prefix Expression
Aim: Write a program in C/C++ or Java to generate Intermediate Code (Prefix Expression) from
given syntax tree.

#define SIZE 50 /* Size of Stack */


#include<string.h>
#include<ctype.h>
#include<stdio.h>
#include<stdlib.h>
char s[SIZE];
int top=-1; /* Global declarations */

void push(char elem)


{ /* Function for PUSH operation */
s[++top]=elem;
}

char pop()
{ /* Function for POP operation */
return(s[top--]);
}

int pr(char elem)


{ /* Function for precedence */
switch(elem)
{
case '#': return 0;
case ')': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
}
}
char *strrev (char *str)
{
if (!str) {
fprintf (stderr, "%s() Error: invalid string\n", __func__);
return NULL;
}

char *begin = str;


char *end = *begin ? str + strlen (str) - 1 : begin; /* ensure non-empty */

Student Registration No. – RA1811003030238


33
char tmp;

while (end > begin)


{
tmp = *end;
*end-- = *begin;
*begin++ = tmp;
}

return str;
}

int main()
{ /* Main Program */
char infx[50],prfx[50],ch,elem;
int i=0,k=0;
printf("\n\nRead the Infix Expression ? ");
scanf("%s",infx);
push('#');
strrev(infx);
while( (ch=infx[i++]) != '\0')
{
if( ch == ')') push(ch);
else
if(isalnum(ch)) prfx[k++]=ch;
else
if( ch == '(')
{
while( s[top] != ')')
prfx[k++]=pop();
elem=pop(); /* Remove ) */
}
else
{ /* Operator */
while( pr(s[top]) >= pr(ch) )
prfx[k++]=pop();
push(ch);
}
}
while( s[top] != '#') /* Pop from stack till empty */
prfx[k++]=pop();
prfx[k]='\0'; /* Make prfx as valid string */
strrev(prfx);
strrev(infx);
printf("\n\nGiven Infix Expn: %s Prefix Expn: %s\n",infx,prfx);
Student Registration No. – RA1811003030238
34
return 0;
}

Output:

Result: The Program executed successfully.

Student Registration No. – RA1811003030238


35
Experiment 10: Implementation of Shift Reduce Parsing
Aim: Write a program in C/C++ to implement the shift reduce parsing.

Algorithm:
1. Start the Process.
2. Symbols from the input are shifted onto stack until a handle appears on top of the stack.
3. The Symbols that are the handle on top of the stack are then replaces by the left hand side
of the production (reduced).
4. If this result in another handle on top of the stack, then another reduction is done, otherwise
we go back to shifting.
5. This combination of shifting input symbols onto the stack and reducing productions when
handles appear on the top of the stack continues until all of the input is consumed and the
goal symbol is the only thing on the stack - the input is then accepted.
6. If we reach the end of the input and cannot reduce the stack to the goal symbol, the input is
rejected.
7. Stop the process.

Program (srp.cpp):

#include<stdio.h>
#include<conio.h>
#include<string.h>
void check();
void check1();
void copy();
void print(int val);
char stack[20];
char temp[10];
char result[10];
int i,j;
int main()
{
printf("Enter Your Expression:");
scanf("%s",&stack);
check();
return 0;
}
void check()
{
for(;i<strlen(stack)+1;i++)
{
Student Registration No. – RA1811003030238
36
if(stack[i]=='+' || stack[i]=='-' || stack[i]=='*' || stack[i]=='/'|| stack[i]=='\0')
{
temp[j]='E';
j++;
temp[j]=stack[i];
j++;
}
}
check1();
}
void check1()
{
printf("\n STACK VALUES\tINPUT \n");

l: for(j=0,i=0;i<strlen(temp);)
{
if(temp[i]=='+' || temp[i]=='-' || temp[i]=='*' || temp[i]=='/')
{
printf("\n\t %c",temp[i]);
i++;
print(i);
printf("\n\t %c",temp[i]);
i++;
print(i);
i--;
copy();
goto l;
}
else
{
printf("\n\t %c",temp[i]);
i++;
print(i);
}
}
printf("\n\n\t Expressions Output:%s",temp);
}
void copy()
{
j=0;
while(temp[i]!='\0')
{
Student Registration No. – RA1811003030238
37
temp[j]=temp[i];
j++;
i++;
}
temp[j]='\0';
}
void print(int val)
{
printf("\t\t");
for(;val<strlen(temp);val++)
printf("%c",temp[val]);
}

Output:

Result: The Program Executed successfully.

Student Registration No. – RA1811003030238


38
Experiment 11: Construction of DAG
Aim: Write a c or c++ or java to Construct DAG for input expression.

Code :
#include<iostream>
#include<string>
using namespace std;
int main()
{
string exp;
cout<<"Enter the expression:-";
cin>>exp;
int j=0,k=0;
char q;
for(int i=exp.length()-1;i>1;i--)
{
if(islower(exp[i]) || (exp[i]>=48 && exp[i]<=57))
{
cout<<j<<"->"<<exp[i]<<endl;
j++;
}
}
for(int i=exp.length()-1;i>1;i--)
{
if(!(islower(exp[i])|| (exp[i]>=48 && exp[i]<=57)))
{
cout<<j<<"->"<<exp[i]<<k<<k+1<<endl;
j++;
k+=2;
}
}
cout<<j<<"->"<<exp[0]<<endl;
j++;
cout<<j<<"->"<<exp[1]<<j-1<<j-2<<endl;
return 0;
}

Student Registration No. – RA1811003030238


39
Output:

Result: The Program Executed successfully

Student Registration No. – RA1811003030238


40
Experiment 12: Recursive Descent Parsing
Aim: Write a program in C/ C++ or Java to implement Recursive Descent Parsing

Code:
#include<iostream>
#include<map>
#include<vector>
using namespace std;
int main()
{
int flag = 0;
map<char,vector<string> >rules;
string exp,test;
rules['S'].push_back("aAc");
rules['A'].push_back("cd");
rules['A'].push_back("d");
cout<<"Enter the string: ";
cin>>exp;
string start="aAc";
if(start[0]!=exp[0])
cout<<"Not Accepted";
else
{
cout<<"S"<<endl<<start<<endl;
string a= (rules['A'])[0]; string b=(rules['A'])[1];
string t;
t=start[0]+a+start[2];
cout<<t<<endl;
if(t==exp)
{
flag = 1;
cout<<"Accepted";
}
else
{
cout<<start<<endl;
t=start[0]+b+start[2];
cout<<t<<endl;
if(t==exp)
{
flag = 1;
Student Registration No. – RA1811003030238
41
cout<<"Accepted";

}
}
if(flag == 0) cout<<"Not accepted";
return 0;
}

Output:

Result: The Program Executed successfully

Student Registration No. – RA1811003030238


42

You might also like