Sie sind auf Seite 1von 45

Ex 1.

Lexical Analyzer

AIM: To implement a lexical analyzer for a simple C program.

ALGORITHM:
1. Save the program to be analyzed in a text file,
2. Create a keyword function, which simply checks if the string obtained from the text file is a
keyword or an identifier,
3. Open the file in the main function to be analyzed character by character,
4. If the character is an operator, print so,
5. If the string obtained after the white space or newline character matches the keyword, print it’s a
keyword,
6. If the string is identifier, print so.

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int isKeyword(char buffer[]){
char keywords[32][10] =
{"auto","break","case","char","const","continue","defau
lt",
"do","double","else","enum","extern","float","for","goto
", "if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while"};
int i, flag = 0;
for(i = 0; i < 32; ++i){
if(strcmp(keywords[i], buffer) == 0){
flag = 1;
break;
}
}
return flag;
}
int main(){
char ch, buffer[15], operators[] = "+-*/%=";
FILE *fp;
int i,j=0;
fp = fopen("program.txt","r");
if(fp == NULL){
printf("error while opening the file\n");
exit(0);
}
while((ch = fgetc(fp)) != EOF){
for(i = 0; i < 6; ++i){
if(ch == operators[i])
printf("%c is operator\n", ch);
}
if(isalnum(ch)){
buffer[j++] = ch;
}
else if((ch == ' ' || ch == '\n') && (j != 0)){
buffer[j] = '\0';
j = 0;
if(isKeyword(buffer) == 1)
printf("%s is keyword\n", buffer);
else
printf("%s is indentifier\n", buffer);
}
}
fclose(fp);
return 0;
}

OUTPUT:
void is keyword
main is identifier
int is keyword
a is identifier
b is identifier
c is identifier
= is
operator a
is
identifier
+ is
operator b
is
identifier

RESULT:
The following program was successfully compiled and executed.
Ex 2. Regular Expression to NFA

AIM: To write a C program to convert the given RE to NFA.

ALGORITHM:
1. Accept the regular expression string from the user,
2. Using the Thompson’s Algorithm, implement operator precedence,
3. Handle the parentheses,
4. Handle the kleene stars,
5. Perform concatenation,
6. Followed by alternation.

PROGRAM:

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main(){
char reg[20];
int q[20][3],i,j,len,a,b;
for(a=0;a<20;a++){
for(b=0;b<3;b++){
q[a][b]=0;
}
}
printf("Regular expression: \n");
scanf("%s",reg);
len=strlen(reg);
i=0;
j=1;
while(i<len){
if(reg[i]=='a'& reg[i+1]!='/'&reg [i+1]!='*'){
q[j][0]=j+1;
j++;
}
if(reg[i]=='b'& reg[i+1]!='/'& reg[i+1]!='*'){
q[j][1]=j+1;
j++;
}
if(reg[i]=='e'& reg[i+1]!='/'& reg[i+1]!='*'){
q[j][2]=j+1;
j++;
}
if(reg[i]=='a'&reg[i+1]=='/'&reg[i+2]=='b'){
q[j][2]=((j+1)*10)+(j+3);
j++;
q[j][0]=j+1;
j++;
q[j][2]=j+3;
j++;
q[j][1]=j+1;
j++;
q[j][2]=j+1;
j++;
i=i+2;
}
if(reg[i]=='b'&reg[i+1]=='/'&reg[i+2]=='a'){
q[j][2]=((j+1)*10)+(j+3);
j++;
q[j][1]=j+1;
j++;
q[j][2]=j+3;
j++;
q[j][0]=j+1;
j++;
q[j][2]=j+1;
j++;
i=i+2;
}
if(reg[i]=='a'&reg[i+1]=='*'){
q[j][2]=((j+1)*10)+(j+3);
j++;
q[j][0]=j+1;
j++;
q[j][2]=((j+1)*10)+(j-1);
j++;
}
if(reg[i]=='b'&reg[i+1]=='*'){
q[j][2]=((j+1)*10)+(j+3);
j++;
q[j][1]=j+1;
j++;
q[j][2]=((j+1)*10)+(j-1);
j++;
}
if(reg[i]==')'&reg[i+1]=='*'){
q[0][2]=((j+1)*10)+1;
q[j][2]=((j+1)*10)+1;
j++;
}
i++;
}
printf("Transition function \n");
for(i=0;i<=j;i++){
if(q[i][0]!=0)
printf("\n q[%d,a]-->%d",i,q[i][0]);
if(q[i][1]!=0)
printf("\n q[%d,b]-->%d",i,q[i][1]);
if(q[i][2]!=0){
if(q[i][2]<10)
printf("\n q[%d,e]-->%d",i,q[i][2]);
else
printf("\n q[%d,e]-->%d & %d",i,q[i][2]/10,q[i][2]%10);
}
}
getch();
}

OUTPUT:
Simulation of Data

*****************

Enter Regular expression (a+b)*

0 1 2 3 4

E |0

E EE |1

) |2

E E |3

|4

Start state:0 Final state:4

RESULT:
The following program was successfully compiled and executed.
Ex 3. NFA to DFA

AIM: To write a C program to convert the given NFA to DFA.

