Вы находитесь на странице: 1из 69

Experiment No.

1 RECOGNIZER :

Objective:

A recognizer is an application that is used to identify a set of


predefined keywords. A recogniser iterates the source looking for a set of
words. It matches the words against a set of predefined word list. On
finding the match it identifies the word as a keyword or an identifier.

Aim:

To write a C program to recognize keywords and identifiers.

Algorithm:

1. Start the program

2. Include the required header files and start the declaration of main
method.

3. Declare the required variables and keywords

4. Using printf function notify the user to enter a string and accept it.

5. Check whether the length of string is greater than 7, if so then


declare it

as not a keyword (or) an identifier

6. If the string length is less than 7 then compare the keyword and
string, if

it matches then declare as keyword.

7. Compare the string with special characters, numbers and alphabets,


if it
matches then declare it as not a keyword (or) an identifier.

8. If the flag value is 1 then print as identifier else print as not a


keyword or

an identifier.

9. Compile and execute the program to verify the output.

10. Stop the program

PROGRAM :

#include<stdio.h>

#include<conio.h>

#include<string.h>

#include<process.h>

void main()

int i,j,flag;

char kw[10]
[10]={"int","float","double","void","for","return","include","printf","char","l
ong"};

char str[10];

clrscr();

while(1)

printf("\n Enter the string");

scanf("%s",str);

if(strlen(str)>7)

{
printf("\n Not an identifier and a keyword");

getch();

goto end;

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

if(strcmp(kw[i],str)==0)

printf("\n Keyword");

getch();

goto end;

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

if((str[0]>=65&&str[0]<=90)||(str[0]>=97&&str[0]<=122)||(str[0]=='-'))

for(j=1;j<strlen(str);j++)

if((str[j]>=0&&str[j]<=47)||(str[j]>=91&&str[j]<=94)||
(str[j]>=57&&str[j]<=64)||(str[j]==96))

printf("\n Not identifier and keyword");

getch();

goto end;

flag=1;
}}}

if(flag==1)

printf("\n Identifier");

else

printf("\n Not identifier and keyword");

end:

printf("\n\n enter the choice(0/1):");

scanf("%d",&ch);

if(ch==0)

break;

OUTPUT:

Enter the string : Nithin

Identifier

Enter the choice(0/1): 1

Enter the string : int

Keyword

Enter the choice (0/1): 1

Enter the string : abcdefghij

Not an identifier and a keyword

Enter the choice (0/1): 0


FAQ’s:

1. What is a recogniser?

2. What do you mean by keywords and identifiers?

3. What is the application of a recogniser?

Experiment No. 2 EXPRESSION-PATTERN MATCHING

Objective:

A pattern evaluator is used to evaluate the given expression again a


set of predefined pattern based on the lexical grammar. When the
expression is entered, it evaluated the expression against a patter to find
if it is justified or not.

Aim:

To write a C program to check the expression and the pattern is


matching.

Algorithm:

1. Start the program

2. Include the required header files

3. Declare the required char variable re,ptt,a,op with their array size
and

int variable i,count and j, where count and j is initialize to 0.


4. Declare a void function fun1() with an infinite for loop and the if

condition to check the condition a[i][0]!=ptt[j]

5. Now start the main method

6. By using a printf statement notify the user to give an expression


and a

pattern

7. Accept the expression and pattern and check whether the


expression

matches with the pattern.

8. If matches print that the expression and the pattern matches else
print

does not match.

9. Now compile and execute the program for the output

10. stop the program

PROGRAM

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

#include <ctype.h>

#include <string.h>

char re[30],ptt[30],a[20][2],op=' ';

int i,count=0,j=0;

void fun1()

for(;;)

if(a[i][0] != ptt[j])

break;

j++;

main()

clrscr();

printf("Enter the Expression :");

scanf("%s",re);

printf("Enter the Pattern :");

scanf("%s",ptt);

for(i=strlen(re)-1;i>=0;i--)

if(isalpha(re[i]) != 0)

a[count][0]=re[i];

a[count++][1]=op;
op=' ';

else if(re[i] == '+' || re[i] == '*')

op=re[i];

for(i=count-1,j=0;i>=0;i--)

if(a[i][1] == '+')

if (a[i][0] != ptt[j])

printf("\n The pattern | %s | does not match the


expression | %s | \n",ptt,re);

return;

fun1();

else if (a[i][1] == '*')

if (a[i][0] != ptt[j])

continue;

fun1();
}

