Sie sind auf Seite 1von 67

A

Laboratory File
On
Compiler Design (CSP 303)
Submitted
For
Bachelor of Technology
In
Computer Science & Engineering
At

Sharda University
2020

Submitted to: Submitted By:


Ms. Latha Banda Sabin
khadka(2017006101)
Astt. Professor, CSE CSE-III Year
SET Sharda University VI sem, A - G2
Roll no: 170101184
Table of Contents
S.N Title Page No
1 Design a DFA which will accept all the strings containing even number of 0's over an alphabet {0, 2

1} and write a program to implement the DFA.


2 Design a DFA which will accept all the strings containing odd number of 1's over an alphabet {0, 1} 4

and write a program to implement the DFA.


3 Design a DFA which will accept all the strings ending with 00 over an alphabet {0, 1} and write a 6

program to implement the DFA.


4 Design a DFA which will accept all the strings containing mod 3 of 0’s over analphabet {0, 1} and 8

write a program to implement the DFA.


5 To convert regular expression into NFA. 10

6 To find string is keyword, identifier and constant or not. 12

7 To check the balanced parenthesis of an expression. 17

8 Write a program for token separation with expression. 21

9 WAP to find operator precedence relations in top down parser. 26

10 WAP to calculate leading for all non terminals. 31

11 To calculate trailing for all non terminals. 34

12 Write a program to compute FIRST function. 37

13 Write a program to compute FOLLOW function. 41

14 Write an algorithm and program on Recursive Descent parser. 44

15 C Programs for generation of three address code. 48

16 Implementation of operator precedence parser. 52

17 Write a program for recursive descent parser. 57

18 To write a C program to construct of DAG (Directed Acyclic Graph). 61

19 To write a C program to implement simple code optimization technique. 63

1|Page
1. Design a DFA which will accept all the strings containing even number of 0's over
an alphabet {0, 1} and write a program to implement the DFA.

#include<stdio.h>
#define max 100
int main()
{
char str[max],f='x',c;
printf("Do you want to check for epsilon string's case? (y/n) : ");
scanf("%c",&c);
if(c=='y'|| c=='Y')
goto flag;

printf("enter the string to be checked: ");


scanf("%s",str);
int i;
for(i=0;i<strlen(str);i++)
{
switch(f)
{
case 'x': if(str[i]=='0') f='y';
else if(str[i]=='1') f='x';
break;
case 'y': if(str[i]=='0') f='x';
else if(str[i]=='1') f='y';
break;
}
}
flag: if(f=='x') printf("\nString Accepted :Reached Final State %c",f);

2|Page
else printf("\nString Not Accepted :Reached Non Final State %c",f);
return 0;
}

Output:

3|Page
2. Design a DFA which will accept all the strings containing odd number of 1's over
an alphabet {0, 1} and write a program to implement the DFA.

#include<stdio.h>
#define max 100
main()
{
char str[max],f='x';
int i;
printf("enter the string to be checked: ");
scanf("%s",str);
for(i=0;i<strlen(str);i++)
{
switch(f)
{
case 'x': if(str[i]=='0') f='x';
else if(str[i]=='1') f='y';
break;
case 'y': if(str[i]=='0') f='y';
else if(str[i]=='1') f='x';
break;
}
}
if(f=='y') printf("\nString Accepted: Final State Reached: %c",f);
else printf("\nstring Not Accepted.Non Final State Reached: %c",f);
}

4|Page
Output:

5|Page
3. Design a DFA which will accept all the strings ending with 00 over an
alphabet {0, 1} and write a program to implement the DFA.

#include<stdio.h>
#define max 100
main()
{
char str[max],f='a';
int i;
printf("enter the string to be checked: ");
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
{
switch(f)
{
case 'a': if(str[i]=='0') f='b';
else if(str[i]=='1') f='a';
break;
case 'b': if(str[i]=='0') f='c';
else if(str[i]=='1') f='d';
break;
case 'c': if(str[i]=='0') f='c';
else if(str[i]=='1') f='d';
break;
case 'd': if(str[i]=='0') f='b';
else if(str[i]=='1') f='d';
break;
}

6|Page
}
if(f=='c') printf("\nString Accepted: Final State Reached: %c",f);
else printf("\nstring Not Accepted.Non Final State Reached: %c",f);
}

Output:

7|Page
4. Design a DFA which will accept all the strings containing mod 3 of 0’s
over analphabet {0, 1} and write a program to implement the DFA.

#include<stdio.h>
#include<conio.h>
#include<string.h>
main(){
int i=0;
int total_len=0;
int len_zero=0;
char store[20];
printf("Enter a sting containing 0/1: " );
gets(store);
total_len = strlen(store);
for(i=0;i<total_len;i++)
{
if(store[i]=='0'){len_zero++;}
}
printf("Entered string is: %s",store);
if(len_zero%3==0){
printf("\nstring is accepted");
}
else{
printf("\nstring is not accepted");
}
}

8|Page
Output:

9|Page
5. To convert regular expression into NFA.

Input: A regular expression R over alphabet Σ.


Output: A NFA n accepting the language denoted by R .
Method: We first decompose R into the primitive components. For each component we construct
a finite automaton as follows.
1. For ε we construct the NFA

2. For a in Σ we construct the NFA

3. Having constructed components for the basic regular expressions, we proceed to combine them in
ways that correspond to the way compounded regular expressions are formed from small regular
expressions. For regular expression R1/R2 we construct the composite NFA.

10 | P a g e
11 | P a g e
6. To find string is keyword, identifier and constant or not.

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
void main()
{
char
exp[50]="\0",con[50]="\0",kwd[50]="\0",id[50]="\0",sym[50]="\0",opr[50]="\0";
char key[6][10]={"if","for","do","while","int","float"};
char ch;
char ptr[10][10]={"\0"};
int i=0,j=0,k=-1,n=-1,p=-1,s=-1;
puts("Enter the expression for lexical analysis");
gets(exp);
puts("\n\n\nThe tokens are");
do
{
ch=exp[i];
if(isalpha(ch))
{
k=-1;
ptr[++n][++k]=ch;
i++;
ch=exp[i];
if(isalpha(ch)||isdigit(ch))
{

12 | P a g e

[Type here]
while(isalpha(ch)||isdigit(ch))

{
ptr[n][++k]=ch;
i++;
ch=exp[i];
}
while(j<6)
{
if(strcmp(key[j],ptr[n])==0)
{
ptr[n][++k]=' ';
strcat(kwd,ptr[n]);
break;
}
if(j==5)
{
ptr[n][++k]=' ';
strcat(id,ptr[n]);
}
j++;
}
}
else
{
ptr[n][++k]=' ';
strcat(id,ptr[n]);
}
i--;

13 | P a g e

[Type here]
ch=exp[i];
j=0;
}
else if(isdigit(ch))
{
k=-1;
ptr[++n][++k]=ch;
i++;
ch=exp[i];
if(isdigit(ch))
{
while(isdigit(ch))
{
ptr[n][++k]=ch;
i++;
ch=exp[i];
}
}
i--;
ch=exp[i];
ptr[n][++k]=' ';
strcat(con,ptr[n]);
}
else if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='%'||ch=='>'||ch=='<'||ch=='='||ch=='!')

{
opr[++p]=ch;
i++;
ch=exp[i];

14 | P a g e

[Type here]
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='%'||ch=='>'||ch=='<'||ch=='='||ch=='!')
{
opr[++p]=ch;
}
else
{
i--;
ch=exp[i];
opr[++p]=' ';
}
}
else
{
sym[++s]=ch;
sym[++s]=' ';
}
i++;
}while(exp[i]!='\0');
puts("\nKeyword:");
puts(kwd);
puts("\nIdentifier:");
puts(id);
puts("\nConstant:");
puts(con);
puts("\nOperator:");
puts(opr);
puts("\nSymbol:");
puts(sym);

15 | P a g e

[Type here]
}

Output:

16 | P a g e

[Type here]
7. To check the balanced parenthesis of an expression.

#include<stdio.h>
#include<stdlib.h>
#define bool int
struct sNode
{
char data;
struct sNode *next;
};

void push(struct sNode** top_ref, int new_data);