ALGORITHM:
1. Accept the NFA from the user,
2. Accept the number of input symbols,
3. Accept the number of NFA states,
4. Accept the number of DFA states,
5. Finally, convert the given NFA to DFA.

PROGRAM:
#include <stdio.h>
#include <string.h>
#define STATES 256
#define SYMBOLS 20
int N_symbols;
int NFA_states;
char *NFAtab[STATES][SYMBOLS];
int DFA_states;
int DFAtab[STATES][SYMBOLS];
void put_dfa_table(
int tab[][SYMBOLS],
int nstates,
int nsymbols) {
int i, j;
puts("STATE TRANSITION TABLE");
printf(" | ");
for (i = 0; i < nsymbols; i++) printf(" %c ", '0'+i);
printf("\n-----+--");
for (i = 0; i < nsymbols; i++) printf("-----");
printf("\n");
for (i = 0; i < nstates; i++) {
printf(" %c | ", 'A'+i);
for (j = 0; j < nsymbols; j++)
printf(" %c ", 'A'+tab[i][j]);
printf("\n");
}
}
void init_NFA_table(){
NFAtab[0][0] = "12";
NFAtab[0][1] = "13";
NFAtab[1][0] = "12";
NFAtab[1][1] = "13";
NFAtab[2][0] = "4";
NFAtab[2][1] = "";
NFAtab[3][0] = "";
NFAtab[3][1] = "4";
NFAtab[4][0] = "4";
NFAtab[4][1] = "4";
NFA_states = 5;
DFA_states = 0;
N_symbols = 2;
}
void string_merge(char *s, char *t){
char temp[STATES], *r=temp, *p=s;
while (*p && *t) {
if (*p == *t) {
*r++ = *p++; t++;
} else if (*p <
*t) { *r++
= *p++;
} else
*r++ = *t++;
}
*r = '\0';
if (*p) strcat(r, p);
else if (*t) strcat(r, t);
strcpy(s, temp);
}
void get_next_state(char *nextstates, char
*cur_states, char *nfa[STATES][SYMBOLS],
int n_nfa, int symbol){ int i;
char temp[STATES];
temp[0] = '\0';
for (i = 0; i < strlen(cur_states); i++)
string_merge(temp, nfa[cur_states[i]-'0'][symbol]);
strcpy(nextstates, temp);
}
int state_index(char *state, char statename[]
[STATES], int *pn){ int i;
if (!*state) return -1;
for (i = 0; i < *pn; i++)
if (!strcmp(state, statename[i])) return i;
strcpy(statename[i], state);
return (*pn)++;
}
int nfa_to_dfa(char *nfa[STATES]
[SYMBOLS], int n_nfa, int n_sym, int dfa[]
[SYMBOLS]){
char statename[STATES][STATES];
int i = 0;
int n = 1;
char nextstate[STATES];
int j;
strcpy(statename[0], "0");
for (i = 0; i < n; i++) {
for (j = 0; j < n_sym; j++) {
get_next_state(nextstate, statename[i], nfa, n_nfa, j);
dfa[i][j] = state_index(nextstate, statename, &n);
}
}
return n;
}
int main(){
init_NFA_table();
DFA_states = nfa_to_dfa(NFAtab, NFA_states,
N_symbols, DFAtab); put_dfa_table(DFAtab,
DFA_states, N_symbols);
}

OUTPUT:
Enter the no of input symbols:2
Enter the input symbols:
a ,b
Enter the transitions:(-1 to stop)
move(0,a);-1
move(0,b);-1
move(0,e);1
move( 0,e);7
move(0,e);-1
move(1,a);-1
move(1,b);-1
move( 1,e);2
move(1,e);4
move(1,e);-1
move(2,a);3
move(2,a);3
move(2,a);-1
move(2,b);-1
move(2,e);-1
move(3,a);-1
move(3,b);-1
move(3,e);6
move(3,e);-1
move(4,a);-1
move(4,b);-1
move(4,e);-1
move(5,a);-1
move(5,b);-1
move(5,e);6
move(5,e);1
move(5,e);-1
move(6,a);-1
move(6,b);-1
move(6,e);-1
move(7,a);-1
move(7,b);-1
move(7,e);-1
DFA transition table
States String
Inputs b
a
------------------------------------------ C
------- C
A 01247 B
B 36 C
C CC

RESULT:
The following program was successfully compiled and executed.
Ex.4 Left Recursion and Left Factoring

Ex 4(a): Left Recursion

AIM: To a write a C program to eliminate left recursion from a grammar.

ALGORITHM:
1. Accept a grammar as input production,
2. For each non-terminal Ai,
3. Repeat until and iteration leaves the grammar unchanged.
4. For each rule, Ai ->αi, αi being a sequence of terminals and non-terminals,
5. If αi begins with a non-terminal Aj and j<1,
6. Let βi be αi without its leading Aj,
7. Remove the rule Ai-> αi,
8. For each rule Ai-> αj, Add the rule Ai-> αiβi,
9. Remove direct left recursion for Ai.

PROGRAM:

#include<stdio.h>
#include<string.h>
int main() {
char
input[100],*l,*r,*temp,tempprod[20],productions[25]
[50]; int i=0,j=0,flag=0;
printf("Enter the productions: ");
scanf("%s",input);
l = strtok(input,"-
>"); r =
strtok(NULL,"-
>"); temp =
strtok(r,"|");
while(temp) {
if(temp[0] ==
l[0]) { flag =
1;
sprintf(productions[i++],"%s'->%s%s'\0",l,temp+1,l);
}
else sprintf(productions[i++],"%s->%s
%s'\0",l,temp,l);
temp = strtok(NULL,"|");
}
sprintf(productions[i++],"%s-
>\356\0",l); if(flag == 0)
printf("The given productions don't have Left
Recursion"); else
for(j=0;j<i;j++)
{ printf("\n
%s",productions[j]);
}
}
OUTPUT:

Enter the left production(s) (NON TERMINALS) : ETF


Enter the number of productions for E : 2
Enter the number of productions for T : 2
Enter the number of productions for F : 2
Enter the right productions for E
E->E+T
E->T
Enter the right productions for T
T->T*F
T->F
Enter the right productions for F
F->(E)
F->i
The resulting productions after eliminating Left Recursion are :
E -> TE'
T -> FT'
E' -> +TE'|ε
T' -> *FT'|ε
F -> (E)
F ->i

RESULT:
The following program was successfully compiled and executed.
Ex 4(b): Left Factoring

AIM: To write a C program to perform LEFT FACTORING on a given grammar.

ALGORITHM:
1. Accept any production from the user,
2. Use another character array to store one part of the grammar and another character to store the
remaining.
3. Later compare the derived character with each other and copy the matching character to another
array,
4. Print the result.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char a[10],a1[10],a2[10],a3[10],a4[10],a5[10];
int i,j=0,k,l;
printf("enter any productions A->");
gets(a);
for(i=0;a[i]!='/';i++,j++)
a1[j]=a[i];
a1[j]='\0';
for(j=++i,i=0;a[j]!='\0';j++,i++)
a2[i]=a[j];
a2[i]='\0';
k=0;
l=0;
for(i=0;i<strlen(a1)||i<strlen(a2);i++)
{
if(a1[i]==a2[i])
{
a3[k]=a1[i];
k++;
}
else
{
a4[l]=a1[i];
a5[l]=a2[i];
l++;
}}
a3[k]='X';
a3[++k]='\0';
a4[l]='/';
a5[l]='\0';
a4[++l]='\0';
strcat(a4,a5);
printf("\n A->%s'",a3);
printf("\n X'->%s",a4);
getch();
}

OUTPUT:

Enter the no. of productions : 2


Production 1
Enter the no. of productions : 3
Enter LHS : S
S->iCtSeS
S->iCtS
S->a
Production 2
Enter the no. of productions : 1
Enter LHS : C
C->b
The resulting productions are :
S' -> ε| eS| |
C -> b
S ->iCtSS' | a

RESULT:
The following program was successfully compiled and executed.
Ex 5. FIRST and FOLLOW

AIM: To write a C program to find the FIRST and the FOLLOW of a grammar.

ALGORITHM:
1. Accept the number of productions,
2. Accept the production values,
3. Find the FIRST of the values entered,
4. Find the FOLLOW of the values entererd.

PROGRAM:

#include<stdio.h>
#include<string.h>
#include<ctype.h>
int n,m=0,p,i=0,j=0;
char a[10][10],f[10];
void follow(char c);
void first(char c);
int main(){
int i,z;
char c,ch;
printf("Enter the no of prooductions:\n");
scanf("%d",&n);
printf("Enter the productions:\n");
for(i=0;i<n;i++)
scanf("%s%c",a[i],&ch);
do{
m=0;
printf("Enter the elemets whose fisrt & follow is to be found:");
scanf("%c",&c);
first(c);
printf("First(%c)={",c);
for(i=0;i<m;i++)
printf("%c",f[i]);
printf("}\n");
strcpy(f," ");
m=0;
follow(c);
printf("Follow(%c)={",c);
for(i=0;i<m;i++)
printf("%c",f[i]);
printf("}\n");
printf("Continue(0/1)?");
scanf("%d%c",&z,&ch);
}while(z==1);
return(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[k][0]);
else if(islower(a[k][2]))
f[m++]=a[k][2];
else first(a[k][2]);
}
}
}
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]);
}}}}

OUTPUT:

Enter the productions(type 'end' at the last of the production)


E->TA
A->+TA
A->ε
T->FB
B->*FB
B->ε
F->(E)
F->i
end

NT First Follow
______________________

