0% found this document useful (0 votes)
44 views

CD Lab Manual

The program aims to simulate the first and follow functions for a given grammar. It takes 8 productions as input in the form A->BC. It finds the unique non-terminals and initializes their first and follow tables. It calls the findFirst and findFollow functions to populate the tables. The findFirst function recursively finds the first set by checking the productions. The findFollow function propagates the follow sets by checking the right context and calling other functions. Finally, it prints the populated first and follow tables.

Uploaded by

SRIMANTH BATTULA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

CD Lab Manual

The program aims to simulate the first and follow functions for a given grammar. It takes 8 productions as input in the form A->BC. It finds the unique non-terminals and initializes their first and follow tables. It calls the findFirst and findFollow functions to populate the tables. The findFirst function recursively finds the first set by checking the productions. The findFollow function propagates the follow sets by checking the right context and calling other functions. Finally, it prints the populated first and follow tables.

Uploaded by

SRIMANTH BATTULA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

PROGRAM-1

AIM: Write a C program to identify different types of tokens in a given program.


Source Code:
#include<string.h>
#include<ctype.h>
#include<stdio.h>
void keyword(char[]);
void main()
{
FILE *f1,*f2,*f3;
char c,str[10],st1[10];
int num[100],lineno=0,tokenvalue=0,i=0,j=0,k=0;
clrscr();
printf("\nEnter the c program\n");
f1=fopen("input.txt","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input.txt","r");
f2=fopen("identifier.txt","w");
f3=fopen("specialchar.txt","w");
while((c=getc(f1))!=EOF)
{
if(isdigit(c))
{
tokenvalue=c-48;
c=getc(f1);
while(isdigit(c))
{
tokenvalue=tokenvalue*10+(c-48);
c=getc(f1);
}
num[i++]=tokenvalue;
ungetc(c,f1);
}
else if(isalpha(c))
{
putc(c,f2);
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
putc(c,f2);
c=getc(f1);
}
putc(' ',f2);
ungetc(c,f1);
}
else if(c==' '||c=='\t')
printf(" ");
else if(c=='\n')
lineno++;
else putc(c,f3);
}
fclose(f2);
fclose(f3);
fclose(f1);
printf("\nThe numbers in the program are:");
for(j=0;j<i;j++)
printf(" %d ",num[j]);
printf("\n");
f2=fopen("identifier.txt","r");
k=0;
printf("The keywords and identifiersare:");
while((c=getc(f2))!=EOF)
{
if(c!=' ')
str[k++]=c;
else
{
str[k]='\0';
keyword(str);
k=0;
}
}
fclose(f2);
f3=fopen("specialchar.txt","r");
printf("\nSpecial characters are");
while((c=getc(f3))!=EOF)
printf(" %c ",c);
printf("\n");
fclose(f3);
printf("Total no. of lines are:%d",lineno);
getch();
}
void keyword(char str[10])
{
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||
strcmp("int",str)==0||strcmp("float",str)==0||strcmp("char",str)==0||
strcmp("double",str)==0||strcmp("static",str)==0||
strcmp("switch",str)==0||strcmp("case",str)==0)
printf("\n%s is a keyword",str);
else
printf("\n%s is an identifier",str);
}

Output:

Enter the c program int main()


{
int a=10,20;
char ch;
float f;
}
Ctrl+Z
The numbers in the program are: 10 20
The keywords and identifiers are:
int is a keyword main is an identifier int is a keyword
a is an identifier
char is a keyword ch is an identifier float is a keyword f is an identifier
Special characters are ( ) { = , ; ; ; }
Total no. of lines are:5

