0% found this document useful (0 votes)
91 views38 pages

Program To Perform Operations On Stack.: Rogram O

The document describes a C program to calculate the FIRST symbols of a grammar. It defines functions to calculate the FIRST set of non-terminals, handle merging of unique symbols, and calculate the FOLLOW set by recursively analyzing the grammar productions. Global arrays are used to store the grammar rules, FIRST/FOLLOW sets calculated, and flags to track processed non-terminals. The program takes the number of non-terminals as input, initializes the arrays, and calls functions to calculate the FIRST and FOLLOW sets by parsing the grammar rules, outputting the results.

Uploaded by

ijgour
Copyright
© Attribution Non-Commercial (BY-NC)
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)
91 views38 pages

Program To Perform Operations On Stack.: Rogram O

The document describes a C program to calculate the FIRST symbols of a grammar. It defines functions to calculate the FIRST set of non-terminals, handle merging of unique symbols, and calculate the FOLLOW set by recursively analyzing the grammar productions. Global arrays are used to store the grammar rules, FIRST/FOLLOW sets calculated, and flags to track processed non-terminals. The program takes the number of non-terminals as input, initializes the arrays, and calls functions to calculate the FIRST and FOLLOW sets by parsing the grammar rules, outputting the results.

Uploaded by

ijgour
Copyright
© Attribution Non-Commercial (BY-NC)
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/ 38

Programming File: Compiler Design 0112CS071038

PROGRAM NO 1
OBJECTIVE: Program to perform operations on stack.

CODE:
#include<stdio.h>
#include<conio.h>
#include<process.h>

int top, max=9;


char st[10], item;

void main()
{
void push(char);
void pop(void);
void display(void);
int op;
char ch='y';
top=-1;
clrscr();
while(ch=='y'||ch=='Y')
{
printf("Perform Operation on Stack");
printf("\n\n1) Push ");
printf("\n2) Pop ");
printf("\n3) Display ");
printf("\n4) Exit\n ");
printf("\n\nPlease Enter Your Choice Here: ");
fflush(stdin);
scanf("%d", &op);

switch (op)
{
case 1:
if (top==max)
printf("Overflow");
else
{
printf("\nPlease Enter a Character Element to Push in Stack: ");
fflush(stdin);
scanf("%c",&item);
push(item);
}
break;

case 2:
if (top<0)
printf("Underflow");
else
{
pop();
}
break;

case 3:

Submitted By:INRDAJEET GOUR 1|Page


Programming File: Compiler Design 0112CS071038

if (top<0)
printf("\nNo Item to Display (Underflow) ");
else
display();
break;

case 4:
exit(0);
break;

default:
printf("\nPlease Enter Correct Choice!!!");
}

printf ("\nDo you want to continue (Y/N): ");


fflush(stdin);
scanf("%c", &ch);
clrscr();
}

//Function for PUSH


void push(char it)
{
top=top+1;
st[top]=it;
}

//Function for POP


void pop()
{
top = top-1;
}

//Function for Display


void display()
{
int i;
for (i=0;i<=top;i++)
{
printf("\n%c", st[i]);
}
}

Submitted By:INRDAJEET GOUR 2|Page


Programming File: Compiler Design 0112CS071038

OUTPUT
Perform Operation on Stack

1) Push

2) Pop

3) Display

4) Exit

Please Enter Your Choice Here: 3

Do you want to continue (Y/N): Y

Submitted By:INRDAJEET GOUR 3|Page


Programming File: Compiler Design 0112CS071109
0112CS071038

PROGRAM NO 2
OBJECTIVE: Calculate FIRST symbols of a grammar.

CODE:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
char **arr;
int *flagstate;
int **markarr;
char **foundfirst;
int *firstisnull;
int *NtSymbols;
char **foundfollow;
int **followgoesto;

int strmergeunique(char*dest,const char *source)


{
int strlength=strlen(source),change=0;
for(int i=0;i<strlength;i++)
{
if(!strchr(dest,source[i]))
{
dest[strlen(dest)+1]='\0';
dest[strlen(dest)]=source[i];
change=1;
}
}
return change;
}

char* first(char* ch,int &k,int rowno)