else if(a[i][1] == ' ')

if (a[i][0] == ptt[j++])

continue;

printf("\n The pattern | %s | does not match the


expression | %s | \n",ptt,re);

return;

if(ptt[j] == '\0')

printf("\n The pattern | %s | match the expression | %s


| \n",ptt,re);

else

printf("\n The pattern | %s | does not match the


expression | %s | \n",ptt,re);

getch(); }

OUTPUT:

Enter the Expression : a*b

Enter the Pattern: ab

The pattern | ab | match the expression | a*b |

Enter the Expression : a+b

Enter the Pattern: ac

The pattern | ac | does not match the expression | a+b |

FAQ’s:
1. What is an expression ?

2. What is a pattern?

3. What is lexical grammar ?

4. How do you evaluate an expression ?

Experiment No.3 LEXICAL ANALYSER

Objective:

Lexical analysers are used to iterate a document and identify the


words in the document against the predefined set of symbols. It matches
the words and categorises them by denoting them with predefined
tokens.
Aim:

To write a C program to analysing the tokens using lexical analyzer.

Algorithm:

1. Start the program

2. Include the required header files and start the declaration of main

Method

3. Declare the variables,keywords,special characters,operators

4. Declare two files and use It for reading and writing

5. Check whether the file opened reached the EOF ,if not then
compare

the function name with temp variable declared

6. Print the function name and the temp variable

7. Similarly compare the temp with all the declared variables and
print it

8. In this way , all the variables in the file is read and assigned to temp

and is compared with declared keyword, special character etc. each

token is analyzed and values are assigned


9. Now compile and execute the program for the output

10. Stop the program

Program:

#include<stdio.h>

#include<conio.h>

#include<string.h>

#include<ctype.h>

void main()

int i,r,flag,n,m;

char fn_name[20][20]={"stdio.h","conio.h","string.h"};

char key[20][20]={"main","int","char","void","include","printf","scanf"};

char sp_char[20][20]={"{","}",",","()","(",")","'",";","#"};

char op[20][20]={"+","-","*","/","=","<",">","++","--","=="};

char temp[20];

FILE *f1,*f2;

f1=fopen("INPUT.TXT","r");

f2=fopen("OUTPUT.TXT","w");

fprintf(f2,"f:function name");

fprintf(f2,"\n k: keyword");

fprintf(f2,"\n op: operator");


fprintf(f2,"\n s:special character");

fprintf(f2,"\n id: identifier");

fprintf(f2,"\n c: constant");

fprintf(f2,"\n u: undefined");

fprintf(f2,"\n\n\n LEXEMES\t\t\t TOKENS");

while(!feof(f1))

fscanf(f1,"%s",temp);

flag=0;

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

r=strcmp(fn_name[i],temp);

if(r==0)

flag=1;

fprintf(f2,"\n%s\t\t:\t f",temp);

break;

if(flag==0)

r=strcmp(key[i],temp);

if(r==0)

flag=1;

fprintf(f2,"\n%s\t\t\t:\t k", temp);

break;

}
}

if(flag==0)

r=strcmp(op[i],temp);

if(r==0)

flag=1;

fprintf(f1,"\n%s\t\t:\t op",temp);

break;

if(flag==0)

if(isalpha(temp[0]!=0))

flag=1;

fprintf(f2,"\n%s\t\t:\t id",temp);

if(flag==0)

n=strlen(temp);

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

m=isdigit(temp[i]);

if(m==0)

fprintf(f2,"\n%s\t\t:\t m", temp);


flag=1;

break;

if(flag==0)

if(isdigit(temp[0]!=0))

fprintf(f2,"\n%s\t\t:\t c",temp);

flag=1;

if(r!=0&&flag==0)

fprintf(f2,"\n%s\t\t:\t u",temp);

fclose(f1);

fclose(f2);

INPUT.TXT

#include<stdio.h>

#include<conio.h>

main()

int a,b,sum;

printf("enter the value of a and b");


scanf("%d%d",&a,&b);

sum=a+b;

printf("the sum is:", sum);

getch();

OUTPUT.TXT

f:function name

k: keyword

op: operator

s:special character

id: identifier

c: constant

u: undefined

m: digit

LEXEMES TOKENS

#include<stdio.h>: m

#include<conio.h>: m

main() : m

{ : m

int : s

a,b,sum; : m

printf("enter: m

the : m

value : m
of : m

a : m

and : m

b"); : m

scanf("%d%d",&a,&b);: m

sum=a+b; : m

printf("the : m

sum : m

is:", : m

sum); : m

getch(); : m

} : s

} : s