int pop(struct sNode** top_ref);
bool isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return 1;
else if (character1 == '{' && character2 == '}')
return 1;
else if (character1 == '[' && character2 == ']')
return 1;
else
return 0;
}
bool areParenthesisBalanced(char exp[])
{
int i = 0;
struct sNode *stack = NULL;
while (exp[i])

17 | P a g e

[Type here]
{
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
push(&stack, exp[i]);
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
if (stack == NULL)
return 0;
else if ( !isMatchingPair(pop(&stack), exp[i]) )
return 0;
}
i++;
}
if (stack == NULL)
return 1;
else
return 0;
}
int main()
{
char exp[100];
printf("Enter parenthesis check data:");
scanf("%d",&exp);
if (areParenthesisBalanced(exp))
printf("Balanced \n");
else
printf("Not Balanced \n");
return 0;
}

18 | P a g e

[Type here]
void push(struct sNode** top_ref, int new_data)
{
struct sNode* new_node =(struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow n");
getchar();
exit(0);
}
new_node->data = new_data;
new_node->next = (*top_ref);
(*top_ref) = new_node;
}
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
if (*top_ref == NULL)
{
printf("Stack overflow n");
getchar();
exit(0);
}
else
{
top = *top_ref;
res = top->data;
*top_ref = top->next;

19 | P a g e

[Type here]
free(top);
return res;
}
}

Output:

20 | P a g e

[Type here]
8. Write a program for token separation with expression.

#include<stdio.h>
#include<string.h>
#include<ctype.h>
void main()
{
char
exp[50]="\0",con[50]="\0",kwd[50]="\0",id[50]="\0",sym[50]="\0",opr[50]="\0";
char key[6][10]={"if","for","do","while","int","float"};
char ch;
char ptr[10][10]={"\0"};
int i=0,j=0,k=-1,n=-1,p=-1,s=-1;
puts("Enter the expression for lexical analysis");
gets(exp);
puts("\n\n\nThe tokens are");
do
{
ch=exp[i];
if(isalpha(ch))
{
k=-1;
ptr[++n][++k]=ch;
i++;
ch=exp[i];
if(isalpha(ch)||isdigit(ch))
{
while(isalpha(ch)||isdigit(ch))

21 | P a g e

[Type here]
{
ptr[n][++k]=ch;
i++;
ch=exp[i];
}
while(j<6)
{
if(strcmp(key[j],ptr[n])==0)

{
ptr[n][++k]=' ';
strcat(kwd,ptr[n]);
break;
}
if(j==5)
{
ptr[n][++k]=' ';
strcat(id,ptr[n]);
}
j++;
}
}
else
{
ptr[n][++k]=' ';
strcat(id,ptr[n]);
}
i--;
ch=exp[i];

22 | P a g e

[Type here]
j=0;
}
else if(isdigit(ch))
{
k=-1;
ptr[++n][++k]=ch;
i++;
ch=exp[i];
if(isdigit(ch))
{
while(isdigit(ch))
{
ptr[n][++k]=ch;
i++;
ch=exp[i];
}
}
i--;
ch=exp[i];
ptr[n][++k]=' ';
strcat(con,ptr[n]);
}
else if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='%'||ch=='>'||ch=='<'||ch=='='||ch=='!')

{
opr[++p]=ch;
i++;
ch=exp[i];
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='%'||ch=='>'||ch=='<'||ch=='='||ch=='!')

23 | P a g e

[Type here]
{
opr[++p]=ch;
}
else
{
i--;
ch=exp[i];
opr[++p]=' ';
}
}
else
{
sym[++s]=ch;
sym[++s]=' ';
}
i++;
}while(exp[i]!='\0');

puts("\nKeyword:");
puts(kwd);
puts("\nIdentifier:");
puts(id);
puts("\nConstant:");
puts(con);
puts("\nOperator:");
puts(opr);
puts("\nSymbol:");
puts(sym);
}

24 | P a g e

[Type here]
OUTPUT

25 | P a g e

[Type here]
9. WAP to find operator precedence relations in top down parser.