{
char prod[50]={'\0'},prod1[50]={'\0'};
int i=0,isnull,preisnull=0;

while(1)
{ isnull=0;
if(isupper(ch[i]))
{
int j=0;
j=NtSymbols[toascii(ch[i])-65]+1;
if(!flagstate[j-1])
{
strcpy(prod1,first(arr[j-1]+1,isnull,j-1));
strcpy(foundfirst[j-1],prod1);
flagstate[j-1]=1;

Submitted By:INRDAJEET GOUR 4|Page


Programming File: Compiler Design 0112CS071038

firstisnull[j-1]=isnull;
}
else
{
strcpy(prod1,foundfirst[j-1]);
isnull=firstisnull[j-1];
}
preisnull=isnull;
strmergeunique(prod,prod1);
if(isnull==1)
{ i++;
continue;
}
else
k=k|isnull;//if k=1 k remains 1 else it is isnull
}
else
{
if(ch[i]=='@')
{ k=1;
}
else
{
if(ch[i]=='/')
{
i++;
k=k|preisnull;
continue;
}
if(ch[i]=='\x0'&&preisnull==1)
{
k=1;
return prod;
}
prod[strlen(prod)+1]='\0';
prod[strlen(prod)]=ch[i];
}
}
int prev=1;
for(int p=0;p<10&&markarr[rowno][p]!=-1;p++)
{
if(markarr[rowno][p]>i)
{
i=markarr[rowno][p]+1;
prev=0;
break;
}
}
if(!prev) continue;

Submitted By:INRDAJEET GOUR 5|Page


Programming File: Compiler Design 0112CS071038

return prod;
}
}
char *first(char*ch ,int &k)
{
char prod[50]={'\0'},prod1[50]={'\0'};
int i=0,isnull,preisnull=0;

if(ch[0]=='\x0')
{
k=1;
return ch;
}
while(1)
{ isnull=0;
if(isupper(ch[i]))
{
int j=0;
j=NtSymbols[toascii(ch[i])-65]+1;
if(!flagstate[j-1])
{
strcpy(prod1,first(arr[j-1]+1,isnull,j-1));
strcpy(foundfirst[j-1],prod1);
flagstate[j-1]=1;
firstisnull[j-1]=isnull;
}
else
{
strcpy(prod1,foundfirst[j-1]);
isnull=firstisnull[j-1];
}
preisnull=isnull;
strmergeunique(prod,prod1);
if(isnull==1)
{ i++;
continue;
}
}
else
{
if(ch[i]=='@')
{ k=1;
}
else
{
if(ch[i]=='\x0'&&preisnull==1)
{
k=1;
return prod;
}
prod[strlen(prod)+1]='\0';

Submitted By:INRDAJEET GOUR 6|Page


Programming File: Compiler Design 0112CS071038

prod[strlen(prod)]=ch[i];
}
}
return prod;
}
}
void follow(int );
void main()
{
int nt;
clrscr();
printf("Enter no.of nonterminals :");
scanf("%d",&nt);
arr=new char*[nt];
markarr=new int*[nt];
foundfirst=new char*[nt];
foundfollow=new char*[nt];
flagstate=new int[nt];
firstisnull=new int[nt];
followgoesto=new int*[nt];
NtSymbols=new int[26];
for (int i=0;i<nt;i++)
{
arr[i]=new char[100];
markarr[i]=new int[10];
foundfirst[i]=new char[10];
memset(foundfirst[i],'\0',10);
foundfollow[i]=new char[10];
memset(foundfollow[i],'\0',10);
flagstate[i]=0;
firstisnull[i]=0;
followgoesto[i]=new int[nt];
followgoesto[i][0]=0;
printf("Enter non terminal ");
cin>>arr[i][0];
flushall();
printf("Enter Production for %c------>",arr[i][0]);
gets(arr[i]+1);
NtSymbols[toascii(arr[i][0])-65]=i;
for(int temp=1,k=0;temp<strlen(arr[i]);temp++)
{
if(arr[i][temp]=='/')
markarr[i][k++]=temp-1;
}
markarr[i][k]=-1;
}
char prod[50];
int isnull=0;
follow(nt);
cout<<endl<<endl;
for(i=0;i<nt;i++)

Submitted By:INRDAJEET GOUR 7|Page


Programming File: Compiler Design 0112CS071038

{
isnull=0;
strcpy(prod,first(arr[i]+1,isnull,i));
printf("First (%c)--> { %s %c}\n",arr[i][0],prod,isnull?'@':' ');
printf("Follow (%c)--> { %s }\n",arr[i][0],foundfollow[i]);
delete arr[i];
delete markarr[i];
delete foundfirst[i];
delete followgoesto[i];
}
delete arr;
delete markarr;
delete flagstate;
delete foundfirst;
delete firstisnull;
delete NtSymbols;
delete foundfollow;
}

void follow(int no_of_nonteminals)