FAQ’s:

1. What is a lexical analyser?

2. What is the application of lexical analyser?

3. What do you mean by lexemes?

4. In which phase of compilation do lexical analysis comes in use ?

Experiment No.4 SYMBOL TABLE

Objective:

A Symbol table is a table which contains a list of all the keywords


and identifier and their values and attributes. An iterator is used to scan
the document, it identifies the keywords and the data types associated
with it. It adds them to the symbol table to be used later by the
application for reference.
Aim:

To write a C program to make a symbol table from the given code.

Algorithm:

1. Start the program

2. Include the required header files and start the declaration of main

method.

3. Declare the char variables str,temp,cop with their array size and the
int

4. variables i,j,count where count is initialized to 0.

5. Create to file pointers *fp1 and *fp2 for reading and writing .

6. Open the file input.txt and read each string.

7. If the string is in int , float, char,double then print the string to the

output.txt.

8. Now copy the contents to the symbol table

9. Execute the program and check for the result

10. Stop the program.


PROGRAM :

#include<stdio.h>

#include<conio.h>

void main()

char str[100],temp[100],cop[100];

int i,j,count=0;

FILE *fp1,*fp2;

clrscr();

fp1=fopen("INPUT.TXT","r");

fp2=fopen("OUTPUT.TXT","w");

while(fscanf(fp1,"%s",str)!=EOF)

if(strcmp(str,"int")==0||strcmp(str,"float")==0||strcmp(str,"double")==0||
strcmp(str,"char")==0)

fprintf(fp2,"%s\t",str);

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

for(j=0,count=0;j<strlen(temp);j++,count++)

if((cop[count]=temp[j])=='=')

cop[count]='\0';

fprintf(fp2,"%s\t",cop);

count=-1;
}

else if((cop[count]=temp[j])==',')

cop[count]='\0';

fprintf(fp2,"%s\n%s\t",cop,str);

count=-1;

else if(temp[j]==';')

cop[count]='\0';

fprintf(fp2,"%s\n",cop);

INPUT.TXT

void main()

int a,c,e;

char t,k;

float f,y,u,o;

double r;

OUTPUT.TXT

int a
int c

int e

char t

char k

float f

float y

float u

float o

double r

FAQ’s:

1. What is a symbol table?

2. What are the advantages of symbol table?

3. How do we add symbols to symbol table?

4. In which phase of compilation is a symbol table used?


Experiment No.5 REGULAR EXPRESSION

Objective:

A regular expression evaluates an expression based on a fixed


pattern defined by the lexical grammar. Here we have an expression
which is evaluated against a predefined pattern for its validity.

Aim:

To write a C program to determine whether the given expression is


a regular expression or not.

Algorithm:

1. Start the program

2. Include the required header files and start the declaration of main

method.

3. Declare the int variables I,j,k,a,b,c,d,e , char variable str with an


array

size of 20 and char pointer variable *p,*q,*r,*s,*t,*u,*r

4. By using a printf statement notify the user to input an expression


and

a string and accept it.


5. Determine the length of expression and string and assign it to a and
b

6. Assign the value of i,j and e to 0 and Check whether the expression

and the string is equal, and if so assign the value of e to 1

7. Check whether the expression is equal to special character if


matches

assign e=1

8. If the string can be obtained from the expression then declare valid

else declare invalid

9. Compile an execute the program for the output

10 . Stop the program.

PROGRAM:

#include<stdio.h>

#include<conio.h>

#include<ctype.h>

#include<string.h>

void main()
{

int i,j,k,a,b,c,d,e;

char exp[20],str[20];

char *p,*q,*r,*s,*t,*u,*v;

clrscr();

printf("Enter an Expression : ");

scanf("%s",exp);

printf("Enter the String : ");

scanf("%s",&str);

a=strlen(exp);

c=strlen(str);

printf("Length of expression is \t%d\n",a);

printf("Length of string is: \t %d\n",c);

i=0;

j=0;

e=0;

while(c>0)

if(exp[i]==str[j])

if(j==(b-1))

e=1;

else

e=0;

i++;

j++;

c--;
}

else if(exp[i]=='*')

if(exp[i-1]==str[j])

for(k=0;k<strlen(str);k++)

j++;

c--;

e=1;

else

break;

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

p=strtok(exp,"(");

q=strtok(NULL," ");

r=strtok(q,",");