#include<stdio.h>
#include<string.h>
char *input;
int i=0;
char lasthandle[6],stack[50],handles[][5]={")E(","E*E","E+E","i","E^E"}; //(E)
becomes )E( when pushed to stack int top=0,l;
char prec[9][9]={
/*stack + - * / ^ i ( ) $ */
/* + */ '>', '>','<','<','<','<','<','>','>',
/* - */ '>', '>','<','<','<','<','<','>','>',
/* * */ '>', '>','>','>','<','<','<','>','>',
/* / */ '>', '>','>','>','<','<','<','>','>',
/* ^ */ '>', '>','>','>','<','<','<','>','>',
/* i */ '>', '>','>','>','>','e','e','>','>',
/* ( */ '<', '<','<','<','<','<','<','>','e',
/* ) */ '>', '>','>','>','>','e','e','>','>',
/* $ */ '<', '<','<','<','<','<','<','<','>',

};
int getindex(char c)
{
switch(c)
{
case '+':return 0;
case '-':return 1;
case '*':return 2;

26 | P a g e

[Type here]
case '/':return 3;
case '^':return 4;
case 'i':return 5;
case '(':return 6;
case ')':return 7;
case '$':return 8;
}
}
int shift()
{
stack[++top]=*(input+i++);
stack[top+1]='\0';
}
int reduce()
{
int i,len,found,t;
for(i=0;i<5;i++)//selecting handles
{
len=strlen(handles[i]);
if(stack[top]==handles[i][0]&&top+1>=len)

{
found=1;
for(t=0;t<len;t++)
{
if(stack[top-t]!=handles[i][t])
{
found=0;
break;

27 | P a g e
}}
if(found==1)
{
stack[top-t+1]='E';
top=top-t+1;
strcpy(lasthandle,handles[i]);
stack[top+1]='\0';
return 1;//successful reduction
}}
}
return 0;
}
void dispstack()
{
int j;
for(j=0;j<=top;j++)
printf("%c",stack[j]);
}
void dispinput()
{
int j;
for(j=i;j<l;j++)
printf("%c",*(input+j));
}

void main()

28 | P a g e

[Type here]
{
int j;
input=(char*)malloc(50*sizeof(char));
printf("\nEnter the string\n");
scanf("%s",input);
input=strcat(input,"$");
l=strlen(input);
strcpy(stack,"$");
printf("\nSTACK\tINPUT\tACTION");
while(i<=l)
{
shift();
printf("\n");
dispstack();
printf("\t");
dispinput();
printf("\tShift");
if(prec[getindex(stack[top])][getindex(input[i])]=='>')

{
while(reduce())
{
printf("\n");
dispstack();
printf("\t");
dispinput();
printf("\tReduced: E->%s",lasthandle);
}
}

29 | P a g e

[Type here]
}

if(strcmp(stack,"$E$")==0)

printf("\nAccepted;");
else
printf("\nNot Accepted;");
}

Output:

30 | P a g e

[Type here]
10. WAP to calculate leading for all non terminals.

#include<conio.h>
#include<stdio.h>

char arr[18][3] ={{'E', '+', 'F'},{'E', '*', 'F'},{'E', '(', 'F'}, {'E', ')', 'F'},{'E', 'i', 'F'},{'E', '$', 'F'},
{'F', '+', 'F'},{'F', '*', 'F'},{'F', '(', 'F'},{'F', ')', 'F'},{'F', 'i', 'F'},{'F', '$', 'F'}, {'T', '+', 'F'}, {'T', '*',
'F'}, {'T', '(', 'F'},{'T', ')', 'F'},{'T', 'i', 'F'},{'T', '$', 'F'}}; char prod[6] = "EETTFF";

char res[6][3] ={ {'E', '+', 'T'}, {'T', '\0'}, {'T', '*', 'F'}, {'F', '\0'}, {'(', 'E', ')'}, {'i', '\0'}};
char stack [5][2];
int top = -1;
void install(char pro, char re) {
int i;
for (i = 0; i < 18; ++i) {
if (arr[i][0] == pro && arr[i][1] == re) {
arr[i][2] = 'T';
break;
}}
++top;
stack[top][0] = pro;
stack[top][1] = re;
}
void main() {
int i = 0, j;
char pro, re, pri = ' ';

for (i = 0; i < 6; ++i) {


for (j = 0; j < 3 && res[i][j] != '\0'; ++j) {

31 | P a g e
if (res[i][j] == '+' || res[i][j] == '*' || res[i][j] == '(' || res[i][j] == ')' || res[i][j] == 'i' || res[i][j] == '$') {
install(prod[i], res[i][j]);
break;
}}}
while (top >= 0) {
pro = stack[top][0];
re = stack[top][1];
--top;
for (i = 0; i < 6; ++i) {
if (res[i][0] == pro && res[i][0] != prod[i]) {
install(prod[i], re);
}}}
for (i = 0; i < 18; ++i) {
printf("\n\t");
for (j = 0; j < 3; ++j)
printf("%c\t", arr[i][j]);
}
printf("\n\n");
for (i = 0; i < 18; ++i) {
if (pri != arr[i][0]) {
pri = arr[i][0];
printf("\n\t%c -> ", pri);
}
if (arr[i][2] == 'T')
printf("%c ", arr[i][1]);}
}

32 | P a g e

[Type here]
Output:

33 | P a g e

[Type here]
11. To calculate trailing for all non terminals.

#include<conio.h>
#include<stdio.h>
char arr[18][3] ={{'E', '+', 'F'}, {'E', '*', 'F'}, {'E', '(', 'F'}, {'E', ')', 'F'}, {'E', 'i', 'F'},
{'E', '$', 'F'}, {'F', '+', 'F'}, {'F', '*', 'F'}, {'F', '(', 'F'}, {'F', ')', 'F'}, {'F', 'i', 'F'},
{'F', '$', 'F'}, {'T', '+', 'F'}, {'T', '*', 'F'}, {'T', '(', 'F'}, {'T', ')', 'F'}, {'T', 'i', 'F'},
{'T', '$', 'F'},

};
char prod[6] = "EETTFF";
char res[6][3] ={ {'E', '+', 'T'}, {'T', '\0', '\0'}, {'T', '*', 'F'}, {'F', '\0', '\0'}, {'(', 'E', ')'}, {'i', '\0', '\0'},};
char stack [5][2];
int top = -1;
void install(char pro, char re) {
int i;
for (i = 0; i < 18; ++i) {
if (arr[i][0] == pro && arr[i][1] == re) {
++top;
arr[i][2] = 'T';
break;
}
}
stack[top][0] = pro;
stack[top][1] = re;
}
void main() {
int i = 0, j;

34 | P a g e

[Type here]
char pro, re, pri = ' ';
for (i = 0; i < 6; ++i) {
for (j = 2; j >= 0; --j) {

if (res[i][j] == '+' || res[i][j] == '*' || res[i][j] == '(' || res[i][j] == ')' || res[i][j] == 'i' || res[i][j] == '$') {
install(prod[i], res[i][j]);
break;
} else if (res[i][j] == 'E' || res[i][j] == 'F' || res[i][j] == 'T') {
if (res[i][j - 1] == '+' || res[i][j - 1] == '*' || res[i][j - 1] == '(' || res[i][j - 1] ==
')' || res[i][j - 1] == 'i' || res[i][j - 1] == '$') { install(prod[i], res[i][j - 1]);
break;
}}}}
while (top >= 0) {
pro = stack[top][0];
re = stack[top][1];
--top;
for (i = 0; i < 6; ++i) {
for (j = 2; j >= 0; --j) {
if (res[i][0] == pro && res[i][0] != prod[i]) {
install(prod[i], re);
break;
} else if (res[i][0] != '\0') break;
}}}

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


{ printf("\n\t");
for (j = 0; j < 3; ++j)
printf("%c\t", arr[i][j]);
35 | P a g e
}
printf("\n\n");
for (i = 0; i < 18; ++i) {
if (pri != arr[i][0]) {
pri = arr[i][0];
printf("\n\t%c -> ", pri);
}
if (arr[i][2] == 'T')
printf("%c ", arr[i][1]);}
getch();}

Output:

36 | P a g e
12. Write a program to compute FIRST function.

#include<stdio.h>
#include<ctype.h>
void FIRST(char[],char );
void addToResultSet(char[],char);
void RemFromResultSet(char[],char);
int numOfProductions;
char productionSet[10][10];
main()
{
int i;
char choice;
char c;
char result[20];
printf("How many number of productions ? :");
scanf(" %d",&numOfProductions);
for(i=0;i<numOfProductions;i++)
{
printf("Enter productions Number %d : ",i+1);
scanf(" %s",productionSet[i]);
}
do
{
printf("\n Find the FIRST of :");
fflush(stdin);
scanf("%c",&c);
FIRST(result,c);

37 | P a g e

[Type here]
printf("\n FIRST(%c)= { ",c);
for(i=0;result[i]!='\0';i++)
printf(" %c ",result[i]);
printf("}\n");
printf("press 'y' to continue : ");
scanf(" %c",&choice);
}while(choice=='y'||choice =='Y');
}
void FIRST(char* Result,char c)
{
int i,j,k;
char subResult[20];
int foundEpsilon;
subResult[0]='\0';
Result[0]='\0';
if(!(isupper(c)))
{
addToResultSet(Result,c);
return ;
}
for(i=0;i<numOfProductions;i++)
{
if(productionSet[i][0]==c)
{
if(productionSet[i][2]=='#') addToResultSet(Result,'#');

else
{
j=2;

38 | P a g e

[Type here]
while(productionSet[i][j]!='\0')
{
foundEpsilon=0;
FIRST(subResult,productionSet[i][j]);
for(k=0;subResult[k]!='\0';k++)
addToResultSet(Result,subResult[k]);
for(k=0;subResult[k]!='\0';k++)
if(subResult[k]=='#')
{
foundEpsilon=1;
break;
}
if(!foundEpsilon)
break;
j++;
}
if(!foundEpsilon)
RemFromResultSet(Result,'#');
}}}
}
void addToResultSet(char Result[],char val)
{
int k;
for(k=0 ;Result[k]!='\0';k++)
if(Result[k]==val)
return;
Result[k]=val;
Result[k+1]='\0';

39 | P a g e

[Type here]
}
void RemFromResultSet(char Result[],char val)

{
int i,k;
for(k=0 ;Result[k]!='\0';k++)
if(Result[k]==val)
{
for(i=k;Result[i]!='\0';i++)
Result[i]=Result[i+1];
break;
}
}

Output:

40 | P a g e

[Type here]
13. Write a program to compute FOLLOW function.

#include<stdio.h>
#include<string.h>
int n,m=0,p,i=0,j=0;
char a[10][10],f[10];
void follow(char c);
void first(char c);
int 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)?");