{
char Beta[10]={'\0'},prod[20],BigB;
int nonterminal=0,isnull=0;
strcpy(foundfollow[0],"$");

while(nonterminal<no_of_nonteminals)
{
for(int eachletter=1;arr[nonterminal][eachletter]!='\0';eachletter++)
{
BigB=arr[nonterminal][eachletter];
if(isupper(BigB))
{
for(int i=eachletter+1;arr[nonterminal][i]!='/'
&&arr[nonterminal][i]!='\x0';i++)
{
Beta[i-eachletter-1]=arr[nonterminal][i];
}
Beta[i-eachletter-1]='\0';
isnull=0;
strcpy(prod,first(Beta,isnull));
strmergeunique(foundfollow[NtSymbols[toascii(BigB)-65]],prod);
if(isnull)
{
followgoesto[ nonterminal ][ followgoesto[nonterminal][0]+1 ]
=NtSymbols[toascii(BigB)-65];
followgoesto[nonterminal][0]++;
}
}
}
nonterminal++;
}

Submitted By:INRDAJEET GOUR 8|Page


Programming File: Compiler Design 0112CS071038

int change=0;
do
{
change=0;
for(int i=0;i<nonterminal;i++)
{
for(int j=1;j<=followgoesto[i][0];j++)
{
change|=strmergeunique(foundfollow[followgoesto[i][j]],foundfollow[i]);
}
}
}

while(change);
getch();

Submitted By:INRDAJEET GOUR 9|Page


Programming File: Compiler Design 0112CS071038

OUTPUT
Enter no. of non terminals: 2

Enter non terminal S

Enter Production for S-----aSb/bSa/A

Enter non terminal A

Enter Production for A---a/b

First (S)  {ab}

First (A)  {ab}

Submitted By:INRDAJEET GOUR 10 | P a g e


Programming File: Compiler Design 0112CS071038

PROGRAM NO 3
OBJECTIVE: Calculate FOLLOW symbols of a grammar.
Note:
1) The variables and terminals can be single character only. Combination of characters like
“S” for variables or id for terminal is not allowed.
2) For null character use the symbol ^.
3) The symbol # and $ cannot be used for terminals. If they are present in the grammar,
use some other alternative for them.

#include<iostream.h>
#include<conio.h>
#include<string.h>
int anychange;
class ustack
{
int a[10],top;
public:
ustack()
{
top=-1;
}
int te()
{
if(top>=0)
return a[top];
else
return(-1);
}
int push(int x);
int pop()
{
if(top>=0)
{
int temp=a[top];
top--;
return(temp);
}
else
return(-1);
}
int contains(int);
friend void copystk(ustack &s1, ustack&s2);
void show();
};
void ustack::show()
{
int I;
for(i=0;i<=top;i++)

Submitted By:INRDAJEET GOUR 11 | P a g e


Programming File: Compiler Design 0112CS071038

{cout<<(char)a[i]<<” “;}
cout<<”\n”;
}
int ustack::contains(int s)
{
for(int i=0;i<=top;i++)
{
if(s==a[i])
return(i);
}
return(-1);
}
int ustack::push(int x)
{
If (top<9)
{
if(contains(x)==-1)
{
top++;
a[top]=x;
return(1);
}
else
return(0) ;
}
else
{cout<<”stack is full,ERROR!”;
return(0);
}
}
class grammer
{
int nv,nt,np[10];
char v[10],t[10],prod[10][15];
ustack firstk[10],folstk[10],tocopy[10];
ustack varstk,terstk;
public:
grammer();
void follow();
int match(int,int,int);
void ifcompleted();
void showfollow();
};
grammer::grammer()
{
int I,j,temp;
cout<<”\nenter no of variables”;
cin>>v[i];
varstk.push(v[i]);
}
cout<<”enter terminal”<<(i+1)<<” “;

Submitted By:INRDAJEET GOUR 12 | P a g e


Programming File: Compiler Design 0112CS071038

cin>>t[i];
terstk.push(t[i]);
}
for(i=0;i<nv;i++)
{
cout<<”enter production for variable”<<v[i]<<””;
cin>>prod[i];
}
char c;
for(i=0;i<nv;i++)
{
cout<<”enter first symbols for variables”<<v[i]<<” when done enter #”;
do
{
cin>>c;
if(c!=’#’)
firstk[i].push(c);
}
while(c!=’#’)
}
}
int grammer::match(int i, int j, int k)
{
int curr, next,a,b,c;
curr=prod[i][j];
next=prod[i][j+k];
a=varstk.contains(curr);
b=varstk.contains(next);
c=terstk.contains(next);
if(a==-1)
{
return(0);
}
else if(e!=-1)
{
folstk[a].push(next);
}
else if(next==’|’ || next==’\0’)
{
tocopy[a].push(i);
}
Else if(b!=-1)
{
copystk(folstk[a],firstk[b]);
if(firstk[b].contains(‘^’)!=-1)
{
match(i,j,k+1);
}}
return(0);
}
void grammer::follow()

Submitted By:INRDAJEET GOUR 13 | P a g e


Programming File: Compiler Design 0112CS071038

{
folstk[0].push(‘$’);
int i,j,curr,next,a,b,c;
for(i=0;i<nv;i++)
{
for(j=0;j<strlen(prod[i]);j++)
{
match(i,j,1);
}}
ifcompleted();
}
void copystk(ustack &s1,ustack&s2)
{
int I;
for(i=0;i<=s2.top;i++)
{
If(s2.a[i]!=’^’)
{
anychange=s1.push(s1.a[i]);
}}}
void grammer::ifcompleted()
{
Int i,j,t;
anychange=0;
for(i=0;i<nv;i++)
{
t=tocopy[i].pop();
while(t!=-1)
{
copystk(tocopy[i],tocopy[t]);
copystk(folstk[i],folstk[t]);
t=tocopy[i].pop();
}}
if (anychange==1)
follow();
}
void grammer::showfollow()
{ int i,j;
for(i=0;i<nv;i++)
{
cout<<”follows of”<<v[i]<<” “;
folstk[i].show();
}}
void main()
{
clrscr();
grammer g1;
g1.follow();
g1.showfollow();
getch();
}

Submitted By:INRDAJEET GOUR 14 | P a g e


Programming File: Compiler Design 0112CS071038

OUTPUT
Enter no of variables: 5
Enter variable 1: E
Enter variable 2: X
Enter variable 3: T
Enter variable 4: Y
Enter variable 5: F

Enter no of terminals: 5
Enter terminal 1: +
Enter terminal 2: *
Enter terminal 3: i
Enter terminal 4: (
Enter terminal 5: )
Enter productions for variable E TX
Enter productions for variable X +TX
Enter productions for variable T FY
Enter productions for variable Y *FY|^
Enter productions for variable F (E)|I
Enter first symbols for variable E when done enter # (
i
#
Enter first symbols for variable X when done enter # +
^
#
Enter first symbols for variable T when done enter # (
i
#
Enter first symbols for variable Y when done enter # *
^
#
Enter first symbols for variable F when done enter # (
i
#
Follows of E: $ )
Follows of X: $ )
Follows of T: + $ )
Follows of Y: + $ )
Follows of F: * + $ )