s=strtok(NULL," ");

for(i=0;i<strlen(r);i++)

if(r[i]==str[j])

d=i;

j++;
e=1;

else

if(d==1)

break;

else

continue;

c--;

else

e=0;

break;

if(e==1)

printf("VALID EXPRESSION..!!");

else

printf("INVALID EXPRESSION..!!!");

getch();

return 0;

OUTPUT:
Enter an Expression : a+b/c

Enter the String : aaac

Length of expression is : 5

Length of string is : 4

VALID EXPRESSION..!!!

FAQ’s:

1. What is a regular expression?

2. How do we evaluate a regular expression?

3. What is a lexical grammar?

4. What is pattern?

5. What is expression?

6. Define: i) String ii) Production

Experiment No.6 OPERATOR PRECEDENCE

Objective:

Every operator has a predefined precedence associated with it. An


expression is evaluated on the basis of this precedence. Here we have the
grammar and the expression, which is then evaluated to based on
precedence

Aim:

To write a C program to implement the concept of operator

precedence.

Algorithm:

1. Start the program


2. Include the required header files and start the declaration of main

method.

3. Declare the required variable and define the function for pushing
and

poping the characters.

4. The operators are displayed in column and row wise and stored it in
a

queue.

5. Using a switch case find the values of the operators

6. Display the precedence of the operator and generate the code for

precedence of operator for the given expression.

7. Compile and execute the program for the output

8. Stop the program

PROGRAM:

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

#include<string.h>

#include<ctype.h>

#include<stdlib.h>

char str[20],stk[20],pstk[20];

int tos=-1,flag=0,ptr=0,rm=-1,i,j;

char q[9][9]={

{'>','>','<','<','<','<','>','<','>'},

{'>','>','<','<','<','<','>','<','>'},

{'>','>','>','>','<','<','>','<','>'},

{'>','>','>','>','<','<','>','<','>'},

{'>','>','<','<','<','<','>','<','>'},

{'<','<','<','<','<','<','=','<','E'},

{'>','>','>','>','>','E','>','E','>'},

{'>','>','>','>','>','E','>','E','>'},

{'<','<','<','<','<','<','E','<','A'},

};

char c[9]={'+','-','*','/','^','a','(',')','$'};

void pushin(char a)

tos++;

stk[tos]=a;

char popout()

char a;

a=stk[tos];
tos--;

return(a);

int find(char a)

switch(a)

case'+':return 0;

case'-':return 1;

case'*':return 2;

case'/':return 3;

case'^':return 4;

case'(':return 5;

case')':return 6;

case'a':return 7;

case'$':return 8;

return-1;

void display(char a)

printf("\n SHIFT %c",a);

void display1(char a)

if(a!='(')

{
if(isalpha(a))

printf("\n REDUCE E--> %c",a);

else if(a==')')

printf("\n REDUCE E-->(E)");

else

printf("\n REDUCE E-->E %c E",a);

int rel(char a,char b,char d)

if(isalpha (a))

a='a';

if(isalpha(b))

b='a';

if(q[find(a)][find(b)]==d)

return 1;

else

return 0;

void main()

clrscr();

printf("\n\n\t The productions used are:\n\t");

printf("E-->E*E/E+E/E^E/E*E/E-E\n\tE-->E/E \n\tE-->a/b/c/d/e.../z");

printf("\n\t Enter an expression that terminals with $:");

fflush(stdin);

i=-1;
while(str[i]!='$')

i++;

scanf("%c",&str[i]);

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

if((str[j]=='(')||(str[j]==')')||(str[j+1]=='(')||(str[j+1]==')'))

{}

else

if(((isalpha(str[j])==0)&&(isalpha(str[j+1])==0))||((isalpha(str[j])!
=0)&&(isalpha(str[j+1])!=0)))

printf("ERROR");

getch();

exit(0);

if((((isalpha(str[0]))!=0)||(str[0]=='('))&&(((isalpha(str[i-1]))!=0)||(str[i-
1]==')')))

pushin('$');

printf("\n\n\n\t+\t-\t*\t/\t^\ta\t(\t)\t$\n\n");

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

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

for(j=0;j<9;j++)
printf("\t%c",q[i][j]);

printf("\n");

getch();

while(1)

if(str[ptr]=='$' && stk[tos]=='$')

printf("\n\n\t ACCEPT!");

break;

else if(rel(stk[tos],str[ptr],'<')||rel(stk[tos],str[ptr],'=='))

display(str[ptr]);

pushin(str[ptr]);

ptr++;

else if(rel(stk[tos],str[ptr],'>'))

do

rm++;

pstk[rm]=popout();

display1(pstk[rm]);

while(!rel(stk[tos],pstk[rm],'<'));

}
else