E (i #)
A +ε #)
T (i +#)
B *ε +#)
F (i *+#)

_____________________

RESULT:
The following program was successfully compiled and executed.
Ex 6. Computation of Leading and Trailing

AIM: To write a C program to find the leading and trailing terminals of a given grammar.

ALGORITHM:
1. First include the necessary package,
2. Declare the array array and their functions,
3. Accept the number of productions,
4. Accept the different productions,
5. Find and print the leading terminals and the trailing terminals of the grammar.

PROGRAM:

#include<iostream>
#include<string.h>
using namespace std;
int nt,t,top=0;
char s[50],NT[10],T[10],st[50],l[10][10],tr[50][50];
int searchnt(char a){
int count=-1,i;
for(i=0;i<nt;i++){
if(NT[i]==a)
return i;
}
return count;
}
int searchter(char a){
int count=-1,i;
for(i=0;i<t;i++){
if(T[i]==a)
return i;
}
return count;
}
void push(char a){
s[top]=a;
top++;
}
char pop(){
top--;
return s[top];
}
void installl(int a,int b){
if(l[a][b]=='f'){
l[a][b]='t';
push(T[b]);
push(NT[a]);
}
}
void installt(int a,int b){
if(tr[a][b]=='f'){
tr[a][b]='t';
push(T[b]);
push(NT[a]);
}
}

int main(){
int i,s,k,j,n;
char pr[30][30],b,c;
cout<<"Enter the no of productions:";
cin>>n;
cout<<"Enter the productions one by one\n";
for(i=0;i<n;i++)
cin>>pr[i];
nt=0;
t=0;
for(i=0;i<n;i++){
if((searchnt(pr[i][0]))==-1)
NT[nt++]=pr[i][0];
}
for(i=0;i<n;i++){
for(j=3;j<strlen(pr[i]);j++){
if(searchnt(pr[i][j])==-1){
if(searchter(pr[i][j])==-1)
T[t++]=pr[i][j];
}
}
}
for(i=0;i<nt;i++){
for(j=0;j<t;j++)
l[i][j]='f';
}
for(i=0;i<nt;i++){
for(j=0;j<t;j++)
tr[i][j]='f';
}
for(i=0;i<nt;i++){
for(j=0;j<n;j++){
if(NT[(searchnt(pr[j][0]))]==NT[i]){
if(searchter(pr[j][3])!=-1)
installl(searchnt(pr[j][0]),searchter(pr[j][3]));
else{
for(k=3;k<strlen(pr[j]);k++){
if(searchnt(pr[j][k])==-1){
installl(searchnt(pr[j][0]),searchter(pr[j]
[k]));
break;
}
}
}
}
}
}
while(top!=0){
b=pop();
c=pop();
for(s=0;s<n;s++){
if(pr[s][3]==b)
installl(searchnt(pr[s][0]),searchter(c));
}
}
for(i=0;i<nt;i++){
cout<<"Leading["<<NT[i]<<"]"<<"\t{";
for(j=0;j<t;j++){
if(l[i][j]=='t')
cout<<T[j]<<",";
}
cout<<"}\n";
}

top=0;
for(i=0;i<nt;i++){
for(j=0;j<n;j++){
if(NT[searchnt(pr[j][0])]==NT[i]){
if(searchter(pr[j][strlen(pr[j])-1])!=-1)
installt(searchnt(pr[j][0]),searchter(pr[j]
[strlen(pr[j])-1]));
else{
for(k=(strlen(pr[j])-1);k>=3;k--){
if(searchnt(pr[j][k])==-1){
installt(searchnt(pr[j]
[0]),searchter(pr[j][k]));
break;}}}}
}
}
while(top!=0){
b=pop();
c=pop();
for(s=0;s<n;s++){
if(pr[s][3]==b)
installt(searchnt(pr[s][0]),searchter(c));
}
}
for(i=0;i<nt;i++){
cout<<"Trailing["<<NT[i]<<"]"<<"\t{";
for(j=0;j<t;j++){
if(tr[i][j]=='t')
cout<<T[j]<<",";
}
cout<<"}\n";
}
}
OUTPUT:

------------- LEADING AND TRAILING ---------------

Enter the no. of variables : 3

Enter the variables :


E
T
F
Enter the no. of terminals : 5

Enter the terminals :


(
)
*
+
i

------------- PRODUCTION DETAILS -----------------


Enter the no. of production of E:2
E->E+T
E->T
Enter the no. of production of T:2
T->T*F
T->F
Enter the no. of production of F:2
F->(E)
F->i
LEADING(E) = (,*,+,i,
LEADING(T) = (,*,i,
LEADING(F) = (,i,
TRAILING(E) = ),*,+,i,
TRAILING(T) = ),*,i,
TRAILING(F) = ),i,

RESULT
The following program was successfully compiled and executed.
Ex 7. Construction of Predictive Parser

AIM: To write a C program to construct a Predictive Parser for a grammar.

ALGORITHM:
1. Accept the number of coordinates,
2. Accept the productions,
3. Print the FIRST of the grammar,
4. Print the FOLLLOW of the grammar,
5. Finally print if the string is accepted or not.

PROGRAM:

#include<string.h>
#include<stdio.h>
#include<conio.h>
char a[10];
int top=-1,i;
void error(){
printf("Syntax Error");
}
void push(char k[]){ //Pushes The Set Of Characters
on to the Stack for(i=0;k[i]!='\0';i++){
if(top<9)
a[++top]=k[i];
}
}
char TOS(){ //Returns TOP of the Stack
return a[top];
}
void pop(){ //Pops 1 element from the Stack
if(top>=0)
a[top--]='\0';
}
void display(){ //Displays Elements Of Stack
for(i=0;i<=top;i++)
printf("%c",a[i]);
}
void display1(char p[],int m){ //Displays The
Present Input String int l;
printf("\t");
for(l=m;p[l]!='\0';l++)
printf("%c",p[l]);
}
char* stack(){
return a;
}
int main(){
char ip[20],r[20],st,an;
int ir,ic,j=0,k;
char t[5][6][10]={"$","$","TH","$","TH","$",
"+TH","$","e","e","$","e",
"$","$","FU","$","FU","$",
"e","*FU","e","e","$","e",
"$","$","(E)","$","i","$"};
printf("\nEnter any String(Append with $)");
gets(ip);
printf("Stack\tInput\tOutput\n\n");
push("$E");
display();
printf("\t%s\n",ip);
for(j=0;ip[j]!='\0';){
if(TOS()==an){
pop();
display();
display1(ip,j+1);
printf("\tPOP\n");
j++;
}
an=ip[j];
st=TOS();
if(st=='E')ir=0;
else if(st=='H')ir=1;
else if(st=='T')ir=2;
else if(st=='U')ir=3;
else if(st=='F')ir=4;
else {
error();
break;
}
if(an=='+')ic=0;
else if(an=='*')ic=1;
else if(an=='(')ic=2;
else if(an==')')ic=3;
else if((an>='a'&&an<='z')||(an>='A'&&an<='Z')){ic=4;an='i';}
else if(an=='$')ic=5;
strcpy(r,strrev(t[ir][ic]));
strrev(t[ir][ic]);
pop();
push(r);
if(TOS()=='e'){
pop();
display();
display1(ip,j);
printf("\t%c->%c\n",st,238);
}else{
display();
display1(ip,j);
printf("\t%c->%s\n",st,t[ir][ic]);
}
if(TOS()=='$'&&an=='$')
break;
if(TOS()=='$'){
error();
break;
}
}
k=strcmp(stack(),"$");
if(k==0 )
printf("\n Given String is accepted");
else
printf("\n Given String is not accepted");
return 0;
}

OUTPUT:

Enter the no. of co-ordinates


2
Enter the productions in a grammar
S->CC
C->eC | d
First pos
FIRS[S] = ed
FIRS[C] = ed
Follow pos
FOLLOW[S] =$
FOLLOW[C] =ed$
M [S , e] =S->CC
M [S , d] =S->CC
M [C , e] =C->eC
M [C , d] =C->d

RESULT:
The following program was successfully compiled and executed.
Ex 8. Implementation of Shift Reduce Parser

AIM: To write a C program to implement Shift Reduce Parser.

ALGORITHM:
1. Assume a grammar,
2. Accept the input string,
3. Print the actions.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<string.h>
int k=0,z=0,i=0,j=0,c=0;
char a[16],ac[20],stk[15],act[10];
void check();
int main()
{
puts("GRAMMAR is E->E+E \n E->E*E \n E->(E) \n E->id");
puts("enter input string ");
gets(a);
c=strlen(a);
strcpy(act,"SHIFT->");
puts("stack \t input \t action");
for(k=0,i=0; j<c; k++,i++,j++)
{
if(a[j]=='i' && a[j+1]=='d')
{
stk[i]=a[j];
stk[i+1]=a[j+1];
stk[i+2]='\0';
a[j]=' ';
a[j+1]=' ';
printf("\n$%s\t%s$\t%sid",stk,a,act);
check();
}
else
{
stk[i]=a[j];
stk[i+1]='\0';
a[j]=' ';
printf("\n$%s\t%s$\t%ssymbols",stk,a,act);
check();
}
}
getch();
}
void check()
{
strcpy(ac,"REDUCE TO E");
for(z=0; z<c; z++)
if(stk[z]=='i' && stk[z+1]=='d')
{
stk[z]='E';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
j++;
}
for(z=0; z<c; z++)
if(stk[z]=='E' && stk[z+1]=='+' && stk[z+2]=='E')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+2]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
for(z=0; z<c; z++)
if(stk[z]=='E' && stk[z+1]=='*' && stk[z+2]=='E')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
for(z=0; z<c; z++)
if(stk[z]=='(' && stk[z+1]=='E' && stk[z+2]==')')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
}
OUTPUT:

Enter the productions of the grammar(END to end):

S->iCtSeS|iCtS|a
C->b
END

ENTER THE INPUT STRING: ibtaea

-------------------------------------------------------------
STACK INPUT ACTION
-------------------------------------------------------------
# ibtaea# SHIFT ' i '
#ibtaea# SHIFT ' b '
#ibtaea# REDUCE BY C -> b
#iCtaea# SHIFT ' t '
#iCtaea# SHIFT ' a '
#iCtaea# REDUCE BY S -> a
#iCtSea# SHIFT ' e '
#iCtSe a# SHIFT ' a '
#iCtSea # REDUCE BY S -> a
#iCtSeS # REDUCE BY S ->iCtSeS
#S # ACCEPT
---------------------------------------------------------------

RESULT:
The following program was successfully compiled and executed.
Ex 9. Computation of LR(0) items

AIM: To write a C program for LR(0) parser for the given productions.

ALGORITHM:
1. Assume a grammar,
2. Accept the input string,
3. Print the actions.

PROGRAM:

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

int axn[][6][2]={
{{100,5},{-1,-1},{-1,-1},{100,4},{-1,-1},{-1,-1}},
{{-1,-1},{100,6},{-1,-1},{-1,-1},{-1,-1},{102,102}},
{{-1,-1},{101,2},{100,7},{-1,-1},{101,2},{101,2}},
{{-1,-1},{101,4},{101,4},{-1,-1},{101,4},{101,4}},
{{100,5},{-1,-1},{-1,-1},{100,4},{-1,-1},{-1,-1}},
{{100,5},{101,6},{101,6},{-1,-1},{101,6},{101,6}},
{{100,5},{-1,-1},{-1,-1},{-1,-1},{-1,-1},{-1,-1}},
{{100,5},{-1,-1},{-1,-1},{100,4},{-1,-1},{-1,-1}},
{{-1,-1},{100,6},{-1,-1},{-1,-1},{100,11},{-1,-1}},
{{-1,-1},{101,1},{100,7},{-1,-1},{101,1},{101,1}},
{{-1,-1},{101,3},{101,3},{-1,-1},{101,3},{101,3}},
{{-1,-1},{101,5},{101,5},{-1,-1},{101,5},{101,5}}
};

int gotot[12][3]={1,2,3,-1,-1,-1,-1,-1,-1,-1,-1,-
1,8,2,3,-1,-1,-1,-1, 9,3,-1,-1,10,-1,-1,-
1,-1,-1,-1,-1,-1,-1,-1,-1,-1};

int a[10];
char b[10];
int top=-1,btop=-1,i;
void push(int k)
{
if(top<9)
a[++top]=k;
}
void pushb(char k)
{
if(btop<9)
b[++btop]=k;
}
char TOS()
{
return a[top];
}
void pop()
{
if(top>=0)
top--;
}

void popb()
{
if(btop>=0)
b[btop--]='\0';
}

void display()
{
for(i=0;i<=top;i++)
printf("%d%c",a[i],b[i]);
}

void display1(char p[],int m)


{
int l;
printf("\t\t");
for(l=m;p[l]!='\0';l++)
printf("%c",p[l]);
printf("\n");
}

void error()
{
printf("\n\nSyntax Error");
}
void reduce(int p)
{
int len,k,ad;
char src,*dest;
switch(p)
{
case 1:dest="E+T";
src='E';
break;
case 2:dest="T";
src='E';
break;
case 3:dest="T*F";
src='T';
break;
case 4:dest="F";
src='T';
break;
case 5:dest="(E)";
src='F';
break;
case 6:dest="i";
src='F';
break;
default:dest="\0";
src='\0';
break;
}
for(k=0;k<strlen(dest);k++)
{
pop();
popb();
}
pushb(src);
switch(src)
{
case 'E': ad=0;
break;
case 'T': ad=1;
break;
case 'F': ad=2;
break;
default: ad=-1;
break;
}
push(gotot[TOS()][ad]);
}
int main()
{
int j,st,ic;
char ip[20]="\0",an;
clrscr();
printf("Enter any String :- ");
gets(ip);
push(0);
display();
printf("\t%s\n",ip);
for(j=0;ip[j]!='\0';)
{
st=TOS();
an=ip[j];
if(an>='a'&an<='z')
ic=0;
else if(an=='+')
ic=1;
else if(an=='*')
ic=2;
else if(an=='(')
ic=3;
else if(an==')')
ic=4;
else if(an=='$')
ic=5;
else
{
error();
break;
}
if(axn[st][ic][0]==100)
{
pushb(an);
push(axn[st][ic][1]);
display();
j++;
display1(ip,j);
}
if(axn[st][ic][0]==101)
{
reduce(axn[st][ic][1]);
display();
display1(ip,j);
}
if(axn[st][ic][1]==102)
{
printf("Given String is Accepted");
break;
}
}
getch();
return 0;
}

OUTPUT:

ENTER THE PRODUCTIONS OF THE GRAMMAR (0 TO END) :


E->E+T
E->T
T->T*F
T->F
F->(E)
F->i
0

augumented grammar

A->E
E->E+T
E->T
T->T*F
T->F
F->(E)
F->i
THE SET OF ITEMS ARE
I0
A->.E
E->.E+T
E->.T
T->.T*F
T->.F
F->.(E)
F->.i
I1
A->E.
E->E.+T
I2
E->T.
T->T.*F
I3
T->F.
I4
F->(.E)
E->.E+T
E->.T
T->.T*F
T->.F
F->.(E)
F->.i
I5
F->i.
I6
E->E+.T
T->.T*F
T->.F
F->.(E)
F->.i
I7
T->T*.F
F->.(E)
F->.i
I8
F->(E.)
E->E.+T
I9
E->E+T.
T->T.*F
I10
T->T*F.
I11
F->(E).

RESULT:
The following program was successfully compiled and executed.
Ex. 10. Construction of DAG

AIM: To write a C program to construct of DAG (Directed Acyclic Graph)

ALGORITHM:
1. Start the program

2. Include all the header files

3.Check for postfix expression and construct the in order DAG representation

4. Print the output

5. Stop the program

PROGRAM:
#include<stdio.h>

#include<string.h>

#include<ctype.h>

#include<conio.h>

void main()

struct da

int ptr,left,right;

char label;

}dag[25];

int ptr,l,j,change,n=0,i=0,state=1,x,y,k;

char store,*input1,input[25],var;

clrscr();

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

dag[i].ptr=NULL;

dag[i].left=NULL;
dag[i].right=NULL;

dag[i].label=NULL;

printf("\n\nENTER THE EXPRESSION\n\n");

scanf("%s",input1);

/*EX:((a*b-c))+((b-c)*d)) like this give with paranthesis.limit

is 25 char ucan change that*/

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

input[i]=NULL;

l=strlen(input1);

a:

for(i=0;input1[i]!=')';i++);

for(j=i;input1[j]!='(';j--);

for(x=j+1;x<i;x++)

if(isalpha(input1[x]))

input[n++]=input1[x];

else

if(input1[x]!='0')

store=input1[x];

input[n++]=store;

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

input1[x]='0';

if(input1[0]!='0')goto a;

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

dag[i].label=input[i];
dag[i].ptr=i;

if(!isalpha(input[i])&&!isdigit(input[i]))

dag[i].right=i-1;

ptr=i;

var=input[i-1];

if(isalpha(var))

ptr=ptr-2;

else

ptr=i-1;

b:

if(!isalpha(var)&&!isdigit(var))

ptr=dag[ptr].left;

var=input[ptr];

goto b;

else

ptr=ptr-1;

dag[i].left=ptr;

printf("\n SYNTAX TREE FOR GIVEN

EXPRESSION\n\n"); printf("\n\n PTR \t\t LEFT

PTR \t\t RIGHT PTR \t\t LABEL\n\n");


for(i=0;i<n;i++)/* draw the syntax tree for the following

output with pointer value*/

printf("\n%d\t%d\t%d\t%c\n",dag[i].ptr,dag[i].left,dag[i].right,dag[i].label);

getch();

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

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

if((dag[i].label==dag[j].label&&dag[i].left==dag[j].left)&&dag[i].right==dag[j].right
)

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

if(dag[k].left==dag[j].ptr)dag[k].left=dag[i].ptr;

if(dag[k].right==dag[j].ptr)dag[k].right=dag[i].ptr;

dag[j].ptr=dag[i].ptr;

printf("\n DAG FOR GIVEN EXPRESSION\n\n");

printf("\n\n PTR \t LEFT PTR \t RIGHT PTR \t

LABEL \n\n"); for(i=0;i<n;i++)/*draw DAG for

the following output with pointer value*/

printf("\n %dt\t%d\t\t%d\t\t

%c\n",dag[i].ptr,dag[i].left,dag[i].right,dag[i].label); getch();}
OUTPUT:

ENTER THE EXPRESSION

((a*b-c))+((b-c)*d))

SYNTAX TREE FOR GIVEN EXPRESSION:

PTR LEFT PTR RIGHT PTR LABEL

0 0 0 a

1 0 0 b

2 0 0 c

3 1 2 -

4 0 3 -

DAG FOR GIVEN EXPRESSION:

PTR LEFT PTR RIGHT PTR LABEL

0 0 0 a

1 0 0 b

2 0 0 c

3 1 2 -

4 0 3 -

RESULT:
Thus the program for implementation of DAG has been successfully executed and
output is verified.
Ex. 11 Intermediate Code Generation – 3 Address Code

AIM: A program to implement Intermediate Code Generation

ALGORITHM:

1.Start.
2.Initialize required variables.
3.A quadruple has four fields op,arg1,arg2,result.
4.Triple has only three fields op,arg1,arg2.
5.Assign a value to the variables given.
6.Assign a register to variables and perform arithmetic operations.
7.Move the final result to assign variable.
8.Display the output.
9. End.

PROGRAM:

#include"stdio.h"
#include"conio.h"
#include"string.h"
int i=1,j=0,no=0,tmpch=90;
char str[100],left[15],right[15];
void findopr();
void explore();
void fleft(int);
void fright(int);
struct exp
{
int pos;
char op;
}k[15];
void main()
{
clrscr();
printf("\t\tINTERMEDIATE CODE GENERATION\n\n");
printf("Enter the Expression :"); scanf("%s",str);

printf("The intermediate code:\t\tExpression\n");


findopr();
explore();
getch();
}
void findopr()
{
for(i=0;str[i]!='\0';i++)
if(str[i]==':')
{
k[j].pos=i;
k[j++].op=':';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='/')
{
k[j].pos=i;
k[j++].op='/';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='*')
{
k[j].pos=i;
k[j++].op='*';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='+')
{
k[j].pos=i;
k[j++].op='+';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='-')
{
k[j].pos=i;
k[j++].op='-';
}
}
void explore()
{
i=1;
while(k[i].op!='\0')
{
fleft(k[i].pos);
fright(k[i].pos);
str[k[i].pos]=tmpch--;
printf("\t%c := %s%c%s\t\t",str[k[i].pos],left,k[i].op,right);
for(j=0;j <strlen(str);j++)
if(str[j]!='$')
printf("%c",str[j]);
printf("\n");
i++;
}
fright(-1);
if(no==0)
{
fleft(strlen(str));
printf("\t%s := %s",right,left);
getch();
exit(0);
}
printf("\t%s := %c",right,str[k[--i].pos]);
getch();
}
void fleft(int x)
{
int w=0,flag=0;
x--;
while(x!= -1 &&str[x]!= '+' &&str[x]!='*'&&str[x]!='='&&str[x]!='\0'&&str[x]!='-'&&str[x]!='/'&&str[x]!=':')
{
if(str[x]!='$'&& flag==0)
{
left[w++]=str[x];
left[w]='\0';
str[x]='$';
flag=1;
}
x--;
}
}
void fright(int x)
{
int w=0,flag=0;
x++;
while(x!= -1 && str[x]!= '+'&&str[x]!='*'&&str[x]!='\0'&&str[x]!='='&&str[x]!=':'&&str[x]!='-'&&str[x]!='/')
{
if(str[x]!='$'&& flag==0)
{
right[w++]=str[x];
right[w]='\0';
str[x]='$';
flag=1;
}
x++;
}
}
OUTPUT:

INTERMEDIATE CODE GENERATION

Expression :

d=t+b*z
Intermediate code:
Z:= t+b d=Z*z
D:=z

RESULT:
The program was successfully compiled and run
Ex. 12 Intermediate Code Generation – Postfix and
Prefix

AIM: A program to implement Intermediate Code Generation

ALGORITHM:
1.Start the Program.
2. Declare all the header files.
3. Check for string from left to right
4. Get the expression.
5. Print the Output
6. Exit.

PROGRAM:

#define SIZE 50
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <ctype.h>
#include <conio.h>
void findopr();
void explore();
void fleft(int);
void fright(int);
int i=1,j=0,no=0,tmpch=90;
char str[100],left[15],right[15];
char s[SIZE];
int top=-1;
struct exp
{
int pos;
char op;
}k[15];
void fleft(int x)
{
int w=0,flag=0;
x--;
while(x!= -1 &&str[x]!= '+' &&str[x]!='*'&&str[x]!='='&&str[x]!='\0'&&str[x]!
='-'&&str[x]!='/'&&str[x]!=':')
{
if(str[x]!='$'&& flag==0)
{
left[w++]=str[x];
left[w]='\0';
str[x]='$';
flag=1;
}
x--;
}
}
void fright(int x)
{
int w=0,flag=0;
x++;
while(x!= -1 && str[x]!= '+'&&str[x]!='*'&&str[x]!='\0'&&str[x]!='='&&str[x]!
=':'&&str[x]!='-'&&str[x]!='/')
{
if(str[x]!='$'&& flag==0)
{
right[w++]=str[x];
right[w]='\0';
str[x]='$';
flag=1;
}
x++;
}
}
void findopr()
{
for(i=0;str[i]!='\0';i++)
if(str[i]==':')
{
k[j].pos=i;
k[j++].op=':';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='/')
{
k[j].pos=i;
k[j++].op='/';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='*')
{
k[j].pos=i;
k[j++].op='*';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='+')
{
k[j].pos=i;
k[j++].op='+';
}
for(i=0;str[i]!='\0';i++)
if(str[i]=='-')
{
k[j].pos=i;
k[j++].op='-';
}
}
void explore()
{
i=1;
while(k[i].op!='\0')
{
fleft(k[i].pos);
fright(k[i].pos);
str[k[i].pos]=tmpch--;
printf("\t%c := %s%c%s\t\t",str[k[i].pos],left,k[i].op,right);
for(j=0;j <strlen(str);j++)
if(str[j]!='$')
printf("%c",str[j]);
printf("\n");
i++;
}
fright(-1);
if(no==0)
{
fleft(strlen(str));
printf("\t%s := %s",right,left);
getch();
exit(0);
}
printf("\t%s := %c",right,str[k[--i].pos]);
getch();
}
/* Global declarations */

void push(char elem)


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

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

int pr(char elem)


{/* Function for precedence */
switch(elem)
{
case '#': return 0;
case ')': return 1;
case '+':;
case '-': return 2;
case '*':;
case '/': return 3;
}
}

int main()
{ /* Main Program */
char infx[50],prfx[50],pofx[50],ch,elem;
int i=0,k=0;
printf("Enter the Expression:");
scanf("%s",infx);
push('#');
i=0;
while( (ch=infx[i++]) != '\0')
{
if( ch == '(') push(ch);
else
if(isalnum(ch)) pofx[k++]=ch;
else
if( ch == ')')
{
while( s[top] != '(')
pofx[k++]=pop();
elem=pop(); /* Remove ( */
}
else
{ /* Operator */
while( pr(s[top]) >= pr(ch) )
pofx[k++]=pop();
push(ch);
}
}
while( s[top] != '#') /* Pop from stack till
empty */ pofx[k++]=pop();

pofx[k]='\0'; /* Make pofx as valid string */


i=0;k=0;
push('#');
strrev(infx);
while( (ch=infx[i++]) != '\0')
{
if( ch == ')') push(ch);
else
if(isalnum(ch)) prfx[k++]=ch;
else
if( ch == '(')
{
while( s[top] != ')')
prfx[k++]=pop();
elem=pop(); /* Remove ) */
}
else
{ /* Operator */
while( pr(s[top]) >= pr(ch) )
prfx[k++]=pop();
push(ch);
}
}
while( s[top] != '#') /* Pop from stack till
empty */ prfx[k++]=pop();

prfx[k]='\0'; /* Make prfx as valid string */


strrev(prfx);
strrev(infx);
strcpy(str, infx);
printf("Given Infix Expn: %s Prefix Expn: %s\n",infx,prfx);
printf("Given Infix Expn: %s Postfix Expn: %s\n",infx,pofx);
printf("The intermediate code:\t\tExpression\n");
findopr();
explore();
getch();
return 0;
}

OUTPUT:

abcd^e-fgh*+^*+i-

RESULT: Thus the program to generate three address code for prefix and postfix has been successfully
executed.

Das könnte Ihnen auch gefallen