Submitted By:INRDAJEET GOUR 15 | P a g e


Programming File: Compiler Design 0112CS071038

PROGRAM NO 4
OBJECTIVE: Implement Lexical Analyzer.

CODE:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#define MAX 30

void main()
{
char str[MAX];
int state=0;
int i=0, j, startid=0, endid, startcon, endcon;

clrscr();

for(j=0; j<MAX; j++)


str[j]=NULL; //Initialise NULL

printf(" Lexical Analysis \n");


printf("Enter the string: ");
gets(str); //Accept input string
str[strlen(str)]=' ';

printf("Analysis:\n");

while(str[i]!=NULL)
{
while(str[i]==' ') //To eliminate spaces
i++;
switch(state)
{
case 0: if(str[i]=='i') state=1; //if
else if(str[i]=='w') state=3; //while
else if(str[i]=='d') state=8; //do
else if(str[i]=='e') state=10; //else
else if(str[i]=='f') state=14; //for
else if(isalpha(str[i]) || str[i]=='_')
{
state=17;
startid=i;
} //identifiers

else if(str[i]=='<') state=19;


//relational '<' or '<='

else if(str[i]=='>') state=21;

Submitted By:INRDAJEET GOUR 16 | P a g e


Programming File: Compiler Design 0112CS071038

//relational '>' or '>='

else if(str[i]=='=') state=23;


//relational '==' or assignment '='

else if(isdigit(str[i]))
{
state=25; startcon=i;
}
//constant

else if(str[i]=='(') state=26;


//special characters '('

else if(str[i]==')') state=27;


//special characters ')'

else if(str[i]==';') state=28;


//special characters ';'

else if(str[i]=='+') state=29;


//operator '+'

else if(str[i]=='-') state=30;


//operator '-'

break;

//States for 'if'


case 1: if(str[i]=='f') state=2;
else { state=17; startid=i-1; i--; }
break;
case 2: if(str[i]=='(' || str[i]==NULL)
{
printf("if : Keyword \n");
state=0;
i--;
}
else { state=17; startid=i-2; i--; }
break;

//States for 'while'


case 3: if(str[i]=='h') state=4;
else { state=17; startid=i-1; i--; }
break;
case 4: if(str[i]=='i') state=5;
else { state=17; startid=i-2; i--; }
break;
case 5: if(str[i]=='l') state=6;
else { state=17; startid=i-3; i--; }
break;

Submitted By:INRDAJEET GOUR 17 | P a g e


Programming File: Compiler Design 0112CS071038

case 6: if(str[i]=='e') state=7;


else { state=17; startid=i-4; i--; }
break;
case 7: if(str[i]=='(' || str[i]==NULL)
{
printf("while : Keyword\n");
state=0;
i--;
}
else { state=17; startid=i-5; i--; }
break;

//States for 'do'


case 8: if(str[i]=='o') state=9;
else { state=17; startid=i-1; i--; }
break;
case 9: if(str[i]=='{' || str[i]==' ' || str[i]==NULL || str[i]=='(')
{
printf("do : Keyword\n");
state=0;
i--;
}
break;

//States for 'else'


case 10: if(str[i]=='l') state=11;
else { state=17; startid=i-1; i--; }
break;
case 11: if(str[i]=='s') state=12;
else { state=17; startid=i-2; i--; }
break;
case 12: if(str[i]=='e') state=13;
else { state=17; startid=i-3; i--; }
break;
case 13: if(str[i]=='{' || str[i]==NULL)
{
printf("else : Keyword\n");
state=0;
i--;
}
else { state=17; startid=i-4; i--; }
break;

//States for 'for'


case 14: if(str[i]=='o') state=15;
else { state=17; startid=i-1; i--; }
break;
case 15: if(str[i]=='r') state=16;
else { state=17; startid=i-2; i--; }
break;
case 16: if(str[i]=='(' || str[i]==NULL)

Submitted By:INRDAJEET GOUR 18 | P a g e


Programming File: Compiler Design 0112CS071038

{
printf("for : Keyword\n");
state=0;
i--;
}
else { state=17; startid=i-3; i--; }
break;

//States for identifiers


case 17:

if(isalnum(str[i]) || str[i]=='_')
{
state=18; i++;
}
else if(str[i]==NULL||str[i]=='<'||str[i]=='>'||str[i]=='('||str[i]==')'||str[i]==';'||str[i]=='='||
str[i]=='+'||str[i]=='-') state=18;
i--;
break;

case 18:
if(str[i]==NULL || str[i]=='<' || str[i]=='>' || str[i]=='(' || str[i]==')' || str[i]==';' || str[i]=='=' ||
str[i]=='+' ||str[i]=='-')
{
endid=i-1;
printf("");
for(j=startid; j<=endid; j++)
printf("%c ", str[j]);
printf(" : Identifier \n");
state=0;
i--;
}
break;

//States for relational operator '<' & '<='


case 19: if(str[i]=='=') state=20;
else if(isalnum(str[i]) || str[i]=='_')
{
printf("< : Relational operator \n");
i--;
state=0;
}
break;
case 20: if(isalnum(str[i]) || str[i]=='_')
{
printf("<= : Relational operator \n");
i--;
state=0;
}
break;

Submitted By:INRDAJEET GOUR 19 | P a g e


Programming File: Compiler Design 0112CS071038

//States for relational operator '>' & '>='


case 21: if(str[i]=='=') state=22;
else if(isalnum(str[i]) || str[i]=='_')
{
printf("> : Relational operator \n");
i--;
state=0;
}
break;
case 22: if(isalnum(str[i]) || str[i]=='_')
{
printf(">= : Relational operator\n");
i--;
state=0;
}
break;

//States for relational operator '==' & assignment operator '='


case 23: if(str[i]=='=') state=24;
else
{
printf("= : Assignment operator\n");
i--;
state=0;
}
break;
case 24: if(isalnum(str[i]))
{
printf("== : Relational operator \n");
state=0;
i--;
}
break;

//States for constants


case 25: if(isalpha(str[i]))
{
printf("*** ERROR ***");
puts(str);
for(j=0; j<i; j++)
printf(" ");
printf("^");
printf("Error at position %dAlphabet cannot follow digit", i);
state=99;
}
else if(str[i]=='(' || str[i]==')' || str[i]=='<' || str[i]=='>' || str[i]==NULL || str[i]==';' || str[i]=='=')
{
endcon=i-1;
printf("");
for(j=startcon; j<=endcon; j++)
printf("%c \n", str[j]);

Submitted By:INRDAJEET GOUR 20 | P a g e


Programming File: Compiler Design 0112CS071038

printf(" : Constant\n");
state=0;
i--;
}
break;

//State for special character '('


case 26: printf(" ( : Special character\n");
startid=i;
state=0;
i--;
break;

//State for special character ')'


case 27: printf(" ) : Special character\n");
state=0;
i--;
break;

//State for special character ';'


case 28: printf(" ; : Special character\n");
state=0;
i--;
break;

//State for operator '+'


case 29: printf(" + : Operator\n");
state=0;
i--;
break;

//State for operator '-'


case 30: printf(" - : Operator\n");
state=0;
i--;
break;

//Error State
case 99: goto END;
}
i++;
}
printf("End of program");
END:
getch();
}