printf("\n\n\t NOT ACCEPTED!!!!!!!");

getch();

exit(1);

getch();

else {

printf("ERROR");

getch();}}

OUTPUT:

The productions used are:

E-->E*E/E+E/E^E/E*E/E-E

E-->E/E

E-->a/b/c/d/e.../z

Enter an expression that terminals with $ : (a+b)$

+ - * / ^ a ( ) $

+ > > < < < < > < >

- > > < < < < > < >

* > > > > < < > < >


/ > > > > < < > < >

^ > > < < < < > < >

a < < < < < < = < E

( > > > > > E > E >

) > > > > > E > E >

$ < < < < < < E < A

SHIFT (

SHIFT a

REDUCE E--> a

SHIFT +

SHIFT b

REDUCE E--> b

REDUCE E-->E + E

SHIFT )

REDUCE E-->(E)

ACCEPT !

FAQ’s:

1. What is an operator?

2. What is an operand?

3. Types of operators?

4. What is the significance of operator precedence?

5. Define expression and production.


Experiment No.7 SHIFT REDUCE PARSER

Objective:

A shift-reduce parser tries to reduce the given input string into the
starting symbol.

At each reduction step, a substring of the input matching to the right side
of a production rule is replaced by the non-terminal at the left side of that
production rule.

Aim:

To write a C program to implement the concept of shift reduce


parser

Algorithm:

1. Start the program

2. Include the required header files and start the declaration of main

method.

3. Declare the char variables exp,stack,arr,temp with the array size


and

the int variables I,k,j,l,v,s where k is initialized to 0

4. By using the printf function display the choosen production


5. Enter the string to be parsed and display the column stack,input
and

Action

6. If the string entered is not there in the production , then it cannot


be

shifted and hence it is not accepted

7. Else the input is parsed separately and stored in stack, each time
when

it is shifted reduce to i , then the string is accepted.

8. Compile and execute the program for the output.

9. stop the program

PROGRAM:

#include<stdio.h>

#include<conio.h>

#include<string.h>

char exp[10],stack[10],arr[10],temp[10];

int i,k=0,j,l,r,s;

void push(char exp[])

arr[i]=exp[k];
i++;

void dispinp()

printf("\t\t\t");

for(k=0;k<strlen(exp);k++)

printf("%c",exp[k]);

printf("$");

void dispstk()

printf("\n");

for(k=0;k<strlen(stack);k++)

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

void assign()

stack[++j]=arr[i];

exp[i]=' ';

dispstk();

dispinp();

void main()

clrscr();
printf("\t\t\tSHIFT REDUCE PARSER\n");

printf("\nThe Production is: E->E+E/E*E/E-E/i\n");

printf("\nEnter the string to be parsed:\n");

gets(exp);

printf("\nSTACK\t\t\tINPUT\t\t\tACTION\n");

printf("\n$");

dispinp();

printf("\t\t\tShift");

for(k=0;k<strlen(exp);k++)

push(exp);

l=strlen(exp);

stack[0]='$';

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

switch(arr[i])

case 'i':assign();

printf("\t\t\tReduce by E->i");

stack[j]='E';

dispstk();

dispinp();

if(arr[i+1]!='\0')

printf("\t\t\tShift");

break;

case '+':assign();

printf("\t\t\tShift");

break;
case '*':assign();

printf("\t\t\tShift");

break;

case '-':assign();

printf("\t\t\tShift");

break;

default: printf("\nError:String not accepted");

goto label;

l=strlen(stack);

while(l>2)

r=0;

for(i=l-1;i>=l-3;i--)

temp[r]=stack[i];

r++;

temp[r]=NULL;

if((strcmp(temp,"E+E")==0)||(strcmp(temp,"E*E")==0)||
(strcmp(temp,"E-E")==0))

for(i=l;i>l-3;i--)

stack[i]=' ';

stack[l-3]='E';

printf("\t\t\tReduce by E->");
for(i=0;i<strlen(temp);i++)

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

dispstk();

dispinp();

l=l-2;

else

printf("\nError:String not accepted");

goto label;

printf("\t\t\tAccept");

printf("\n\nString accepted");

label:

getch();

OUTPUT:

The Production is: E->E+E/E*E/E-E/i