41 | P a g e

[Type here]
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]);
}}}

42 | P a g e

[Type here]
Output:

43 | P a g e

[Type here]
14. Write an algorithm and program on Recursive Descent parser.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
char in_sym[15],in_ptr=0;
void edash();
void f();
void t();
void tdash();
void advance();
void e()
{printf("\n\t\t E->TE'");
t();
edash();}
void edash()
{
if(in_sym[in_ptr]=='+')
{
printf("\n\t\t E'->+TE'");
advance();
t();
edash();
}
else
printf("\n\t\t E'->e");
}

44 | P a g e

[Type here]
void t()
{
printf("\n\t\t T->FT'");
f();
tdash();
}
void tdash()
{
if(in_sym[in_ptr]=='*')
{
printf("\n\t\t T'->*FT'");
advance();
f();
tdash();
}
else
printf("\n\t\t T'->e");
}
void f()
{
if((in_sym[in_ptr]=='i')||(in_sym[in_ptr]=='I'))

{
printf("\n\t\t F->id");
advance();}
else
{
if(in_sym[in_ptr]=='(')
{

45 | P a g e

[Type here]
printf("\n\t\t F->(E)");
advance();
e();
if(in_sym[in_ptr]==')')
{
advance();
}}
else
{
printf("\n\t\t Syntax Error");
getch();
exit(1);
}}}
void advance()
{
in_ptr++;
}
void main()
{
int i;
printf("\n\t\t Gr.Without Left Recurssion");
printf("\n\t\t E->TE'");
printf("\n\t\t E'->+TE'|e");
printf("\n\t\t T->FT'");
printf("\n\t\t T'->*FT'|e");
printf("\n\t\t F->(E)|id");
printf("\n Enter the Input String (use i for id:)");

gets(in_sym);

46 | P a g e

[Type here]
printf("\n Seq of production rules");
e();
for(i=0;i<strlen(in_sym);i++)
{
if((in_sym[i]!='+')&&(in_sym[i]!='*')&&
(in_sym[i]!='(')&&(in_sym[i]!=')')&&
(in_sym[i]!='i')&&(in_sym[i]!='I'))
{
printf("\n syntax Error");
break;
}}
getch();
}