Submitted By:INRDAJEET GOUR 21 | P a g e


Programming File: Compiler Design 0112CS071038

OUTPUT
*** Lexical Analysis ***

Enter the string: for(x1=0; x1<=10; x1++);

Analysis:

for : Keyword
( : Special character
x1 : Identifier
= : Assignment operator
0 : Constant
; : Special character
x1 : Identifier
<= : Relational operator
10 : Constant
; : Special character
x1 : Identifier
+ : Operator
+ : Operator
) : Special character
; : Special character

End of program

Submitted By:INRDAJEET GOUR 22 | P a g e


Programming File: Compiler Design 0112CS071038

PROGRAM NO 5
OBJECTIVE: Implement Syntax Analyzer.

CODE:
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<process.h>
void main()
{
int ans,I;
char
*all_key[]={“int”,”char”,”float”,”double”,”auto”,”const”,”default”,”extern”,”far”,”long”,”near”,”regist
er”,”short”.”signed”,”do”,”else”,”goto”,”if”,”return”,”typedef”,”union”,”while”};
char input_key[10];
clrscr();
cout<<”enter the keyword “;
cin>>input_key;
for(i=0;i<32;i++)
{
ans=strcmp(input_key,all_key[i]);
if(ans==0)
{
cout<<”Correct Keyword”;
getch();
exit(0);
}
}
cout<<”\n Incorrect keyword”;
getch();
exit(0);
}