Enter the string to be parsed:

i+i*i

STACK INPUT ACTION

$ i+i*i$ Shift
$i +i*i$ Reduce by E->i

$E +i*i$ Shift

$E+ i*i$ Shift

$E+i *i$ Reduce by E->i

$E+E *i$ Shift

$E+E* i$ Shift

$E+E*i $ Reduce by E->i

$E+E*E $ Reduce by E->E*E

$E+E $ Reduce by E->E+E

$E $ Accept

String accepted

FAQ’s:

1. What is a Parsing?

2. What are the types of parsing?

3. What is Shift Reduced Parsing?

4. Advantage of SRP?

5. Contrast SRP with Top Down Parsing ?


Experiment No.8 FINDING CLOSURE

Objective:

The closure of a state is the set of all states attainable from the
current state based on the input. Here, we have the grammar and the
input. This is used to produce the closure.

Aim:

To write a C program to find the closure of the given grammar.

Algorithm:

1. Start the program

2. Include the required header files and start the declaration of main

method.

3. Declare the char variables a,c,ip,op,s,b with the required array size
and

int variables n,m,I,l,flag,j,x,k where flag,j and k is initialize to 0

4. Using a printf function notify the user to input the number of

production and accept it.


5. Read all the production , create a matrix and assign a null
statement to

all the matrix and concatenate with a dot

6. Now get from the user the required production to find closure

7. Compare both the productions , if both are same then print its
closure

reapeatedly, if the production has no terminals.

8. Now compile and execute the program for the output

9. Stop the program.

PROGRAM:

#include <stdio.h>

#include <conio.h>

#include<string.h>

char prod[10][10];

char items[10][10];

char term[5],nonterm[5];

char clos[25][15];

static int nindex= 0, tindex = 0,findex= 0,cindex=0;

int n , ni;

void get_productions();
void get_items();

void scan_prod(char *p);

int isUnique(char *p, char c );

int strUnique(char *p );

void closure();

void traverse( char *p );

void get_productions()

int i;

printf("\nEnter the number of productions:");

scanf("%d",&n);

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

printf("\nEnter production %d:",i+ 1);

scanf("%s",prod[i]);

scan_prod(prod[i] );

void get_items()

int i;

printf("\nEnter the number of items in the set I:");

scanf("%d",&ni);

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

printf("\nEnter production %d:",i+1);

scanf("%s" ,items[i]);
}

void scan_prod( char *p )

int l= strlen(p);

int i;

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

if ( p[i] >= 'A' && p[i] <= 'Z' )

if(isUnique(nonterm,p[i])==-l)

continue;

else

nonterm[nindex++]= p[i];

else if ( p[i] >= 'a' && p[i] <= 'z' )

if ( isUnique(term, p[i] ) ==-l )

continue;

else

term[tindex++] = p[i];

int isUnique(char *p, char c )

int l= strlen(p);
int i;

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

if ( p[i] == c )

return -1;

return l;

int strUnique(char *p )

int l = strlen(p);

int i;

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

if( strcmp( clos[i],p) == 0)

return-1 ;

return 1;

void traverse( char *p )

int i,j,l = strlen(p);

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


{

if( (p[j]=='.')&& (isUnique(nonterm,p[j+1]) == -l))

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

if(prod[i][0] == p[j+1])

if ( strUnique(prod[i] ) != -1 )

strcpy( clos[cindex++],prod[i] );

traverse(prod[i]);

void closure()

int i;

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

strcpy( clos[cindex++], items[i] );

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

traverse( clos[i] );

void display()

{
int i;

printf("\nCLOSURE\n");

printf("\n-------\n");

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

printf("\n%d) %s",i,clos[i]);

void main()

clrscr();

printf("\nCLOSURE OF A GIVEN GRAMMAR\n");

printf("\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n");

get_productions();

get_items();

closure();

display();

getch();

OUTPUT:

CLOSURE OF A GIVEN GRAMMAR

~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter the number of productions:3

Enter production 1:E->E+E

Enter production 2:E->E-E

Enter production 3:E->a

Enter the number of items in the set I:2

Enter production 1:E->.E+E


Enter production 2:E->.a

CLOSURE

------------

0) E->.E+E

1) E->.a

2) E->E+E

3) E->E-E

4) E->a

FAQ’s:

1. What is a Closure?

2. Types of closures?

3. What is *-closure

4. What is positive closure?

5. Contrast * and + Closure?


Experiment No.9 CODE GENERATION

Objective:

Code generators are used to generate the code based on the input.
Here we give the expressions for which the assembly code is generated
using the mnemonics by the program.

Aim:

To write a C program to implement the concept of code generation

Algorithm:

1. Start the program

2. Include the required header files and start the declaration of main

method.

3. Declare a static int variables t,j which is initialized to 0

4. Declare a structure method with name te contains char variable na


and

int variable k

5. Declare a file pointer *F

6. Open input1.txt file using fopen function

7. Create a loop and function to produce the code generation

8. By using printf function Print the output to the console.


9. Now compile and execute the program for the output

10. Stop the program

PROGRAM:

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<conio.h>

static int t=0,j=0;

struct te

char na;

int k;

};

void opr(char a)

switch(a)

case'+':printf("\nAdd ");

break;

case'-':printf("\nSub ");

break;

case'*':printf("\nMul ");
break;

case'/':printf("\nDiv ");

break;

main()

FILE *f;

char str[10],pt[20];

struct te st[20];

int i,rr,f1=0,r;

clrscr();

f=fopen("input1.txt","r");

while(!feof(f))

fscanf(f,"%s",str);

f1=0;

st[j].na=str[0];

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

if(st[i].na==str[2])

r=rr=st[i].k;

f1=1;

break;

if(f1!=1)

r=rr=t++;
st[j++].k=rr;

if(f1!=1)

printf("\nMov %c,R%d",str[2],rr);

opr(str[3]);

printf("%c,R%d",str[4],rr);

else

opr(str[3]);

f1=0;

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

if(st[i].na==str[4])

rr=st[i].k;

f1=1;

break;

if(f1==1)

printf("R%d,R%d",r,rr);

else

printf("%c,R%d",str[4],r);

printf("\nMov R%d,%c",r,str[0]);

getch();

}
INPUT1.TXT:

t=a-b

u=a-c

v=t+u

d=v+u

OUTPUT:

Mov a, R0

Sub b, R0

Mov a, R1

Sub c, R1

Add R0, R1

Add R0, R1

Mov R0, d

FAQ’s:

1. What is a Source Code?

2. What is compilation?

3. What is a mnemonic?

4. What is an expression?

5. In What phase of compilation code generation is used?


Experiment No.10 DIRECT ACYCLIC GRAPH(DAG)

Objective:

A DAG is used to represent the sequence of expression evaluation in


compact manner. It gives the operators as the parent node and operands
as child node on a graph, in the order in which they are to be evaluated.

Aim:

To write a C program to implement the concept of direct acyclic


graph

from three address code.

Algorithm:

1. Start the program

2. Include the required header files and start the declaration of main

method.

3. Declare a structure method te with char variables with na and na1


with

the required array size and int variable y.

4. Declare the char variables str,la,ro,op,opr,la1,na with the required

array size and static int variable y1 which is initialized to 3 and int

variables I initialized to -1 and x1 initialized to 0


5. Declare a file pointer variable *F

6. Enter the three address code generator and print the left right and
root

child to the console.

7. Now compile and execute the program for the output.

8. Stop the program

PROGRAM:

# include<stdio.h>

# include<ctype.h>

# include<stdlib.h>

# include<conio.h>

# include<string.h>

struct te

char na[20];

char na1[20];

int y;

} p[25];

char str[20],*pt,la[20],ro[20],op[20],opr[20],la1[20],na[20];
static int y1=3;

int i=-1,x1=0;

void sep(char l[20],char r[20],char st[20],int tt)

int x,j=0,k=0;

if(pt=='\0')

tt=strlen(st);

for(x=tt+1;x<strlen(st);x++)

r[j++]=st[x];

r[j]='\0';

for(x=0;x<tt;x++)

l[k++]=st[x];

l[k]='\0';

print()

gotoxy(5,p[i].y);

printf("%s",la);

gotoxy(45,p[i].y);

printf("%s",op);

gotoxy(25,p[i].y);

printf("%s",opr);

gotoxy(65+x1,p[i].y);

printf("%s",na);

main()
{

int fl,k;

FILE *f1;

clrscr();

f1=fopen("i.txt","r");

printf("\n Enter the three address code statement");

gotoxy(5,1);

printf("Left child");

gotoxy(45,1);

printf("Right child");

gotoxy(25,1);

printf("Root child");

gotoxy(65,1);

printf("List of attached identifiers");

while(!feof(f1))

x1=fl=0;

fscanf(f1,"%s",str);

pt=strchr(str,'=');

sep(na,ro,str,pt-str);

strcpy(p[++i].na,ro);

strcpy(p[i].na1,na);

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

if(strcmp(p[i].na,p[k].na)==0)

fl=1;

break;
}