PROGRAM-2
Aim: Write a Lex program to implement a Lexical analyzer using Lex tool.
Source Code:
/* Program name as “lexicalfile.l” */
%{
/* program to recognize a c program */
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* { printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}
int |
float |
char |
double |
while |
for |
do |
if |
break |
continue |
void |
switch |
case |
long |
struct |
const |
typedef |
return |
else |
goto {printf("\n\t%s is a KEYWORD",yytext);}
"/*" {COMMENT = 1;}
"*/" {COMMENT = 0;}
{identifier}\( {if(!COMMENT) printf("\n\nFUNCTION\n\t%s",yytext);}
\{ {if(!COMMENT) printf("\n BLOCK BEGINS");}
\} {if(!COMMENT) printf("\n BLOCK ENDS");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\" {if(!COMMENT) printf("\n\t%s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n\t%s is a NUMBER",yytext);}
\)(\;)? {if(!COMMENT) printf("\n\t");ECHO;printf("\n");}
\( ECHO;
= {if(!COMMENT)printf("\n\t%s is an ASSIGNMENT OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
%%
int main(int argc,char **argv)
{
if (argc > 1)
{
FILE *file;
file = fopen(argv[1],"r");
if(!file)
{
printf("could not open %s \n",argv[1]);
exit(0);
}
yyin = file;
}
yylex();
printf("\n\n");
return 0;
} int yywrap()
{
return 0;
}
Input:
$vi input.c
#include<stdio.h>
main()
{
int a,b;
}
Output:
$lex lexicalfile.l
$cc lex.yy.c
$./a.out ex.c
#include<stdio.h> is a PREPROCESSOR DIRECTIVE
FUNCTION
main (
)
BLOCK BEGINS
int is a KEYWORD
a IDENTIFIER
b IDENTIFIER
BLOCK ENDS
PROGRAM-3
Aim: Write a C program to Simulate Lexical Analyzer to validating a given Operator.
Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
char s[5];
clrscr();
printf("\n Enter any operator:");
gets(s);
switch(s[0])
{
case'>': if(s[1]=='=')
printf("\n Greater than or equal");
else
printf("\n Greater than");
break;
case'<': if(s[1]=='=')
printf("\n Less than or equal");
else
printf("\nLess than");
break;
case'=': if(s[1]=='=')
printf("\nEqual to");
else
printf("\nAssignment");
break;
case'!': if(s[1]=='=')
printf("\nNot Equal");
else
printf("\n Bit Not");
break;
case'&': if(s[1]=='&')
printf("\nLogical AND");
else
printf("\n Bitwise AND");
break;
case'|': if(s[1]=='|')
printf("\nLogical OR");
else
printf("\nBitwise OR");
break;
case'+': printf("\n Addition");
break;
case'-': printf("\nSubstraction");
break;
case'*': printf("\nMultiplication");
break;
case'/': printf("\nDivision");
break;
case'%': printf("Modulus");
break;
default: printf("\n Not a operator");
}
getch();
}
Input
Enter any operator: *
Output
Multiplication
PROGRAM-4
Aim: Write a C program to implement the Brute force technique of Top down Parsing.
Source Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int a[30];
clrscr();
int min=10000,temp=0,i,lev,n,noofc,z;
printf("please enter how many number");
scanf(“%d”,&n);
for(i=0;i<n;i++)
a[i]=0;
printf("enter value of root");
scanf(“%d”,&a[0]);
for(i=1;i<=n/2;i++)
{
printf("please enter no of child of parent with value %d",a[i-1]);
scanf(“%d”,&noofc);
for(int j=1;j<=noofc;j++)
{z=(i)*2+j-2;
printf("please enter value of child");
scanf(“%d”,&a[z]);
}
}
for(i=n-1;i>=n/2;i--)
{
temp=0;
for(int j=i+1;j>=1;j=j/2)
temp=temp+a[j-1];
if(temp<min)
min=temp;
printf("temp min is:%d\n",temp);

}
printf(" min is:%d\n",min);
getch();
}

PROGRAM-5
Aim: Write a C program to implement a Recursive Descent Parser.
Source Code:
#include<stdio.h>

#include<string.h>

#include<ctype.h>

char input[10];

int i,error;

void E();

void T();

void Eprime();

void Tprime();

void F();

main()

i=0;

error=0;
printf("Enter an arithmetic expression : ");

gets(input);

E();

if(strlen(input)==i&&error==0)

printf("\nAccepted..!!!\n");

else

printf("\nRejected..!!!\n");

void E()

T();

Eprime();

void Eprime()

if(input[i]=='+')

i++;

T();

Eprime();

void T()

{
F();

Tprime();

void Tprime()

if(input[i]=='*')

i++;

F();

Tprime();

} void F()

if(isalnum(input[i])

i++;

else if(input[i]=='(')

i++;

E();

if(input[i]==')')

i++;

else

error=1;

else
error=1;

Output:

1)Enter an arithmetic expression : a+(a*a)

Accepted..!!!

2) Enter an arithmetic expression : a@a($

Rejected..!!!

PROGRAM-6
AIM: Write a Program to simulate first and follow functions.
Source Code:
#include<stdio.h>
#include<ctype.h>
char a[8][8];
struct firTab
{
int n;
char firT[5];
};
struct folTab
{
int n;
char folT[5];
};
struct folTab follow[5];
struct firTab first[5];
int col;
void findFirst(char,char);
void findFollow(char,char);
void folTabOperation(char,char);
void firTabOperation(char,char);
void main()
{
int i,j,c=0,cnt=0;
char ip;
char b[8];
printf("\nFIRST AND FOLLOW SET \n\nenter 8 productions in format A->B+T\n");
for(i=0;i<8;i++)
{
scanf("%s",&a[i]);
}
for(i=0;i<8;i++)
{ c=0;
for(j=0;j<i+1;j++)
{
if(a[i][0] == b[j])
{
c=1;
break;
}
}
if(c !=1)
{
b[cnt] = a[i][0];
cnt++;
}
}
printf("\n");
for(i=0;i<cnt;i++)
{
col=1;
first[i].firT[0] = b[i];
first[i].n=0;
findFirst(b[i],i);
}
for(i=0;i<cnt;i++)
{
col=1;
follow[i].folT[0] = b[i];
follow[i].n=0;
findFollow(b[i],i);
}
printf("\n");
for(i=0;i<cnt;i++)
{
for(j=0;j<=first[i].n;j++)
{
if(j==0)
{
printf("First(%c) : {",first[i].firT[j]);
}
else
{
printf(" %c",first[i].firT[j]);
}
}
printf(" } ");
printf("\n");
}
printf("\n");
for(i=0;i<cnt;i++)
{
for(j=0;j<=follow[i].n;j++)
{
if(j==0)
{
printf("Follow(%c) : {",follow[i].folT[j]);
}
else
{
printf(" %c",follow[i].folT[j]);
}
}
printf(" } ");
printf("\n");
}
}
void findFirst(char ip,char pos)
{
int i;
for(i=0;i<8;i++)
{
if(ip == a[i][0])
{
if(isupper(a[i][3]))
{
findFirst(a[i][3],pos);
}
else
{
first[pos].firT[col]=a[i][3];
first[pos].n++;
col++;
}
}
}
}
void findFollow(char ip,char row)
{ int i,j;
if(row==0 && col==1)
{
follow[row].folT[col]= '$';
col++;
follow[row].n++;
}
for(i=0;i<8;i++)
{
for(j=3;j<7;j++)
{
if(a[i][j] == ip)
{
if(a[i][j+1] == '\0')
{
if(a[i][j] != a[i][0])
{
folTabOperation(a[i][0],row);
}
}
else if(isupper(a[i][j+1]))
{ if(a[i][j+1] != a[i][0])
{
firTabOperation(a[i][j+1],row);
}
}
else
{
follow[row].folT[col] = a[i][j+1];
col++;
follow[row].n++;
}
}
}
}
}
void folTabOperation(char ip,char row)
{ int i,j;
for(i=0;i<5;i++)
{
if(ip == follow[i].folT[0])
{
for(j=1;j<=follow[i].n;j++)
{
follow[row].folT[col] = follow[i].folT[j];
col++;
follow[row].n++;
}
}
}
}
void firTabOperation(char ip,char row)
{
int i,j;
for(i=0;i<5;i++)
{
if(ip == first[i].firT[0])
{
for(j=1;j<=first[i].n;j++)
{
if(first[i].firT[j] != '0')
{
follow[row].folT[col] = first[i].firT[j];
follow[row].n++;
col++;
}
else
{
folTabOperation(ip,row);
}
}
}
}

Output:
PROGRAM-7
AIM: Write a C program for eliminating the left recursion and left factoring of a given grammar

Eliminate Left Recursion in C Program:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define SIZE 20

int main()
{
char pro[SIZE], alpha[SIZE], beta[SIZE];
int nont_terminal,i,j, index=3;

printf("Enter the Production as E->E|A: ");


scanf("%s", pro);

nont_terminal=pro[0];
if(nont_terminal==pro[index]) //Checking if the Grammar is LEFT RECURSIVE
{
//Getting Alpha
for(i=++index,j=0;pro[i]!='|';i++,j++){
alpha[j]=pro[i];
//Checking if there is NO Vertical Bar (|)
if(pro[i+1]==0){
printf("This Grammar CAN'T BE REDUCED.\n");
exit(0); //Exit the Program
}
}
alpha[j]='\0'; //String Ending NULL Character

if(pro[++i]!=0) //Checking if there is Character after Vertical Bar (|)


{
//Getting Beta
for(j=i,i=0;pro[j]!='\0';i++,j++){
beta[i]=pro[j];
}
beta[i]='\0'; //String Ending NULL character

//Showing Output without LEFT RECURSION


printf("\nGrammar Without Left Recursion: \n\n");
printf(" %c->%s%c'\n", nont_terminal,beta,nont_terminal);
printf(" %c'->%s%c'|#\n", nont_terminal,alpha,nont_terminal);
}
else
printf("This Grammar CAN'T be REDUCED.\n");
}
else
printf("\n This Grammar is not LEFT RECURSIVE.\n");
}

Left Factoring Program in C:

#include<stdio.h>
#include<string.h>
int main()
{
char gram[20],part1[20],part2[20],modifiedGram[20],newGram[20],tempGram[20];
int i,j=0,k=0,l=0,pos;
printf("Enter Production : A->");
gets(gram);
for(i=0;gram[i]!='|';i++,j++)
part1[j]=gram[i];
part1[j]='\0';
for(j=++i,i=0;gram[j]!='\0';j++,i++)
part2[i]=gram[j];
part2[i]='\0';
for(i=0;i<strlen(part1)||i<strlen(part2);i++){
if(part1[i]==part2[i]){
modifiedGram[k]=part1[i];
k++;
pos=i+1;
}
}
for(i=pos,j=0;part1[i]!='\0';i++,j++){
newGram[j]=part1[i];
}
newGram[j++]='|';
for(i=pos;part2[i]!='\0';i++,j++){
newGram[j]=part2[i];
}
modifiedGram[k]='X';
modifiedGram[++k]='\0';
newGram[j]='\0';
printf("\nGrammar Without Left Factoring : : \n");
printf(" A->%s",modifiedGram);
printf("\n X->%s\n",newGram);
}

PROGRAM-8
Aim: Write a C program to check the validity of input string using Predictive Parser.

Source Code:

#include<stdio.h>
#include<conio.h>
#include<string.h>
char prol[7][10]={"S","A","A","B","B","C","C"};
char pror[7][10]={"A","Bb","Cd","aB","@","Cc","@"};
char prod[7][10]={"S->A","A->Bb","A->Cd","B->aB","B->@","C->Cc","C->@"};
char first[7][10]={"abcd","ab","cd","a@","@","c@","@"};
char follow[7][10]={"$","$","$","a$","b$","c$","d$"};
char table[5][6][10];
numr(char c)
{
switch(c)
{
case 'S': return 0;
case 'A': return 1;
case 'B': return 2;
case 'C': return 3;
case 'a': return 0;
case 'b': return 1;
case 'c': return 2;
case 'd': return 3;
case '$': return 4;
}
return(2);
}
void main()
{
int i,j,k;
clrscr();
for(i=0;i<5;i++)
for(j=0;j<6;j++)
strcpy(table[i][j]," ");
printf("\nThe following is the predictive parsing table for the following grammar:\n");
for(i=0;i<7;i++)
printf("%s\n",prod[i]);
printf("\nPredictive parsing table is\n");
fflush(stdin);
for(i=0;i<7;i++)
{
k=strlen(first[i]);
for(j=0;j<10;j++)
if(first[i][j]!='@')
strcpy(table[numr(prol[i][0])+1][numr(first[i][j])+1],prod[i]);
}
for(i=0;i<7;i++)
{
if(strlen(pror[i])==1)
{
if(pror[i][0]=='@')
{
k=strlen(follow[i]);
for(j=0;j<k;j++)
strcpy(table[numr(prol[i][0])+1][numr(follow[i][j])+1],prod[i]);
}
}
}
strcpy(table[0][0]," ");
strcpy(table[0][1],"a");
strcpy(table[0][2],"b");
strcpy(table[0][3],"c");
strcpy(table[0][4],"d");
strcpy(table[0][5],"$");
strcpy(table[1][0],"S");
strcpy(table[2][0],"A");
strcpy(table[3][0],"B");
strcpy(table[4][0],"C");
printf("\n--------------------------------------------------------\n");
for(i=0;i<5;i++)
for(j=0;j<6;j++)
{ printf("%-10s",table[i][j]);
if(j==5)
printf("\n--------------------------------------------------------\n");
}
getch();
}

Output:
PROGRAM -09
Aim: Write a C program for implementation of LR parsing algorithm to accept a given input
string.

Source Code:

#include<stdio.h>

#include<string.h>

char stack[30];

int top=-1;

void push(char c)

top++;

stack[top]=c;

char pop()

char c;

if(top!=-1)

c=stack[top];

top--;

return c;
}

return'x';

void printstat()

int i;

printf("\n\t\t\t $");

for(i=0;i<=top;i++)

printf("%c",stack[i]);

void main()

int i,j,k,l;

char s1[20],s2[20],ch1,ch2,ch3;

clrscr();

printf("\n\n\t\t LR PARSING");

printf("\n\t\t ENTER THE EXPRESSION");

scanf("%s",s1);

l=strlen(s1);

j=0;

printf("\n\t\t $");

for(i=0;i<l;i++)< span="" style="box-sizing: border-box;">

{
if(s1[i]=='i' && s1[i+1]=='d')

s1[i]=' ';

s1[i+1]='E';

printstat(); printf("id");

push('E');

printstat();

else if(s1[i]=='+'||s1[i]=='-'||s1[i]=='*' ||s1[i]=='/' ||s1[i]=='d')

push(s1[i]);

printstat();

printstat();

l=strlen(s2);

while(l)

ch1=pop();

if(ch1=='x')

printf("\n\t\t\t $");
break;

if(ch1=='+'||ch1=='/'||ch1=='*'||ch1=='-')

ch3=pop();

if(ch3!='E')

printf("errror");

exit();

else

push('E');

printstat();

ch2=ch1;

getch();

}
OUTPUT:

LR PARSING

ENTER THE EXPRESSION


id+id*id-id

$id

$E

$E+

$E+id

$E+E

$E+E*

$E+E*id

$E+E*E

$E+E*E-

$E+E*E-id

$E+E*E-E

$E+E*E-E

$E+E*E

$E

PROGRAM -10
Aim: Write a C program for implementation of a Shift Reduce Parser using Stack Data Structure
to accept a given input string of a given grammar

Source Code:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
char ip_sym[15],stack[15];
int ip_ptr=0,st_ptr=0,len,i;
char temp[2],temp2[2];
char act[15];
void check();
void main()
{
clrscr();
printf("\n\t\t SHIFT REDUCE PARSER\n");
printf("\n GRAMMER\n");
printf("\n E->E+E\n E->E/E");
printf("\n E->E*E\n E->E-E\n E->id");
printf("\n enter the input symbol:\t");
gets(ip_sym);
printf("\n\t stack implementation table");
printf("\n stack\t\t input symbol\t\t action");
printf("\n \t\t \t\t \n");
printf("\n $\t\t%s$\t\t\t--",ip_sym);
strcpy(act,"shift ");
temp[0]=ip_sym[ip_ptr];
temp[1]='\0';
strcat(act,temp);
len=strlen(ip_sym);
for(i=0;i<=len-1;i++)
{
stack[st_ptr]=ip_sym[ip_ptr];
stack[st_ptr+1]='\0';
ip_sym[ip_ptr]=' ';
ip_ptr++;
printf("\n $%s\t\t%s$\t\t\t%s",stack,ip_sym,act);
strcpy(act,"shift ");
temp[0]=ip_sym[ip_ptr];
temp[1]='\0';
strcat(act,temp);
check();
st_ptr++;
}
st_ptr++;
check();
}
void check()
{
int flag=0;
temp2[0]=stack[st_ptr];
temp2[1]='\0';
if(islower(temp2[0]))
{
stack[st_ptr]='E';
flag=1;
}
if((!strcmp(temp2,"+"))||(!strcmp(temp2,"*"))||(!strcmp(temp2,"/"))||(!strcmp(temp2,"-")))
{
flag=1;
}
if((!strcmp(stack,"E+E"))||(!strcmp(stack,"E/E"))||(!strcmp(stack,"E*E"))
||(!strcmp(stack,"E-E")))
{
if(!strcmp(stack,"E+E"))
{
strcpy(stack,"E");
printf("\n $%s\t\t%s$\t\t\tE->E+E",stack,ip_sym);
}
else if(!strcmp(stack,"E/E"))
{
strcpy(stack,"E");
printf("\n $%s\t\t %s$\t\t\tE->E/E",stack,ip_sym);
}
else
if(!strcmp(stack,"E-E"))
{
strcpy(stack,"E");
printf("\n $%s\t\t %s$\t\t\tE->E-E",stack,ip_sym);
}
else
{
strcpy(stack,"E");
printf("\n $%s\t\t%s$\t\t\tE->E*E",stack,ip_sym);
}
flag=1;
st_ptr=0;
}
if(!strcmp(stack,"E")&&ip_ptr==len)
{
printf("\n $%s\t\t%s$\t\t\tACCEPT",stack,ip_sym);
getch();
exit(0);
}
if(flag==0)
{
printf("\n $%s\t\t\t%s\t\t reject",stack,ip_sym);
exit(0);
}
return;
}

Output:
PROGRAM-11
Aim: Simulate the calculator using LEX and YACC tool.
Source Code:
LEX PART:

%{

#include<stdio.h>

#include "y.tab.h"

extern int yylval;

%}

%%

[0-9]+ {

yylval=atoi(yytext);

return NUMBER;

}
[\t] ;

[\n] return 0;

. return yytext[0];

%%

int yywrap()

return 1;

YACC PART:

%{

#include<stdio.h>

int flag=0;

%}

%token NUMBER

%left '+' '-'

%left '*' '/' '%'

%left '(' ')'

%%

ArithmeticExpression: E{

printf("\nResult=%d\n",$$);

return 0;

};
E:E'+'E {$$=$1+$3;}

|E'-'E {$$=$1-$3;}

|E'*'E {$$=$1*$3;}

|E'/'E {$$=$1/$3;}

|E'%'E {$$=$1%$3;}

|'('E')' {$$=$2;}

| NUMBER {$$=$1;}

%%

void main()

printf("\nEnter Any Arithmetic Expression which can have operations Addition, Subtraction,
Multiplication, Divison, Modulus and Round brackets:\n");

yyparse();

if(flag==0)

printf("\nEntered arithmetic expression is Valid\n\n");

void yyerror()

printf("\nEntered arithmetic expression is Invalid\n\n");

flag=1;

}
OUTPUT:

PROGRAM-12
Aim: Generate YACC specification for a few syntactic categories.
Source Code:

Program name: arith_id.l

%{
/* This LEX program returns the tokens for the expression */
#include “y.tab.h”
%}

%%
“=” {printf(“\n Operator is EQUAL”);}
“+” {printf(“\n Operator is PLUS”);}
“-“ {printf(“\n Operator is MINUS”);}
“/” {printf(“\n Operator is DIVISION”);}
“*” {printf(“\n Operator is MULTIPLICATION”);}

[a-z A-Z]*[0-9]* {
printf(“\n Identifier is %s”,yytext);
return ID;
}
return yytext[0];
\n return 0;
%%

int yywrap()
{
return 1;
}

Program Name : arith_id.y

%{
#include
/* This YYAC program is for recognizing the Expression */
%}
%%
statement: A’=’E
|E{
printf(“\n Valid arithmetic expression”);
$$ = $1;
};

E: E’+’ID
| E’-’ID
| E’*’ID
| E’/’ID
| ID
;
%%
extern FILE *yyin;
main()
{
do
{
yyparse();
}while(!feof(yyin));
}

yyerror(char*s)
{
}

Output:

[root@localhost]# lex arith_id.1


[root@localhost]# yacc –d arith_id.y
[root@localhost]# gcc lex.yy.c y.tab.c
[root@localhost]# ./a.out
x=a+b;
Identifier is x
Operator is EQUAL
Identifier is a
Operator is PLUS
Identifier is b

PROGRAM-13
Aim: Write a C program for generating the three address code of a given
expression/statement.
Source Code:

/* Program to Implement 3 Address Code */


#include<stdio.h>
#include<string.h>
void pm();
void plus();
void div();
int i,ch,j,l;
char ex[10],ex1[10],exp1[10],ex2[10];
main()

while(1)

printf("\n 1.Assignment\n 2.Arithmatic\n 3.exit\n ENTER THE CHOICE:");

scanf("%d",&ch);

switch(ch)

case 1:printf("\n enter the expression with assignment operator:");

scanf("%s",ex1);

l=strlen(ex1);

ex2[0]='\0';

i=0;

while(ex1[i]!='=')
{ i++; }

strncat(ex2,ex1,i);

strrev(ex1);

exp1[0]='\0';

strncat(exp1,ex1,l-(i+1));

strrev(exp1);

printf("3 address code:\n temp=%s \n %s=temp\n",exp1,ex2);

break;

case 2:printf("\n enter the expression with arithmatic operator:");

scanf("%s",ex);

strcpy(ex1,ex);

l=strlen(ex1);

exp1[0]=' \0';

for(i=0;i<l;i++)

if(ex1[i]=='+'||ex1[i]==' -')

if(ex1[i+2]=='/'||ex1[i+2]=='*')

pm();

break;

else

plus();
break;

else if(ex1[i]=='/'||ex1[i]=='*')

div();

break;

break;

break;

case 3:exit(0);

void pm()

strrev(exp1);

j=l-i-1;

strncat(exp1,ex1,j);

strrev(exp1);

printf("3 address code:\n temp=%s\n temp1=%c%c temp\n",exp1,ex1[j+2],ex1[j]);

}
void div()

strncat(exp1,ex1,i+2);

printf("3 address code:\n temp=%s\n temp1=temp%c%c\n",exp1,ex1[l+2],ex1[i+3]);

void plus()

strncat(exp1,ex1,i+2);

printf("3 address code:\n temp=%s\n temp1=temp%c%c\n",exp1,ex1[l+2],ex1[i+3]);

OUTPUT:

1.Assignment

2.Arithmetic

3.Exit

Enter the choice:1

Enter the exp with assignment operator:a=b

3 address code: temp=b a=temp

1.Assignment

2.Arithmetic

3.Exit

Enter the choice:2

Enter the exp with arithmetic operator:a*b+c

3 address code: temp=a*b temp1=temp+c

1.Assignment

2.Arithmetic
3.Exit

Enter the choice:3

PROGRAM-14
Aim: Write a C program for implementation of a Code Generation Algorithm of a given
expression/statement.
Source Code:

/* Program to Implement Code Generation */

#include<stdio.h>

#include<string.h>

int label[20];

int no=0;

int main()

FILE *fp1,*fp2;

char fname[10],op[10],ch;

char operand1[8],operand2[8],result[8];

int i=0,j=0;

printf("\n enter the filename of intermediate code \n");

scanf("%s",&fname);

fp1=fopen(fname,"r");

fp2=fopen("target.txt","w");

if(fp1==NULL||fp2==NULL)

printf(" \n error opening the file");


exit(0);

while(!feof(fp1))

fprintf(fp2," \n");

fscanf(fp1,"%s",op);

i++;

if(check_label(i))

fprintf(fp2," \nlabel#%d",i);

if(strcmp(op,"print")==0)

fscanf(fp1,"%s",result);

fprintf(fp2," \n \tOUT%s",result);

if(strcmp(op,"goto")==0)

fscanf(fp1,"%s%s",operand1,operand2);

label[no++]=atoi(operand2);

if(strcmp(op,"[]=")==0)

fscanf(fp1,"%s%s%s",operand1,operand2,result);
fprintf(fp2,"\n\tSTORE%s[%s],%s",operand1,operand2,result);

if(strcmp(op,"uminus")==0)
{

fscanf(fp1,"%s,%s",operand1,result);

fprintf(fp2,"\n\t,LOAD%s",operand1);

fprintf(fp2,"\n\tSTORE R1,%s",result);

switch(op[0])

case '*': fscanf(fp1,"%s%s%s",operand1,operand2,result);

fprintf(fp2,"\n\t LOAD",operand1);

fprintf(fp2,"\n\t LOAD %s,R1",operand2);

fprintf(fp2,"\n\t MUL R1,R0");

fprintf(fp2,"\n\t STORE R0,%s",result);

break;

case '+': fscanf(fp1,"%s%s%s",operand1,operand2,result);

fprintf(fp2,"\n\t LOAD%s,R0",operand1);

fprintf(fp2,"\n\t LOAD %s,R1",operand2);

fprintf(fp2,"\n\t ADD R1,R0");

fprintf(fp2,"\n\t STORE R0,%s",result);

break;

case '-': fscanf(fp1,"%s%s%s",operand1,operand2,result);

fprintf(fp2,"\n\t LOAD%s,R0",operand1);

fprintf(fp2,"\n\t LOAD %s,R1",operand2);

fprintf(fp2,"\n\t SUB R1,R0");

fprintf(fp2,"\n\t STORE R0,%s",result);

break;
case '/': fscanf(fp1,"%s%s%s",operand1,operand2,result);

fprintf(fp2,"\n\t LOAD%s,R0",operand1);

fprintf(fp2,"\n\t LOAD %s,R1",operand2);

fprintf(fp2,"\n\t DIV R1,R0");

fprintf(fp2,"\n\t STORE R0,%s",result);

break;

case '=': fscanf(fp1,"%s%s",operand1,result);

fprintf(fp2," \n \t STORE %s%s",operand1,result);

break;

case '>': fscanf(fp1,"%s%s%s",operand1,operand2,result);

fprintf(fp2," \n \t LOAD%s,R0",operand1);

fprintf(fp2," \n \t JGT%S,label#%s",operand2,result);

label[no++]=atoi(result);

break;

case '<': fscanf(fp1,"%s%s%s",operand1,operand2,result);

fprintf(fp2," \n \t LOAD%s,R0",operand1);

fprintf(fp2," \n \ t JLT%S,label#%s",operand2,result);

label[no++]=atoi(result);

break;

fclose(fp2);

fclose(fp1);

fp2=fopen("target.txt","r");

if(fp2==NULL)
{

printf("error opening in file \n");

exit(0);

do

ch=fgetc(fp2);

printf("%c",ch);

} while(ch!=EOF);

fclose(fp1);

return 0;

int check_label(int k)

int i;

for(i=0;i<no;i++)

if(k==label[i])

return 1;

return 0;

Input.txt

/t3 t2 t2

uminus t2 t2
print t2

+t1 t3 t4

print t4

OUTPUT:

enter the filename of intermediate code input.txt

LOADt2,R0

LOAD t2,R1

DIV R1,R0

STORE R0,uminus

OUTt2

LOADt3,R0

LOAD t4,R1

ADD R1,R0

STORE R0,print

You might also like