Submitted By:INRDAJEET GOUR 23 | P a g e


Programming File: Compiler Design 0112CS071038

OUTPUT
Enter the keyword: if

Correct keyword

Submitted By:INRDAJEET GOUR 24 | P a g e


Programming File: Compiler Design 0112CS071038

PROGRAM NO 6
OBJECTIVE: Program to remove Left Recursion.

CODE:
#include<iostream.h>
#include<conio.H>
#include<string.h>
//void rec(char,int) ;
void main()
{
int var;
int n,z,x=0;
char prod[10][10],s[10],alpha[10][10],res[10][10];
int i,j,k,len,ctr=0;
clrscr();
cout<<" Enter Production for %c------>",arr[i][0] ";
gets(arr[i+1]);
for(i=0;i<n;i++)
cin>>&prod[i][j];
if(prod[i][0]==prod[i][3])
{
k=0;
s[ctr]=prod[i][0];
len=strlen(prod[i]);
for(j=4;j<len;j++)
{
alpha[ctr][k]=prod[i][j];
k++;
}
ctr++;
}
for(i=0;i<ctr;i++)
getch();
void rec()
for(j=0;j<n;j++)
{
if(prod[j][0]==var)
{
if(prod[j][3]!=var)
{
strcat(res[x],prod[j]);
cout<<"\n"<<res[x]<<var;
x++;
cout<<"\n"<<var;
x++ ;
}
}
}
}

Submitted By:INRDAJEET GOUR 25 | P a g e


Programming File: Compiler Design 0112CS071038

OUTPUT
Enter Production for -----AAa/Bb/a
A BbA/aA
AaA/

Submitted By:INRDAJEET GOUR 26 | P a g e


Programming File: Compiler Design 0112CS071038

PROGRAM NO 7
OBJECTIVE: Implement a 3 Address Code Generator.

CODE:
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<process.h>

void pm();
void plus();
void div();
int i,ch,j,l,addr=100;
char ex[10],exp[10],exp1[10],exp2[10],id1[5],op[5],id2[5];
void main()
{
clrscr();
while(1)
{
printf("\n1.assignment\n2.arithmetic\n3.relational\n4.Exit\nEnter the choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the expression with assignment operator:");
scanf("%s",exp);
l=strlen(exp);
exp2[0]='\0';
i=0;
while(exp[i]!='=')
{
i++;
}
strncat(exp2,exp,i);
strrev(exp);
exp1[0]='\0';
strncat(exp1,exp,l-(i+1));
strrev(exp1);
printf("Three address code:\ntemp=%s\n%s=temp\n",exp1,exp2);
break;

case 2:
printf("\nEnter the expression with arithmetic operator:");
scanf("%s",ex);
strcpy(exp,ex);
l=strlen(exp);
exp1[0]='\0';

for(i=0;i<l;i++)
{
if(exp[i]=='+'||exp[i]=='-')
{
if(exp[i+2]=='/'||exp[i+2]=='*')
{
pm();
break;

Submitted By:INRDAJEET GOUR 27 | P a g e


Programming File: Compiler Design 0112CS071038

}
else
{
plus();
break;
}
}
else if(exp[i]=='/'||exp[i]=='*')
{
div();
break;
}
}
break;

case 3:
printf("Enter the expression with relational operator");
scanf("%s%s%s",&id1,&op,&id2);
if(((strcmp(op,"<")==0)||(strcmp(op,">")==0)||(strcmp(op,"<=")==0)||(strcmp(op,">=")==0)||
(strcmp(op,"==")==0)||(strcmp(op,"!=")==0))==0)
printf("Expression is error");
else
{
printf("\n%d\tif %s%s%s goto %d",addr,id1,op,id2,addr+3);
addr++;
printf("\n%d\t T:=0",addr);
addr++;
printf("\n%d\t goto %d",addr,addr+2);
addr++;
printf("\n%d\t T:=1",addr);
}
break;
case 4:
exit(0);
}
}
}
void pm()
{
strrev(exp);
j=l-i-1;
strncat(exp1,exp,j);
strrev(exp1);
printf("Three address code:\ntemp=%s\ntemp1=%c%ctemp\n",exp1,exp[j+1],exp[j]);
}
void div()
{
strncat(exp1,exp,i+2);
printf("Three address code:\ntemp=%s\ntemp1=temp%c%c\n",exp1,exp[i+2],exp[i+3]);
}
void plus()
{
strncat(exp1,exp,i+2);
printf("Three address code:\ntemp=%s\ntemp1=temp%c%c\n",exp1,exp[i+2],exp[i+3]);
}