if(fl==1)

p[i].y=p[k].y;

x1=5;

else

p[i].y=++y1;

x1=0;

if(strchr(ro,'*'))

strcpy(opr,"*");

pt=strchr(ro,'*');

else if(strchr(ro,'['))

pt=strchr(ro,'[');

strcpy(opr,"[]");

ro[strlen(ro)-1]='\0';

else if(strchr(ro,'+'))

pt=strchr(ro,'+');

strcpy(opr,"+");

}
else

pt='\0';

opr[0]='\0';

sep(la,op,ro,pt-ro);

fl=0;

if(pt=='\0')

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

if(strcmp(p[i].na,p[k].na1)==0)

fl=1;

y1--;

p[i].y=p[k].y;

break;

if(fl==1)

la[0]='\0';

x1=5;

print();

}
}

INPUT.TXT

t1=4*i0

t2=a[t1]

t3=4*i0

t4=b[t3]

t5=t2*t4

t6=pr0+t5

pr=t6

t7=i0+1

i=t7

OUTPUT:

Left Child Root Child Right child List of Attached Identifiers

4 * i0 t1 t3

a [] t1 t2

b [] t3 t4

t2 * t4 t5

pr0 + t5 t6 pr

i0 + 1 t7 i

FAQ’s:

1. What is a graph?

2. What is DAG?

3. What is a cyclic graph?

4. Define parent and children nodes.

5. Methods to parse a graph?


6. Difference b/w a tree and graph

7. What is acyclic graph?

Experiment No.11 TOPDOWN PARSING

Objective:
Top down parsing is a parsing method, which is done by starting
with the root, labelled with starting non-terminal, and repeatedly
performing the following steps:

• A node n, labelled with non-terminal A, select one of the


production for A and construct children at n for the symbols
on the right side of the production

• Find the next node at which a sub tree is to be constructed.

Aim:

To write a C program for parsing a given expression in a topdown


approach.

Algorithm:

1. Start the program

2. Include the required header files and start the declaration of main

method.

3. Declare the required variables and initialize the graphics mode

4. Enter the string to be parsed and print the production

5. Read the string and determine its length

6. Each alphabet in the string is obtained and the line is drawn and the

string is printed

7. Similarly each time the particular string is printed based upon the
code
8. In this way the string is parsed from top to bottom and tree will be

Generated

9. Now compile and execute the program and check the output

10. Stop the program

PROGRAM:

#include<conio.h>

#include<stdlib.h>

#include<graphics.h>

#include<ctype.h>

#include<string.h>

void main()

int gd=DETECT,gm,len,x1=100,y1=200,i,x2,y2;

char str[20],st[10];

initgraph(&gd,&gm," ");

printf("\t\t#include<stdio.h>

\t\t TOP DOWN PARSING \n");

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

printf("productions : \n E->E+E\n E->E-E\n E->E*E\n E->E/E");

printf("\n\n ENTER THE STRINGS TO BE PARSED:");

scanf("%s",str);

printf("\nPARSED tree:");
len=strlen(str);

outtextxy(x1,y1,"E");

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

if(isalpha(str[i]))

if((i+1)==len)

line(x1+5,y1+7,x2+5,y2+57);

sprintf(st,"%c",str[i]);

outtextxy(x1,y1+50,st);

break;

else

sprintf(st,"%c",str[i]);

outtextxy(x1-45,y1+100,st);

continue;

else

x2=x1-40;

y2=y1+40;

line(x1,y1+10,x2,y2+10);

outtextxy(x2,y2+10,"E");

line(x1,y1+10,x1,y2+10);
sprintf(st,"%c",str[i]);

outtextxy(x1,y2+10,st);

x2=x1+40;

line(x1,y1+10,x2,y2+10);

outtextxy(x2,y2+10,"E");

x1+=40;

y1+=50;

}}

getch();

OUTPUT:

Productions:

E->E+E

E->E-E

E->E*E

E->E/E

Enter the string to be parsed: a+b*c

PARSE TREE:

FAQ’s:
1. What is a Parsing?

2. What are the types of parsing?

3.What is Top Down Parsing?

4. Advantage of TDP?

5. Contrast Shift Reduce Parsing with Top Down Parsing ?

6. What is a parse tree?

Вам также может понравиться