SP LAB MANUALfinal
SP LAB MANUALfinal
LAB RECORD
SEMESTER – II
2021- 2022
1
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
VADAPALANI CAMPUS
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
BONAFIDE CERTIFICATE
M.Tech – Computer Science and Engineering, First Year, II Semester as a Partial Fulfillment of Degree of
Master of Technology in Computer Science and Engineering for the Laboratory of the course
2
DATE Examiner-1 Examiner- II
INDEX
Ex..NO Date Name of experiment Page
Sign
number
Implementation of Pass I of Two pass Assembler
1. 4.3.2022
3
Date : Implementation of Pass I of Two pass Assembler
Ex.No. : 1
AIM:
To write a c program to perform first pass of two pass assembler.
ALGORITHM:
1. Start the program.
2. Get the assembly language program and the optab.
3. Display the symbol names along with its address in the symbol table. ∙
4. Display the assembly language program along with its address in the intermediate file.
5. Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct instruction
{
char symbol[10];
char opcode[10];
}in;
struct opcode
{
char opcode[10];
char val[10];
}op;
void main()
{
FILE *fin,*flab,*fsym,*fint;
int locctr;
int length;
int val;
char val1[10];
int len;
char operand[10];
int startadd;
4
clrscr();
fin=fopen("inp.c","r");
flab=fopen("optab.c","r");
fsym=fopen("symb.c","w");
fint=fopen("inter.c","w");
fscanf(fin,"%s%s",in.symbol,in.opcode);
while(!feof(fin))
{
if(strcmp(in.symbol,"-")!=0&&strcmp(in.opcode,"START")!=0) {
fprintf(fsym,"%s\t%d\n",in.symbol,locctr);
}
if(strcmp(in.opcode,"START")==0)
{
printf("START\n");
fscanf(fin,"%d",&val);
printf("val=%d\n",val);
locctr=val;
startadd=val;
fscanf(fin,"%s%s",in.symbol,in.opcode);
if(strcmp(in.symbol,"-")!=0)
{
fprintf(fsym,"%s\t%d\n",in.symbol,locctr);
}
}
rewind(flab);
while(!feof(flab))
{
fscanf(flab,"%s%s",op.opcode,op.val);
if(strcmp(op.opcode,in.opcode)==0)
{
printf("instruction\n");
fscanf(fin,"%s",operand);
5
fprintf(fint,"%d\t%s\t%s\t%s\n",locctr,in.symbol,in.opcode,operand); locctr=locctr+3;
}
}
if(strcmp(in.opcode,"WORD")==0);
{
printf("WORD\n");
fscanf(fin,"%d",&val);
fprintf(fint,"%d\t%s\t%s\t%d\n",locctr,in.symbol,in.opcode,val); locctr=locctr+3;
}
else if(strcmp(in.opcode,"BYTE")==0)
{
printf("BYTE\n");
fscanf(fin,"%s",val1);
fprintf(fint,"%d\t%s\t%s\t%s\n",locctr,in.symbol,in.opcode,val1); if(val1[0]=='c')
{
len=strlen(val1);
locctr=locctr+len-1;
}
else
{
locctr+=1;
}
}
else if(strcmp(in.opcode,"RESW")==0)
{
printf("RESW\n");
fscanf(fin,"%d",&val);
fprintf(fint,"%d\t%s\t%s\t%d\n",locctr,in.symbol,in.opcode,val);
locctr=locctr+3*val;
}
else if(strcmp(in.opcode,"RESB")==0)
{
6
printf("RESB\n");
fscanf(fin,"%d",&val);
fprintf(fint,"%d\t%s\t%s\t%d\n",locctr,in.symbol,in.opcode,val); locctr=locctr+val;
}
else if(strcmp(in.opcode,"END")==0)
{
printf("END\n");
fscanf(fin,"%s",operand);
fprintf(fint,"%d\t%s\t%s\t%s\n",locctr,in.symbol,in.opcode,operand);
length=locctr+startadd;
printf("length=%d",length);
}
fscanf(fin,"%s%s\n",in.symbol,in.opcode);
}
fclose(fin);
fclose(fsym);
fclose(fint);
fclose(flab);
getch();
}
INPUT:
COPY START 1000
FIRST LDA ALPHA
ADD ONE
_ SUB INCR
_ STA BETA
_ BYTE X'F1'
ALPHA RESW 1
ONE RESW 1
INCR RESW 1
BETA RESW 1
_ END FIRST
OPTAB:
LDA 00
ADD 18
7
SUB 0C
STA 1C
OUTPUT:
SYMBOL TABLE:
1000 START
1003 LDA
1006 ADD
1009 SUB
1012 STA
1013 BYTE
INTERMADIATE FILE:
RESULT:
8
Date : Implementation of Pass II of Two pass Assembler
Ex.No. : 2
AIM:
To write a c program to perform pass two of two pass assembler.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct instruction
{
int addr;
char symbol[10]; char
opcode[10];
}in;
struct opcode
{
char opcode[10]; char val[10];
}op;
struct symbol
{
char label[10]; int addr;
}s;
void main()
{
FILE*ftab,*fint,*fsym,*fout; char
val1[10],temp1[10];
9
int val,address; clrscr();
fint=fopen("inter.c","r");
fout=fopen("output.c","w"); fscanf(fint,"%d%s
%s",&in.addr,in.symbol,in.opcode); while(!feof(fint))
{
if(strcmp(in.opcode,"WORD")==0)
{
fscanf(fint,"%d",val); fprintf(fout,"%d\t%d\
n",in.addr,val)
;}
else if(strcmp(in.opcode,"BYTE")==0)
{
fscanf(fint,"%s",val1); fprintf(fout,"%d\t%s\
n",in.addr,val1);
}
else if(strcmp(in.opcode,"RESSW")==0)
{
fscanf(fint,"%d",&val);
}
else if(strcmp(in.opcode,"RESB")==0)
{
fscanf(fint,"%d",&val);
}
else if(strcmp(in.opcode,"END")==0)
{
fscanf(fint,"%s",val1);
}
else
{
fscanf(fint,"%s",val1);
ftab=fopen("optab.c","r"); fscanf(ftab,"%s
%s",op.opcode,op.val); while(!feof(ftab))
10
{
if(strcmp(in.opcode,op.opcode)==0)
{
strcpy(temp1,op.val);
}
fscanf(ftab,"%s%s",op.opcode,op.val);
}
fclose(ftab); fsym=fopen("symb.c","r");
fscanf(fsym,"%s%d",s.label,&s.addr); while(!
feof(fsym))
{
if(strcmp(val1,s.label)==0)
{
address=s.addr;
}
fscanf(fsym,"%s%d",s.label,&s.addr);
}
fclose(fsym); fprintf(fout,"%d\t%s\n",in.addr,temp1,address);
}
fscanf(fint,"%d%s%s",&in.addr,in.symbol,in.opcode);
}
printf("OBJECT PROGRAM IS STORED IN OUTPUT.C\n");
getch();
}
INPUT:
INTERMEDIATE FILE:
OUTPUT:
1000 00
1003 18
1006 1C
1009 1C
1012 X’F1’
1013 1C
1016 1C
1019 1C
RESULT:
12
Date :
Ex.No. : 3
Design of Macro Processor
AIM:
To write a c program to perform macro substitution.
ALGORITHM:
1. Start the program.
2. Get the assembly language program as input.
3. When the macro name occurs, substitute the contents of the macro.
4. Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h> struct ins
{
char symbol[10]; char opcode[10];
char val[10];
}i;
void main()
{
FILE *fp,*fin; char temp[10]; char
name[10][10]; int j,t,i1,totmac=0;
clrscr();
fin=fopen("inmac.c","r"); fscanf(fin,"%s%s
%s",i.symbol,i.opcode,i.val); while(!feof(fin))
{
if(strcmp(i.opcode,"MACRO")==0)
{
totmac+=1; strcpy(name[totmac],i.symbol);
fp=fopen(i.symbol,"w");
while(strcmp(i.opcode,"MEND")!=0)
{
13
fprintf(fp,"%s\t%s\t%s\n",i.symbol,i.opcode,i.val); fscanf(fin,"%s%s
%s",i.symbol,i.opcode,i.val);
}
fclose(fp);
}
else
{ t=0,j=0;
for(i1=1;i1<=totmac;i1++)
{
if(strcmp(i.opcode,name[i1])==0)
{ t=1;
fp=fopen(i.opcode,"r");
printf(".");
fscanf(fp,"%s",temp);
while(!feof(fp))
{ j++;
printf("%s\t",temp); if(j==3)
{
printf("%s\n",temp); j=0;
}
fscanf(fp,"%s",temp);
}}}
if(t==0)
{
if(j<3)
printf("%s\t%s\t%s\n",i.symbol,i.opcode,i.val);
}
}
fscanf(fin,"%s%s%s",i.symbol,i.opcode,i.val);
}
getch();}
14
INPUT :
INMAC.C
ALPHA RESW 1
INCR RESW 1
ONE WORD 1
BETAR RESW 1
_ END FIRST
OUTPUT:
RESULT:
15
Date :
Ex.No. : 4
Implementation of Lexical Analyzer
Aim:
Algorithm:
1. Start
2. Get C program input file.
3. Read the contents of file character by character into ch.
4. If op contains ch, print operator.
5. If pun contains ch, print punctuation.
6. If ch is alphanumeric, store in buffer buf and read next character.
7. Store ch until whitespace or new line is encountered.
8. If keyword contains buf, print keyword.
9. If isdigit(buf) true, print digit.
10. Else, print identifier.
Program:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
int iskeyword(char buf[])
{
char keyword[11][10]={"int","float","for","while","if","else","do","double","return","void","main"};
int i, flag=0;
for(i=0;i<11;i++)
{
if(strcmp(keyword[i],buf)==0)
{
flag=1;
16
break;
}
}
return flag;
}
void main()
{
char op[7]={'+','-','=','*','/','%','&'};
char pun[3]={',',';','!'};
char ch,buf[15],name[10];
FILE *fp;
int i,j=0;
clrscr();
printf("enter file name: ");
scanf("%s",name);
fp=fopen(name,"r");
while((ch=fgetc(fp))!=EOF)
{
for(i=0;i<7;i++)
if(ch==op[i])
printf("\n%c: operator",ch);
for(i=0;i<3;i++)
if(ch==pun[i])
printf("\n%c: punctuation",ch);
if(isalnum(ch))
buf[j++]=ch;
else
if((ch==' '||ch=='\n')&&(j!=0))
{
buf[j]='\0';
17
j=0;
if(iskeyword(buf)==1)
printf("\n%s: keyword",buf);
else if((int)buf[0]>=48&&(int)buf[0]<=57)
printf("\n%s: digit",buf);
else
printf("\n%s: identifier",buf);
}
}
fclose(fp);
getch();
}
Output:
Result:
Thus, the C program to implement lexical analyzer has been executed and the output has been verified
successfully
18
Date : Regular Expression to NFA
Ex.No. : 5
Aim:
To write a program to convert Regular Expression to NFA.
Algorithm:
1. Start
2. Get input of the regular expression.
3. Read input character by character into s.
4. If s is alphabet, store in ret[].
5. If s is ‘.’, ‘+’, ‘*’, determine transition inputs according to Thompson’s Construction.
6. Store the transition inputs in ret.
7. Display the output.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
int ret[100];
static int pos=0;
static int sc=0;
void nfa(int st, int p, char* s)
{
int i,sp,fs[15],fsc=0;
sp=st;
pos=p;
sc=st;
while(*s!=NULL)
{
if(isalpha(*s))
{
19
ret[pos++]=sp;
ret[pos++]=*s;
ret[pos++]=++sc;
}
if(*s=='.')
{
sp=sc; ret[pos+
+]=sc; ret[pos+
+]=238; ret[pos+
+]=++sc; sp=sc;
}
if(*s=='+')
{
sp=st; fs[fsc+
+]=sc;
}
if(*s=='*')
{
ret[pos++]=sc;
ret[pos++]=238;
ret[pos++]=sp;
ret[pos++]=sp;
ret[pos++]=238;
ret[pos++]=sc;
}
if(*s=='(')
{
char ps[50];
20
int i=0, flag=1;
s++;
while(flag!=0)
{
ps[i++]=*s;
if(*s=='(')
flag++;
if(*s==')')
flag--;
s++;
}
ps[--i]='\0';
nfa(sc,pos,ps);
s--;
}
s++;
}
sc++;
}
void main()
{
int i;
char *inp;
printf("\nenter the regular expression: ");
gets(inp);
nfa(1,0,in
p);
printf("\nstate input state\n");
for(i=0;i<pos;i+=3)
21
printf("%d -->%c--> %d\n",ret[i],ret[i+1],ret[i+2]);
printf("\n");
getch();
}
Output:
Result:
Thus, the C program to construct NFA for the given regular expression has been executed and the output has
been verified successfully
22
Date : Conversion of NFA to DFA
Ex.No. 6
Aim:
To write a program to convert NFA to DFA.
Algorithm:
1. Start
2. Get the input for NFA transitions.
3. Determine the closure of input state.
4. Find the states that can be traversed from present for each input symbol.
5. If any new state is found, take it as current state and repeat step 4.
6. Repeat steps 4 and 5 until no new state is found.
7. Display the DFA table.
Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
char nfa[50][50],s[20],st[10][20],eclos[20],input[20];
int x,e,top=0,topd=0,n=0,ns,nos,in;
int checke(char a)
{
int i;
for(i=0;i<e;i++)
{
if(eclos[i]==a)
return i;
}
return -1;
}
int check(char a)
{
int i;
for(i=0;i<in;i++)
{
23
if(input[i]==a)
return i;
}
return -1;
}
void push(char a)
{
s[top]=a;
top++;
}
char pop()
{
top--;
return s[top];
}
void pushd(char *a)
{
strcpy(st[topd],a);
topd++;
}
char *popd()
{
topd--;
return st[topd];
}
int ctoi(char a)
{
int i=a-48;
return i;
}
24
char itoc(int a)
{
char i=a+48;
return i;
}
char *eclosure(char *a)
{
int i,j;
char c;
for(i=0;i<strlen(a);i++)
push(a[i]);
e=strlen(a);
strcpy(eclos,a);
while(top!=0)
{
c=pop();
for(j=0;j<ns;j++)
{
if(nfa[ctoi(c)][j]=='e')
{
if(check(itoc(j))==-1)
{
eclos[e]=itoc(j);
push(eclos[e]);
e++;
}
}
}
}
eclos[e]='\0';
25
return eclos;
}
void main()
{
int i,j,k,count;
char ec[20],a[20],b[20],c[20],dstates[10][10];
clrscr();
printf("Enter the number of states\n");
scanf("%d",&ns);
for(i=0;i<ns;i++)
{
for(j=0;j<ns;j++)
{
printf("Move [%d][%d]:",i,j);
scanf("%s",&nfa[i][j]); if(nfa[i]
[j]!='-' && nfa[i][j]!='e')
{
if((check(nfa[i][j]))==-1)
input[in++]=nfa[i][j];
}
}
}d=0; nos=0; c[0]=itoc(0);
c[1]='\0';
pushd(eclosure(c));
strcpy(dstates[nos],eclosure(c));
for(x=0;x<in;x++)
printf("\t%c",input[x]);
printf("\n");
while(topd>0)
{
26
strcpy(a,popd());
printf(" %s",a);
for(i=0;i<in;i++)
{
int len=0;
for(j=0;j<strlen(a);j++)
{
int x=ctoi(a[j]);
for(k=0;k<ns;k++)
{
if(nfa[x][k]==input[i])
ec[len++]=itoc(k);
}
}
ec[len]='\0';
strcpy(b,eclosure(ec));
count=0;
for(j=0;j<=nos;j++)
{
if(strcmp(dstates[j],b)==0)
count++;
}
if(count==0)
{
if(b[0]!='\0')
{
nos++;
pushd(b);
strcpy(dstates[nos],b);
}
27
}
printf("\t%s",b);
}
printf("\n");
}
getch();
}
Output:
Result:
Thus, the C program to convert NFA to DFA has been executed and the output has been verified successfully
28
Date :
Ex.No. : 7.a
Left Recursion
Aim:
To write program to perform Left recursion.
Algorithm:
1. For each nonterminal :
a. Repeat until an iteration leaves the grammar unchanged:
b. For each rule , being a sequence of terminals and non terminals.
2. If begins with a nonterminal and :
a. Let be without its leading.
b. Remove the rule .
c. For each rule :
d. Add the rule .
3. Remove direct left recursion for as described above.
Program:
#include<stdio.h>
#include<string.h>
int main()
{ int i,j,n,k;
int lrec = 0;
char prod[100];
char newprod1[100]= "";
char newprod2[100]= "";
char alpha[100] = "";
char beta[100]= "";
char sts[20]="";
scanf("%s",prod);
sts[0] = prod[0]; // sts is Start Symbol
int size = (int)(strlen(prod));
for(i=0;i<size;i++) {
if(prod[i] == '|')
{ k = i; } }
if(prod[3] == prod[0]) //E->E+T
29
{ lrec = 1;
}
if(lrec == 1)
{
int c =0;
k = k-1;
for(i=4;i<=k;i++)
{
alpha[c] = prod[i];
c++;
}
c = 0;
for(i=k+2;i<size;i++)
{
beta[c] = prod[i];
c++;
}
strcat(newprod1,sts);//-,E //printf(strcat(newprod1,sts));
strcat(newprod1,"->");//->
strcat(newprod1,beta);//T
strcat(newprod1,sts);//E
strcat(newprod1,"'");//E'
strcat(newprod2,sts);//E
strcat(newprod2,"'");//E'
strcat(newprod2,"->");//->
strcat(newprod2,alpha);//+T
strcat(newprod2,sts);//E
strcat(newprod2,"'");//'
strcat(newprod2,"|e");//|e
printf("\n%s\n%s",newprod1,newprod2);//E->TE' }
}
30
Output:
Result:
Thus, the C program to remove Left recursion in the given grammar has been executed and the output has been
verified successfully
31
Date :
Ex.No. : 7.b
Left Factoring
Aim:
To write program to perform Left recursion.
Algorithm:
1. For each non terminal A find the longest prefix α common to two or more of its alternatives.
2. If α!= E,i. e., there is a non trivial common prefix, replace all the A productions.
3. A-> αβ1| αβ2|…………..| αβn| ɣ where ɣ represents all alternatives that do not begin with α by
4. A==> α A’| ɣ
5. A’==>β1|β2|………….|βn
6. Here A’ is new non terminal. Repeatedly apply this transformation until no two alternatives for a
non-terminal have a common prefix.
Program:
#include<stdio.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])
32
{
a3[k]=a1[i];
k++;
}
else
{
a4[l]=a1[i];
a5[l]=a2[i];
l++;
}
}
a3[k]='A';
a3[++k]='\0';
a4[l]='|';
a5[l]='\0';
a4[++l]='\0';
//printf("%s",a1);
//printf("\n99.%s",strcat(a4,a3));
printf("\n A->%s'",a3);
printf("\n A'->%s|\356",a5);
return 0;
}
Output:
Result:
Thus, the C program to generate left factored grammar has been executed and the output has been verified
successfully
33
Date :
Ex.No. :8
Computation of First and Follow Sets
Aim:
Algorithm:
1. Start
2. Check whether the first element of a non-terminal production is a terminal.
3. If true, add it to First(NT).
4. For Follow, check if the NT exists on RHS of any production.
If next symbol is
i. NT, then add First(NT) to Follow.
ii. T, add T to Follow.
iii. Nothing, then add Follow(source) to Follow.
Program:
#include<stdio.h>
#include<conio.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);
void main()
{
int i,z;
char c,ch;
clrscr();
printf("Enter the no of productions:\n");
scanf("%d",&n);
printf("Enter the productions:\n");
for(i=0;i<n;i++) scanf("%s
%c",a[i],&ch);
34
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," ");
flushall();
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);
getch();
}
void first(char c)
{
int k; if(!
isupper(c)) f[m+
+]=c;
for(k=0;k<n;k+
+)if(a[k][0]==c)
{
35
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:
36
Result:
Thus, the C program to compute First( ) and Follow( ) for the non-terminals of given CFG has been executed
and the output has been verified successfully
37
Date :
Ex.No. :9
Computation of LR(0)
Aim:
Algorithm
1. Start
2. Generate augmented grammar.
3. Start with C0 by including all marked productions [S->.α]
4. Compute the closure of item set C0
5. Perform a read operation on items in an item set.
6. Compute the closure of new item set.
7. Continue reading until all .S have travelled through all item sets
Program:
#include<iostream.h>
#include<conio.h>
#include<string.h>
char prod[20][20],listofvar[26]="ABCDEFGHIJKLMNOPQR";
int novar=1,i=0,j=0,k=0,n=0,m=0,arr[30];
int noitem=0;
struct Grammar
{ char lhs;
char rhs[8];
}g[20],item[20],clos[20][10];
int isvariable(char variable)
{ for(int i=0;i<novar;i++)
if(g[i].lhs==variable)
return i+1;
return 0;
} void findclosure(int z, char a)
38
{ int n=0,i=0,j=0,k=0,l=0;
for(i=0;i<arr[z];i++)
{
for(j=0;j<strlen(clos[z][i].rhs);j++)
{
if(clos[z][i].rhs[j]=='.' && clos[z][i].rhs[j+1]==a)
{
clos[noitem][n].lhs=clos[z][i].lhs;
strcpy(clos[noitem][n].rhs,clos[z][i].rhs);
char temp=clos[noitem][n].rhs[j];
clos[noitem][n].rhs[j]=clos[noitem][n].rhs[j+1];
clos[noitem][n].rhs[j+1]=temp;
n=n+1;
}}
}
for(i=0;i<n;i++)
{
for(j=0;j<strlen(clos[noitem][i].rhs);j++)
{
if(clos[noitem][i].rhs[j]=='.' && isvariable(clos[noitem][i].rhs[j+1])>0)
{
for(k=0;k<novar;k++)
{
if(clos[noitem][i].rhs[j+1]==clos[0][k].lhs)
{
for(l=0;l<n;l++)
if(clos[noitem][l].lhs==clos[0][k].lhs && strcmp(clos[noitem][l].rhs,clos[0][k].rhs)==0)
break;
39
if(l==n) { clos[noitem]
[n].lhs=clos[0][k].lhs;
strcpy(clos[noitem][n].rhs,clos[0][k].rhs);
n=n+1;
}
}}}}}
arr[noitem]=n;
int flag=0;
for(i=0;i<noitem;i++)
{
if(arr[i]==n)
{
for(j=0;j<arr[i];j++)
{ int c=0;
for(k=0;k<arr[i];k++)
if(clos[noitem][k].lhs==clos[i][k].lhs && strcmp(clos[noitem][k].rhs,clos[i][k].rhs)==0)
c=c+1;
if(c==arr[i])
{ flag=1;
goto exit;
}}
}}
exit:;
if(flag==0)
arr[noitem++]=n;
}
void main()
40
{ clrscr();
cout<<"ENTER THE PRODUCTIONS OF THE GRAMMAR(0 TO END) :\n";
do
{
cin>>prod[i++];
}while(strcmp(prod[i-1],"0")!=0);
for(n=0;n<i-1;n++)
{
m=0;
j=novar; g[novar+
+].lhs=prod[n][0];
for(k=3;k<strlen(prod[n]);k++)
{ if(prod[n][k] != '|')
g[j].rhs[m++]=prod[n][k];
if(prod[n][k]=='|')
{ g[j].rhs[m]='\0';
m=0;
j=novar; g[novar+
+].lhs=prod[n][0];
}
}}
for(i=0;i<26;i++) if(!
isvariable(listofvar[i]))
break;
g[0].lhs=listofvar[i];
char temp[2]={g[1].lhs,'\0'};
strcat(g[0].rhs,temp);
41
cout<<"\n\n augumented grammar \n";
for(i=0;i<novar;i++)
cout<<endl<<g[i].lhs<<"->"<<g[i].rhs<<" ";
getch();
for(i=0;i<novar;i++)
{
clos[noitem][i].lhs=g[i].lhs;
strcpy(clos[noitem][i].rhs,g[i].rhs);
if(strcmp(clos[noitem][i].rhs,"ε")==0)
strcpy(clos[noitem][i].rhs,".");
else
{ for(int j=strlen(clos[noitem][i].rhs)+1;j>=0;j--)
clos[noitem][i].rhs[j]=clos[noitem][i].rhs[j-1];
clos[noitem][i].rhs[0]='.';
}
}
arr[noitem++]=novar;
for(int z=0;z<noitem;z++)
{ char list[10];
int l=0;
for(j=0;j<arr[z];j++)
{
for(k=0;k<strlen(clos[z][j].rhs)-1;k++)
{
if(clos[z][j].rhs[k]=='.')
{
for(m=0;m<l;m++)
42
if(list[m]==clos[z][j].rhs[k+1])
break;
if(m==l) list[l++]=clos[z]
[j].rhs[k+1];
}
}}
for(int x=0;x<l;x++)
findclosure(z,list[x]);
}
cout<<"\n THE SET OF ITEMS ARE \n\n";
for(z=0;z<noitem;z++)
{ cout<<"\n I"<<z<<"\n\n";
for(j=0;j<arr[z];j++)
cout<<clos[z][j].lhs<<"->"<<clos[z][j].rhs<<"\n";
getch();
}
getch();
}
43
Output:
44
Result:
Thus, the C program to generate LR(0) items has been executed and the output has been verified successfully
Date :
Ex.No. :10
Intermediate Code Generation- Three Address Codes
45
Aim:
To write a C Program to generate a three address code.
Algorithm:
1. Initially check the choice of the user
2. Assignment shows how it is assigned in three address code
3. Arithmetic shows how it solves in three address code
4. Relational shows how it proves the relations in three address code
5. Stop the program by exit
Code:
#include"stdio.h"
#include"conio.h"
#include"string.h"
#include"process.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()
{
printf("Enter the Expression :- ");
scanf("%s",str);
printf("The Intermediate code:-\t\tExpression\n");
findopr();
explore();
getch();
}
46
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='-';
}
}
47
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]!=':')
48
{
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++;
}
}
49
OUTPUT:
RESULT:
Thus, the C program to generate 3-address code for the give expression has been executed and the output has
been verified successfully
Date :
Ex.No. : 11
Intermediate Code Generation- Prefix, Postfix
Aim:
Algorithm:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
i. If the precedence of the scanned operator is greater than the precedence of the operator in the
stack(or the stack is empty), push it.
ii. Else, Pop the operator from the stack until the precedence of the scanned operator is less-
equal to the precedence of the operator residing on the top of the stack. Push the scanned
operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty. Output is postfix expression.
50
8. Reverse the infix string.
9. Apply infix to postfix operations.
10. Reversed output string is prefix expression.
Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
int pop();
int precedence(char symbol);
int isEmpty();
void infix_to_prefix();
void infix_to_postfix();
int checker(char symbol);
void push(long int symbol);
51
char prefix_string[20], infix_string[20], postfix_string[20];
int top;
long int stack[20];
int main()
{
int i, length;
char temp;
top = -1;
clrscr();
printf("\nEnter an Expression in Infix format:\t");
scanf("%[^\n]s", infix_string);
infix_to_postfix();
printf("\nExpression in Postfix Format: \t%s\n", postfix_string);
strrev(infix_string);
infix_to_prefix();
strrev(postfix_string);
strcpy(prefix_string,postfix_string);
length=strlen(prefix_string);
printf("\nExpression in Prefix Format: \t");
for(i=0;i<length;i++)
if(prefix_string[i]!='(' && prefix_string[i]!=')')
printf("%c",prefix_string[i]);
getch();
return 0;
}
52
void infix_to_postfix()
{
unsigned int count, temp = 0;
char next;
char symbol;
for(count = 0; count < strlen(infix_string); count++)
{ symbol = infix_string[count];
if(!checker(symbol))
switch(symbol)
{
case '(': push(symbol);
break;
case ')':
while((next = pop()) != '(')
postfix_string[temp++] = next;
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
while(!isEmpty() && precedence(stack[top]) >= precedence(symbol))
postfix_string[temp++] = pop();
push(symbol);
break;
default:
53
postfix_string[temp++] = symbol;
}}
while(!isEmpty())
postfix_string[temp++] = pop();
postfix_string[temp] = '\0';
}
void infix_to_prefix()
{ unsigned int count, temp = 0;
char next;
char symbol;
for(count = 0; count < strlen(infix_string); count++)
{ symbol = infix_string[count];
if(!checker(symbol))
switch(symbol)
{
case ')': push(symbol);
break;
case '()':
while((next = pop()) != ')')
postfix_string[temp++] = next;
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
54
while(!isEmpty() && precedence(stack[top]) >= precedence(symbol))
postfix_string[temp++] = pop();
push(symbol);
break;
default:
postfix_string[temp++] = symbol;
}}
while(!isEmpty())
postfix_string[temp++] = pop();
postfix_string[temp] = '\0';
}
int precedence(char symbol)
{ switch(symbol)
{
case '(': return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default:
return 0;
}}
55
int checker(char symbol)
{ if(symbol == '\t' || symbol == ' ')
return 1;
return 0;
}
void push(long int symbol)
{ if(top > 20)
{
printf("Stack Overflow\n");
exit(1);
}
top = top + 1;
stack[top] = symbol;
}
int isEmpty()
{ if(top == -1)
return 1;
return 0;
}
int pop()
{ if(isEmpty())
{
printf("Stack is Empty\n");
exit(1);
}
return(stack[top--]);
}
56
Output:
Result:
Thus, the C program to convert the given infix to prefix and postfix expression has been executed and the
output has been verified successfully
57
Date : SIMPLE CODE GENERATOR
Ex.No. :12
Aim:
To write a program to generate a simple code.
Algorithm:
#include<iostream> using
namespace std;
#include<string.h>
#include<conio.h>
char reg[10][3]={"R0","R1","R2","R3","R4","R5"};
char stmt[10][10],code[15]; int
nostmt=0,i=0,output[15];
void icode(char source[10],char dest[10],int out)
{
strcat(code,source);
strcat(code," ");
strcat(code,dest);
output[i]=out;
cout<<code<<endl;
getch();
}
int main()
{
//clrscr();
int j,i;
cout<<" Enter the statements(END to end): \n";
do
58
{
cin>>stmt[nostmt++];
}while(strcmp(stmt[nostmt-1],"END")!=0);
nostmt=nostmt-1;
cout<<"\n THE INTERMEDIATE CODE IS\n\n";
for(i=0;i<nostmt;i++)
{
strcpy(code,"");
int rd=-1,rs=-1,k;
for(j=0;j<i;j++)
{
if(stmt[j][0]==stmt[i][2])
rs=output[j]; if(stmt[j]
[0]==stmt[1][4])
rd=output[j];
}
if(rs==-1)
{
strcpy(code,"MOV ");
char temp[2]={stmt[i][2],'\0'};
icode(temp,reg[i],i);
}
if(stmt[i][3]=='+')
strcpy(code,"ADD ");
if(stmt[i][3]=='-')
strcpy(code,"SUB ");
if(stmt[i][3]=='*')
strcpy(code,"MUL ");
if(stmt[i][3]=='/')
strcpy(code,"DIV ");
if(rd==-1) {
char temp[2]={stmt[i][4],'\
0'}; if(rs!=-1)
k=output[rs];
else
k=i;
icode(temp,reg[k],k); }
if(rs!=-1 && rd!=-1) {
int flag=0;
for(j=i;j<nostmt;j++)
if(stmt[j][2]==stmt[i][2] || stmt[j][2]==stmt[i]
[4]) flag=1;
if(flag!=1)
icode(reg[output[rs]],reg[output[rd]],output[rd]);
if(flag==1)
59
icode(reg[output[rd]],reg[output[rs]],output[rs]);
}
}
strcpy(code,"MOV ");
char temp[2]={stmt[i-1][0],'\0'};
icode(reg[output[i-1]],temp,0);
}
OUTPUT:
Result:
Thus, the C program to generate assembly code for the given three address code has been
executed and the output has been verified successfully
60
Date :
Ex.No. : 13 IMPLEMENTATION OF DAG
Aim:
To write a C Program to generate a Directed Acyclic Graph
Algorithm:
3. Create interior nodes with an operator symbol and pointers to left and right operands.
2. Create a list of attached identifiers for each node to hold the computed values.
Case (i) x : = y OP z
Case (ii) x : = OP y
Case (iii) x : = y
3. For the case(i), create a node(OP) whose left child is node(y) and right child isnode(z).
3. Delete x from the list of identifiers for node(x). Append x to the list of
attached identifiers for the node n found in step 3 and set node(x) to n.
61
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))*/
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++)
62
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
63
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
Result:
Thus, the C program to construct DAG has been executed and the output has been verified successfully
64
Date : IMPLEMENTATION OF GLOBAL DATA FLOW ANALYSIS
Ex.No. :14
Aim:
To write a C program to Implement Data Flow Analysis
Algorithm:
Program:
# include <stdio.h>
# include <conio.h>
# include<string.h>
struct op {
char left[10]; char
right[10];
}op2[15],prt[15];
int main(){
int a,j,i,k,n,m,q,l=1;char *p,*li; char
temp,t;
char *tem,*mat; printf("enter
no.of.values"); scanf("%d",&n);
for(i=0;i<n;i++){ printf("left");
scanf("%s",op2[i].left);
printf("right");
scanf("%s",op2[i].right);}
printf("intermediate code"); for
(i=0;i<n;i++)
65
{printf("Lineno=%d\n",l);
printf("%s=",op2[i].left);
printf("%s\n",op2[i].right); l++;}
printf("dataflow analysis");
for(i=0;i<n;i++)
{for(j=0;j<n;j++)
{mat=strstr(op2[j].right,op2[i].left);if (mat)
{printf("\n%s is live at %s\n",op2[i].left,op2[j].right);}}} return 0;}
Output:
Result:
Thus, the C program to perform global data flow analysis has been executed and the output has been
verified successfully
66
Date : IMPLEMENTATION OF STORAGE ALLOCATION -
Ex.No. :15.a STACK
Aim:
Program:
#include<stdio.h>
#include<conio.h>
int i, stk[100], top=-1, n;
void show()
{
for(i=0;i<=top;i++)
printf("%d\t",stk[i]);
}
void push()
{
int item;
if(top == n-1)
printf("\nStack is
full."); else { 67
printf("\nEnter the item:
"); scanf("%d",&item);
stk[++top]=item; }}
void pop(){
if(top==-1)
printf("Stack is empty.");
else {
printf("%d is popped.",stk[top]);
top--; }}
int main(){
int i,op;
printf("Enter the size of the stack: "); scanf("%d",&n);
do
{
printf("\n1 : Push");
printf("\n2 : Pop");
printf("\n3 : Display");
printf("\n4 : Exit");
printf("\nEnter your choice: ");
scanf("%d",&op);
switch(op)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
show();
break;
}
68
}while(op!=4);
getch();
}
Output:
Result:
Thus, the C program to implement storage allocate using stack has been executed and the output has
been verified successfully
69
Date : IMPLEMENTATION OF STORAGE ALLOCATION - HEAP
Ex.No. :15.b
Aim:
Program :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct Heap
{ int data;
struct Heap *next;
}node;
node *create(); void
main()
{ /*local declarations*/ int
choice,val;
char ans; node
*head;
void display(node *); node
*search(node *,int); node
70
*insert(node *); void
dele(node **); head=NULL;
do
{
printf("\n Various operations on Heap");
printf("\n1.Create"); printf("\n2.Display");
printf("\n3.Insert an element in a list");
printf("\n4.Delete an element from list");
printf("\n5.Quit");
printf("\n Enter Your Choice(1-5): ");
scanf("%d",&choice);
switch(choice)
{ case 1:head=create();
break;
case 2:display(head);
break;
case 3:head=insert(head);
break;
case 4:dele(&head);
break;
case 5:exit(0);
default:
printf("Invalid Choice,Try again");
getch();
}}
while(choice!=5);}
node *create(){
node *temp,*new1,*head; int
val,flag;
char ans='y';
node *get_node();
temp=NULL;
71
flag=TRUE;
do{
printf("\n Enter the Element: ");
scanf("%d",&val);
new1=get_node(); if(new1==NULL)
printf("\n Memory is not allocated");
new1-> data=val;
if (flag==TRUE)/* Executed only for the first time*/{
head=new1;
temp=head; /*head is the first node in the heap*/
flag=FALSE;
} else
{ temp->next=new1;
temp=new1;}
printf("\nDo you want to enter more elements?(y/n)");
ans=getch();
}while(ans=='y'); printf("\nThe list
is created"); getch();
return head;}
node *get_node(){ node
*temp;
temp=(node*)malloc(sizeof(node));
temp->next=NULL;
return temp;}
void display(node*head){ node
*temp;
temp=head;
if(temp==NULL){
printf("\n The list is empty\n");
getch();
return;}
while(temp!= NULL){
72
printf("%d->",temp-> data);
temp=temp->next;}
printf("NULL");
getch();}
node *search(node *head,int key){ node
*temp;
int found;
temp=head;
if (temp==NULL){
printf("The linked list is empty\n");
getch();
return NULL;}
found=FALSE;
while((temp!=NULL)&&(found==FALSE))
{ if(temp->data != key)
temp = temp->next; else
found = TRUE;
} if(found == TRUE){
printf("\n The Elements is present in the list\n");
getch();
return temp;
} else
printf("\n The Element is not present in the list\n");
getch();
return NULL;}
node *insert(node *head)
{ int choice;
node *insert_head(node*); void
insert_after(node*); void
insert_last(node*);
printf("\n1. Insert a node as a head node");
printf("\n2. Insert a node as a last node");
73
printf("\nEnter your choice for insertion of node (1-2): ");
scanf("%d",&choice);
switch(choice)
{ case 1:head =
insert_head(head);
break;
case 2:insert_last(head);
break;}
return head;
} /*Insertion of node at first position*/
node *insert_head(node*head){
node *New,*temp;
New = get_node();
printf ("\n Enter the element which you want to insert: ");
scanf("%d",&New->data);
if(head == NULL) head
= New;
else
{ temp=head;
New->next = temp;
head= New;
}
return head;
} /*Insertion of node at last position*/ void
insert_last(node *head) {
node *New,*temp;
New = get_node();
printf ("\n Enter the element which you want to insert: ");
scanf("%d",&New->data);
if(head == NULL){ head
= New;
} else
74
{ temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->next=New;
New->next=NULL; }}
node *get_prev(node *head,int val){ node
*temp,*prev;
int flag; temp =
head;
if(temp == NULL)
return NULL;
flag = FALSE; prev
= NULL;
while(temp!=NULL && !flag)
{ if(temp->data!=val) { prev
= temp;
temp = temp->next;
} else
flag = TRUE;
} if(flag) /*if Flag is true*/
return prev;
else
return NULL;}
void dele(node **head)
{ int key;
node *New,*temp, *prev;
temp=*head;
if (temp== NULL){
printf ("\n The list is empty\n ");
getch();
return;}
printf("\nENTER the Element you want to delete: ");
75
scanf("%d",&key);
temp= search(*head,key);
if(temp !=NULL) {
prev = get_prev(*head,key);
if(prev != NULL) {
prev ->next = temp-> next;
free(temp);
} else{
*head = temp->next;
free(temp); // using the mem. Dellocation function
}
printf("\nThe Element is deleted\n");
getch();
}}
Output:
76
Result:
Thus, the C program to implement storage allocate using heap has been executed and the output has been
verified successfully
77