Submitted By:INRDAJEET GOUR 28 | P a g e


Programming File: Compiler Design 0112CS071038

OUTPUT
1. Assignment

2. Arithmetic

3. Relational

4. Exit

Enter the choice: 1

Enter the expression with assignment operator: A+B=C

Three address code:

Temp=C

A+B=Temp

Submitted By:INRDAJEET GOUR 29 | P a g e


Programming File: Compiler Design 0112CS071038

PROGRAM NO 8
OBJECTIVE: Create Quadruples, Triples and Indirect Triples of a grammar.

CODE:
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
clrscr();
char arr[10][10],a[10][10];
int i,n,x[10];
cout<<"\n Enter the no. of string";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"\n Enter the string"<<i+1;
cin>>arr[i];
}
for(i=0;i<n;i++)
{
x[i]=strlen(arr[i]);
if(x[i]>4)
{
a[i][0]=arr[i][0]; a[i][1]=arr[i][3]; a[i][2]=arr[i][2]; a[i][3]=arr[i][4];
}
else
{
a[i][0]=arr[i][0]; a[i][0]=arr[i][1]; a[i][0]=arr[i][2];
}
}
cout<<"The quadruples are ";
for(i=0;i<n;i++)
{
cout<<"\n"<<a[i][0]; cout<<"\t"<<a[i][3]; cout<<"\t"<<a[i][2]; cout<<"\t"<<a[i][4]; cout<<"\n";
}
if(x[i]>4)
{
a[i][0]=arr[i][3] ; a[i][1]=arr[i][2] ; a[i][2]=arr[i][4] ;
}
else
{
a[i][0]=arr[i][1] ;
a[i][1]=i-1;
}
cout<<"The triples are";
for(i=0;i<n;i++)
{
cout<<"\n"<<a[i][0];
cout<<"\t"<<a[i][1]; cout<<"\t"<<a[i][2]; cout<<"\t"<<a[i][3]; cout<<"\n";
}
getch();
}

Submitted By:INRDAJEET GOUR 30 | P a g e


Programming File: Compiler Design 0112CS071038

OUTPUT
Enter no. of strings: 2
Enter the string 1 t=a+b
Enter the string 2 c=t
The quadruples are
t + a b
c = t
The triples are
+ a b
=

Submitted By:INRDAJEET GOUR 31 | P a g e


Programming File: Compiler Design 0112CS071038

PROGRAM NO 9
OBJECTIVE: Implement LL (1) Parser.

CODE:

#include <iostream.h>
#include <conio.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void main()
{
clrscr();
int i=0,j=0,k=0,m=0,n=0,o=0,o1=0,var=0,l=0,f=0,c=0,f1=0;
char str[30],str1[40]="E",temp[20],temp1[20],temp2[20],tt[20],t3[20];
strcpy(temp1,'\0');
strcpy(temp2,'\0');
char t[10];
char array[6][5][10] = {
"NT", "<id>","+","*",";",
"E", "Te","Error","Error","Error",
"e", "Error","+Te","Error","\0",
"T", "Vt","Error","Error","Error",
"t", "Error","\0","*Vt","\0",
"V", "<id>","Error","Error","Error"
};
cout << "\n\tLL(1) PARSER TABLE \n";
for(i=0;i<6;i++)
{
for(j=0;j<5;j++)
{
cout.setf(ios::right);
cout.width(10);
cout<<array[i][j];
}
cout<<endl;
}
cout << endl;
cout << "\n\tENTER THE STRING :";
gets(str);
if(str[strlen(str)-1] != ';')
{
cout << "END OF STRING MARKER SHOULD BE ';'";
getch();
exit(1);
}
cout << "\n\tCHECKING VALIDATION OF THE STRING ";
cout <<"\n\t" << str1;
i=0;

while(i<strlen(str))
{
again:
if(str[i] == ' ' && i<strlen(str))
{
cout << "\n\tSPACES IS NOT ALLOWED IN SOURSE STRING ";
getch();

Submitted By:INRDAJEET GOUR 32 | P a g e


Programming File: Compiler Design 0112CS071038

exit(1);
}
temp[k]=str[i];
temp[k+1]='\0';
f1=0;
again1:
if(i>=strlen(str))
{
getch();
exit(1);
}
for(int l=1;l<=4;l++)
{
if(strcmp(temp,array[0][l])==0)
{
f1=1;
m=0,o=0,var=0,o1=0;
strcpy(temp1,'\0');
strcpy(temp2,'\0');
int len=strlen(str1);
while(m<strlen(str1) && m<strlen(str))
{
if(str1[m]==str[m])
{
var=m+1;
temp2[o1]=str1[m];
m++;
o1++;
}
else
{
if((m+1)<strlen(str1))
{
m++;
temp1[o]=str1[m];
o++;
}
else
m++;
}
}
temp2[o1] = '\0';
temp1[o] = '\0';
t[0] = str1[var];
t[1] = '\0';
for(n=1;n<=5;n++)
{
if(strcmp(array[n][0],t)==0)
break;
}
strcpy(str1,temp2);
strcat(str1,array[n][l]);
strcat(str1,temp1);
cout << "\n\t" <<str1;
getch();

if(strcmp(array[n][l],'\0')==0)
{
if(i==(strlen(str)-1))

Submitted By:INRDAJEET GOUR 33 | P a g e


Programming File: Compiler Design 0112CS071038

{
int len=strlen(str1);
str1[len-1]='\0';
cout << "\n\t"<<str1;
cout << "\n\n\tENTERED STRING IS VALID";
getch();
exit(1);
}
strcpy(temp1,'\0');
strcpy(temp2,'\0');
strcpy(t,'\0');
goto again1;
}
if(strcmp(array[n][l],"Error")==0)
{
cout << "\n\tERROR IN YOUR SOURCE STRING";
getch();
exit(1);
}
strcpy(tt,'\0');
strcpy(tt,array[n][l]);
strcpy(t3,'\0');
f=0;
for(c=0;c<strlen(tt);c++)
{
t3[c]=tt[c];
t3[c+1]='\0';
if(strcmp(t3,temp)==0)
{
f=0;
break;
}
else
f=1; }
if(f==0)
{
strcpy(temp,'\0');
strcpy(temp1,'\0');
strcpy(temp2,'\0');
strcpy(t,'\0');
i++;
k=0;
goto again;
}
else
{
strcpy(temp1,'\0');
strcpy(temp2,'\0');
strcpy(t,'\0');
goto again1;
} } }
i++;
k++;
}
if(f1==0)
cout << "\nENTERED STRING IS INVALID";
else
cout << "\n\n\tENTERED STRING IS VALID";
getch(); }