Output:

47 | P a g e
15. C Programs for generation of three address code.

#include<stdio.h>
#include<string.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()
{
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);

48 | P a g e

[Type here]
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;}
else
{
plus();
break;
}}
else if(exp[i]=='/'||exp[i]=='*')
{
div();
break;

49 | P a g e
}}
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)||(str
cmp(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()
50 | P a g e

[Type here]
{
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]);

Output:

51 | P a g e

[Type here]
16. Implementation of operator precedence parser

#include<stdio.h>
#include<ctype.h>
#include<string.h>
void main()
{
char stack[50]={"$"},texpr[50],expr[50],optbl[50]={"$"};
char op[6][6][1]={/*+-
id$*//*+*/'>','>','<','<','<','>',/*_*/'<','>','<','<','<','>',/***/'>','>','>','>','<','>',/*/*/'>','>' ,'>','<','<','>',/*i d*/'>','>','>','>','>','>',/*$*/'<','<','<','<','<','\0'}; int

count=0,index=0,loop=0,idtbl[50],i,j,k;

printf("\n Constrains:");
printf("\n Operator should be{+,-,*,/}\n");
printf("\n operand should be of single digit number");
printf("\n Enter arithmetic Expression:");
strcat(gets(texpr),"$");
strcat(stack,texpr);
for(i=1,j=0;i<strlen(stack);i+=2,j++)
{
idtbl[j]=stack[i];
if(idtbl[j]>57)
{
printf("\n Invalid Expression:");
exit(0);
}
idtbl[j]=idtbl[j]%48;
optbl[j+1]=stack[i+1];

52 | P a g e

[Type here]
}
while(optbl[1]!='$'&&strlen(texpr)>2)

{
while(count<strlen(stack))
{
switch(stack[count]){
case'+':
i=0;
break;
case'-':
i=1;
break;
case'*':
i=2;
break;
case'/':
i=3;
break;
case'$':
i=5;
break;
default:
i=4;
break;
}
switch(stack[count+1])
{
case'+':

53 | P a g e

[Type here]
j=0;
break;
case'-':
j=1;
break;
case'*':
j=2;
break;
case'/':
j=3;
break;
case'$':
j=5;
break;
default:
j=4;
break;
}
expr[index]=stack[count];
index+=1;
expr[index]=op[i][j][0];
count+=1;
index+=1;
if(i==4&&j==4)
{
printf("Invalid Expression:");

exit(0);
}}

54 | P a g e

[Type here]
expr[index-1]='\0';
printf("\n %s",expr);
for(i=0;i<strlen(expr)&&loop>0;i++)

{if(expr[i]=='<'&&expr[i+2]=='>'){

for(j=0;j<strlen(optbl)-1;j++)
{
if(optbl[j+1]==expr[i+1])
{switch(optbl[j+1])
{case'+':
idtbl[j]=idtbl[j]+idtbl[j+1];
break;
case'-':
idtbl[j]=idtbl[j]-idtbl[j+1];
break;
case'*':
idtbl[j]=idtbl[j]*idtbl[j];
break;
case'/':
idtbl[j]=idtbl[j]/idtbl[j];
break;}
for(k=j+1;k<strlen(optbl);k++)
{optbl[k]=optbl[k+1];
idtbl[k]=idtbl[k+1];}
optbl[k]='\0';
break;
}}}}
strcpy(stack,optbl);
index=0;count=0;loop=1;

55 | P a g e

[Type here]
}
if(strlen(texpr)>2)
printf("\n value is %d",idtbl[0]);

else
printf("\n Invalid");
}

Output:

56 | P a g e

[Type here]
17. Write a program for recursive descent parser

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
char in_sym[15],in_ptr=0;
void edash();
void f();
void t();
void tdash();
void advance();
void e()
{
printf("\n\t\t E->TE'");
t();
edash();
}
void edash()
{
if(in_sym[in_ptr]=='+')
{
printf("\n\t\t E'->+TE'");
advance();
t();
edash();
}
else
printf("\n\t\t E'->e");

57 | P a g e

[Type here]
}
void t()
{
printf("\n\t\t T->FT'");
f();
tdash();
}
void tdash()
{
if(in_sym[in_ptr]=='*')
{
printf("\n\t\t T'->*FT'");
advance();
f();
tdash();
}
else
printf("\n\t\t T'->e");
}
void f()
{
if((in_sym[in_ptr]=='i')||(in_sym[in_ptr]=='I'))

{
printf("\n\t\t F->id");
advance();
}
else
{

58 | P a g e
if(in_sym[in_ptr]=='(')
{
printf("\n\t\t F->(E)");
advance();
e();
if(in_sym[in_ptr]==')')
{
advance();
}}
else
{
printf("\n\t\t Syntax Error");
exit(1);
}}}
void advance()
{
in_ptr++;
}
void main()
{
int i;
printf("\n\t\t Gr.Without Left Recurssion");
printf("\n\t\t E->TE'");
printf("\n\t\t E'->+TE'|e");
printf("\n\t\t T->FT'");
printf("\n\t\t T'->*FT'|e");
printf("\n\t\t F->(E)|id");
printf("\n Enter the Input String (use i for id:)");

59 | P a g e

[Type here]
gets(in_sym);
printf("\n Seq of production rules");
e();
for(i=0;i<strlen(in_sym);i++)
{
if((in_sym[i]!='+')&&(in_sym[i]!='*')&&
(in_sym[i]!='(')&&(in_sym[i]!=')')&&
(in_sym[i]!='i')&&(in_sym[i]!='I'))
{
printf("\n syntax Error");
break;
}
}
}

OUTPUT:

60 | P a g e

[Type here]
18. To write a C program to construct of DAG (Directed Acyclic Graph).

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MIN_PER_RANK 1
#define MAX_PER_RANK 5
#define MIN_RANKS 3
#define MAX_RANKS 5
#define PERCENT 30
void main()
{
int i,j,k,nodes=0;
srand(time(NULL));

int ranks=MIN_RANKS+(rand()%(MAX_RANKS-
MIN_RANKS+1)); printf("DIRECTED ACYCLIC GRAPH\n");
for(i=1;i<ranks;i++) {
int new_nodes=MIN_PER_RANK+(rand()%(MAX_PER_RANK-MIN_PER_RANK+1));

for(j=0;j<nodes;j++)
for(k=0;k<new_nodes;k++)
if((rand()%100)<PERCENT)
printf("%d->%d;\n",j,k+nodes);
nodes+=new_nodes;
}
}

61 | P a g e

[Type here]
Output:

62 | P a g e

[Type here]
19. To write a C program to implement simple code optimization technique.

#include<stdio.h>
#include<string.h>
struct op
{
char l;
char r[20];
}
op[10],pr[10];
void main()
{
int a,i,k,j,n,z=0,m,q;
char *p,*l;
char temp,t;
char *tem;
printf("Enter the Number of Values:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("left: ");
scanf(" %c",&op[i].l);
printf("right: ");
scanf(" %s",&op[i].r);
}
printf("Intermediate Code\n") ;
for(i=0;i<n;i++)
{

63 | P a g e

[Type here]
printf("%c=",op[i].l);
printf("%s\n",op[i].r);
}
for(i=0;i<n-1;i++)
{
temp=op[i].l;
for(j=0;j<n;j++)
{
p=strchr(op[j].r,temp);
if(p)
{
pr[z].l=op[i].l;
strcpy(pr[z].r,op[i].
r);
z++;
}}}
pr[z].l=op[n-1].l;
strcpy(pr[z].r,op[n-1].r);
z++;
printf("\nAfter Dead Code Elimination\n");

for(k=0;k<z;k++)
{
printf("%c\t=",pr[k].l);
printf("%s\n",pr[k].r);
}
for(m=0;m<z;m++)
{
tem=pr[m].r;

64 | P a g e

[Type here]
for(j=m+1;j<z;j++)
{
p=strstr(tem,pr[j].r);
if(p)
{
t=pr[j].l;
pr[j].l=pr[m].l;
for(i=0;i<z;i++)
{
l=strchr(pr[i].r,t) ;
if(l)
{
a=l-pr[i].r;
printf("pos: %d\n",a);
pr[i].r[a]=pr[m].l;
}}}}}
printf("Eliminate Common Expression\n");
for(i=0;i<z;i++)
{
printf("%c\t=",pr[i].l);
printf("%s\n",pr[i].r);
}
for(i=0;i<z;i++)
{
for(j=i+1;j<z;j++)
{
q=strcmp(pr[i].r,pr[j].r);
if((pr[i].l==pr[j].l)&&!q)

65 | P a g e

[Type here]
{
pr[i].l='\0';
}}}
printf("Optimized Code\n");

for(i=0;i<z;i++)
{
if(pr[i].l!='\0')
{
printf("%c=",pr[i].l);
printf("%s\n",pr[i].r);
}}}

Output:

66 | P a g e

[Type here]

Das könnte Ihnen auch gefallen