Submitted By:INRDAJEET GOUR 34 | P a g e


Programming File: Compiler Design 0112CS071038

OUTPUT
PARSER TABLE

NT <id> + * ;
E Te Error Error Error
e Error +Te Error
T Vt Error Error Error
t Error *Vt
V <id> Error Error Error

Submitted By:INRDAJEET GOUR 35 | P a g e


Programming File: Compiler Design 0112CS071038

PROGRAM NO 10
OBJECTIVE: Implement Brute Force Technique of top down parsing.

CODE:

typedef enum {ident, number, lparen, rparen, times, slash, plus,


minus, eql, neq, lss, leq, gtr, geq, callsym, beginsym, semicolon,
endsym, ifsym, whilesym, becomes, thensym, dosym, constsym, comma,
varsym, procsym, period, oddsym} Symbol;

Symbol sym;
void getsym(void);
void error(const char msg[]);
void expression(void);

int accept(Symbol s) {
if (sym == s) {
getsym();
return 1;
}
return 0;
}

int expect(Symbol s) {
if (accept(s))
return 1;
error("expect: unexpected symbol");
return 0;
}

void factor(void) {
if (accept(ident)) {
;
} else if (accept(number)) {
;
} else if (accept(lparen)) {
expression();
expect(rparen);
} else {
error("factor: syntax error");
getsym();
}
}

void term(void) {
factor();
while (sym == times || sym == slash) {
getsym();
factor();
}
}

void expression(void) {
if (sym == plus || sym == minus)
getsym();
term();

Submitted By:INRDAJEET GOUR 36 | P a g e


Programming File: Compiler Design 0112CS071038

while (sym == plus || sym == minus) {


getsym(); term();
}}
void condition(void) {
if (accept(oddsym)) {
expression();
} else { expression();
if (sym == eql || sym == neq || sym == lss || sym == leq || sym == gtr || sym == geq) {
getsym(); expression();
} else {
error("condition: invalid operator");
getsym();
} }}
void statement(void) {
if (accept(ident)) {
expect(becomes);
expression();
} else if (accept(callsym)) {
expect(ident);
} else if (accept(beginsym)) {
do { statement();
} while (accept(semicolon));
expect(endsym);
} else if (accept(ifsym)) {
condition();
expect(thensym);
statement();
} else if (accept(whilesym)) {
condition();
expect(dosym);
statement();
}}
void block(void) {
if (accept(constsym)) {
do {
expect(ident);
expect(eql);
expect(number);
} while (accept(comma));
expect(semicolon);
}
if (accept(varsym)) {
do {
expect(ident);
} while (accept(comma));
expect(semicolon);
}
while (accept(procsym)) {
expect(ident);
expect(semicolon);
block();
expect(semicolon);
}
statement();
}

void program(void) {
getsym();
block();

Submitted By:INRDAJEET GOUR 37 | P a g e


Programming File: Compiler Design 0112CS071038

expect(period); }
OUTPUT
PARSER TABLE

NT <id> + * ;
E Te Error Error Error
e Error +Te Error
T Vt Error Error Error
t Error *Vt
V <id> Error Error Error

Submitted By:INRDAJEET GOUR 38 | P a g e

You might also like