104337811.

doc

By K. Ravi Chythanya

OS and CD Lab Manual
Objective:
To provide an understanding of the design aspects of operating system. To provide an efficient understanding of the language translation peculiarities by designing a complete translator for a mini language.

Recommended Systems/Software Requirements:
• • Intel based desktop PC with minimum of 166 MHZ or faster processor with at least 64 MB RAM and 100 MB free disk space Turbo C or TC3 complier in Windows XP or Linux Operating System.

Developed By: K. Ravi Chythanya

1

104337811.doc

By K. Ravi Chythanya

Table of Contents

S. No 1)

Program’s Name

Page No

Part A
Simulate the following CPU Scheduling Algorithms a) FCFS b) SJF c) Priority d) Round Robin Simulate MVT and MFT Simulate Bankers algorithm for Deadlock Avoidance Simulate Bankers Algorithm for deadlock Prevention Simulate all Page Replacement Algorithms a) FIFO b) LRU c) Optimal Simulate Paging Technique of Memory Management 4 6 8 10 12 16 19 22 24 26 28 31 33 36 41 43 50

2) 3) 4) 5)

6) 7) 8) 9) 10) 11) 12)

Part B
Design a lexical analyzer for given language .the lexical analyzer should ignore redundant spaces, tabs and new lines. Implement the lexical analyzer using JLex, flex or other lexical analyzer generating tools. Design predictive parser for the given language Design a LALR bottom up parser for the given language Convert the BNF rules into Yacc form and write code to generate abstract syntax tree. A program to generate machine code

2

104337811.doc

By K. Ravi Chythanya

PART A

3

104337811.doc

By K. Ravi Chythanya

1) Simulate the following CPU scheduling algorithms a) FCFS b) SJF c) Priority d) Round Robin a) FCFS: AIM: A program to simulate the FCFS CPU scheduling algorithm
PROGRAM:
#include<stdio.h> #include<conio.h> void main() { char pn[10][10]; int arr[10],bur[10],star[10],finish[10],tat[10],wt[10],i,n; int totwt=0,tottat=0; clrscr(); printf("Enter the number of processes:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the Process Name, Arrival Time & Burst Time:"); scanf("%s%d%d",&pn[i],&arr[i],&bur[i]); } for(i=0;i<n;i++) { if(i==0) { star[i]=arr[i]; wt[i]=star[i]-arr[i]; finish[i]=star[i]+bur[i]; tat[i]=finish[i]-arr[i]; } else { star[i]=finish[i-1]; wt[i]=star[i]-arr[i]; finish[i]=star[i]+bur[i]; tat[i]=finish[i]-arr[i]; } } printf("\nPName Arrtime Burtime Start TAT Finish"); 4

104337811.doc

By K. Ravi Chythanya

for(i=0;i<n;i++) { printf("\n%s\t%6d\t\t%6d\t%6d\t%6d\t%6d",pn[i],arr[i],bur[i],star[i],tat[i],finish[i]); totwt+=wt[i]; tottat+=tat[i]; } printf("\nAverage Waiting time:%f",(float)totwt/n); printf("\nAverage Turn Around Time:%f",(float)tottat/n); getch(); }

OUTPUT:
Input: Enter the number of processes: 3 Enter the Process Name, Arrival Time & Burst Time: 1 2 3 Enter the Process Name, Arrival Time & Burst Time: 2 5 6 Enter the Process Name, Arrival Time & Burst Time: 3 6 7 Output: PName Arrtime Burtime Srart TAT Finish 1 2 3 2 3 5 2 5 6 5 6 4 3 6 7 6 7 10 Average Waiting Time: 3.333 Average Turn Around Time: 7.000

5

int totwt=0. else st[i]=ft[i-1]. at[i]=at[j]. flushall().&et[i]).j<n.totta=0.i++) { if(i==0) st[i]=at[i].&n).i.pn[j]).pn[i]).i<n.doc By K.j++) { if(et[i]<et[j]) { temp=at[i]. } } for(i=0. printf("Enter the number of process:").ata. strcpy(pn[i].i++) { printf("Enter process name.ft[10]. strcpy(pn[j].h> void main() { int et[20].j.h> #include<conio.temp. char pn[10][10]. scanf("%s%d%d". clrscr().st[10]. strcpy(t.i<n. et[i]=et[j].pn[i]. arrival time & execution time:"). for(i=0.h> #include<string. } for(i=0.t). et[j]=temp.at[10]. float awt.n. Ravi Chythanya b) SJF: AIM: A program to simulate the SJF CPU scheduling algorithm PROGRAM: #include<stdio.i++) for(j=0.ta[10].wt[10]. 6 .104337811.t[10].i<n. at[j]=temp.&at[i]. scanf("%d". temp=et[i].

3333 7 .wt[i]. for(i=0. printf("\nAverage waiting time is:%f". ata=(float)totta/n. ta[i]=ft[i]-at[i].i++) printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d".doc By K. } OUTPUT: Input: Enter the number of processes: 3 Enter the Process Name. Arrival Time & Burst Time: 3 6 11 Output: Pname arrivaltime executiontime waitingtime tatime 1 4 6 0 6 3 6 11 4 15 2 5 15 16 31 Average Waiting Time: 6.ta[i]). printf("\nAverage turnaroundtime is:%f". totwt+=wt[i].at[i]. getch(). } awt=(float)totwt/n.i<n.pn[i]. Arrival Time & Burst Time: 2 5 15 Enter the Process Name.ata). ft[i]=st[i]+et[i].6667 Average Turn Around Time: 17. printf("\nPname\tarrivaltime\texecutiontime\twaitingtime\ttatime").et[i]. Ravi Chythanya wt[i]=st[i]-at[i].awt).104337811. Arrival Time & Burst Time: 1 4 6 Enter the Process Name. totta+=ta[i].

i<n.h> #include<string.wt[10].at[10].i<n. at[j]=temp.execution time & priority:"). printf("Enter the number of process:").totta=0. scanf("%s%d%d%d".i++) { 8 . temp=at[i]. } } for(i=0.i. et[j]=temp.t[10]. at[i]=at[j].n.h> #include<conio.j++) { if(p[i]<p[j]) { temp=p[i].ata.ta[10]. p[i]=p[j]. strcpy(t.pn[j]). temp=et[i]. scanf("%d".pn[i]).pn[i]. p[j]=temp. strcpy(pn[j].temp. flushall().i<n.st[10].i++) { printf("Enter process name.&at[i].j.arrivaltime. for(i=0.ft[10].&n).&p[i]).j<n.doc By K. } for(i=0. strcpy(pn[i]. Ravi Chythanya c) Priority: AIM: A program to simulate the priority CPU scheduling algorithm PROGRAM: #include<stdio.i++) for(j=0.p[10]. char pn[10][10]. float awt.104337811.&et[i]. et[i]=et[j].h> void main() { int et[20]. clrscr().t). int totwt=0.

et[i].p[i]. printf("\nAverage turnaroundtime is:%f". getch().104337811.at[i]. execution time & priority: 2 4 5 2 Enter the Process Name. Arrival Time. Arrival Time. execution time & priority: 3 5 6 3 Output: Pname arrivaltime executiontime priority waitingtime 1 2 3 1 0 2 4 5 2 1 3 5 6 3 5 Average Waiting Time: 2. printf("\nPname\tarrivaltime\texecutiontime\tpriority\twaitingtime\ttatime"). for(i=0. printf("\nAverage waiting time is:%f". } totwt+=wt[i]. ta[i]=ft[i]-at[i]. execution time & priority: 1 2 3 1 Enter the Process Name.pn[i]. } awt=(float)totwt/n. ata=(float)totta/n. wt[i]=st[i]-at[i]. totta+=ta[i].awt).0000 Average Turn Around Time: 6.i<n. } else { st[i]=ft[i-1]. ta[i]=ft[i]-at[i].ata). ft[i]=st[i]+et[i].wt[i]. Arrival Time. ft[i]=st[i]+et[i]. } OUTPUT: Input: Enter the number of processes: 3 Enter the Process Name. Ravi Chythanya if(i==0) { st[i]=at[i].doc By K.i++) printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d\t\t%5d".6667 tatime 3 6 11 9 .ta[i]). wt[i]=st[i]-at[i].

et[i]=0.x=0.i++) { if(et[i]>ts) { x=x+ts. while(x!=tot) { for(i=0.&n).et[i]).i<n.doc By K. char pn[10][10]. for(i=0.i++) tot=tot+et[i].pn[i]).h> void main() { int et[30]. scanf("%s %d". printf("\n %s -> %d".pn[i]. } printf("The processes are:"). Ravi Chythanya d) Round Robin: AIM: A program to simulate the Round Robin CPU scheduling algorithm PROGRAM: #include<stdio.} } 10 . for(i=0.104337811.pn[i]. clrscr().i<n.i+1. printf("Enter the no of processes:"). et[i]=et[i]-ts.i<n.n.pn[i].i<n.i++) { printf("enter process name & estimated time:"). printf("\n %s -> %d". scanf("%d". for(i=0.h> #include<conio.ts).i. } else if((et[i]<=ts)&&et[i]!=0) { x=x+et[i]. scanf("%d".&et[i]). printf("Enter the time quantum:").&ts).i++) printf("process %d: %s\n".ts.tot=0.

getch(). Ravi Chythanya OUTPUT: Input: Enter the no of processes: 2 Enter the time quantum: 3 Enter the process name & estimated time: p1 12 Enter the process name & estimated time: p2 15 Output: p1 -> 3 p2 -> 3 p1 -> 3 p2 -> 3 p1 -> 3 p2 -> 3 p1 -> 3 p2 -> 3 p2 -> 3 Total Estimated Time: 27 11 .x). } By K.doc } printf("\n Total Estimated Time:%d".104337811.

count=0. clrscr().i++) { printf("\nenter memory req for process%d: ".m).m2).i+1). scanf("%d".h> void main() { int m=0. } printf("\nexternal fragmentation for this process is:%d". PROGRAM: #include<stdio. m2=m-m1. MVT: AIM: A program to simulate the MVT.doc By K.i+1.i. scanf("%d". if(m1<=m) { if(count==m) { printf("there is no further memory remaining:"). } else { printf("the memory allocated for process%d is: %d ".&m1).&m). } getch(). Ravi Chythanya 2) Simulate the MVT and MFT.&p). } } else { printf("memory is not allocated for process%d".m2=0. } 12 .104337811.i+1).m2). printf("\nremaining memory is: %d". count=count+m1. for(i=0.m1=0. scanf("%d". printf("enter the memory capacity:"). printf("enter the no of processes:").p. m=m2.h> #include<conio.i<p.

104337811.doc By K. Ravi Chythanya OUTPUT: 13 .

i+1). scanf("%d". } else { printf("\nProcess not allocated in partition%d". scanf("%d".&p1).i+1). scanf("%d".doc By K.fra1).i<p1. printf("Enter the memory size:").s.h> #include<conio. } 14 .i<p1.&p).p1.&m).i++) { printf("\nEnter the memory req for process%d:".i++) printf("\n%5d\t%5d\t%5d".i+1). } } printf("\nProcess\tmemory\tallocatedmemory"). f1=f1+fra1.f2=0. printf("\nEnter the no of processes:"). Ravi Chythanya MFT: AIM: A Program to simulate the MFT PROGRAM: #include<stdio. if(m1[i]<=s) { printf("\nProcess is allocated in partition%d".i.f). fra2=s.&m1[i]). printf("\nExternal fragmentation for partition is:%d". for(i=0. printf("Enter the no of partitions:").104337811.fra2). f2=f2+fra2. for(i=0. printf("Each partn size is:%d".fra1.f1=0. printf("\nThe tot no of fragmentation is:%d".f.s.s). fra1=s-m1[i]. printf("\nInternal fragmentation for process is:%d". s=m/p.h> void main() { int m. clrscr(). getch(). scanf("%d".m1[i]).p. int m1[4].fra2. f=f1+f2.i+1.

104337811. Ravi Chythanya OUTPUT: 15 .doc By K.

} } block[p]=0.104337811.k<=r. for(i=1.totext[10].&newreq[k]). printf("Enter the process making the new request:").resalloc[10][10]. printf("Enter the total existed resource in each class:").&r). printf("Enter the process which are n blocked or running:"). for(k=1. scanf("%d%d".s=0.run[10]. AIM: A program to simulate the Bankers Algorithm for Deadlock Avoidance.resreq[10][10]. int totalloc[10].&resalloc).k++) scanf("%d". printf("Enter the requested resource:").i<=n.i+1).p.k++) scanf("%d".i++) { if(i!=p) { printf("process %d:\n". #include<stdio. int block[10].k<=r. scanf("%d". printf("Enter the no of processes:").i<=n.h> #include<conio. run[p]=0. for(k=1.i.i++) for(k=1. scanf("%d".u=0.doc By K.&totext[k]).r.j.k++) { 16 . scanf("%d".m.&block[i].active[10].&p).k. Ravi Chythanya 3) Simulate Bankers Algorithm for Deadlock Avoidance. for(i=1. int max[10][10].newreq[10]. printf("Enter the allocated resources:").h> void main() { int n.k<=r. PROGRAM: //Bankers algorithm for deadlock avoidance.k<=r. for(k=1.simalloc[10].k++) scanf("%d". clrscr().&n).&run[i]). printf("Enter the no of resource classes:").

k<=r. for(s=1. } } for(i=1. totalloc[k]+=newreq[k].s++) for(i=1.k<=r.k++) { if((totext[k]-simalloc[k])<(max[i][k]-resalloc[i][k])) { j=1.i++) { if(active[i]==1) { j=0.i++) { if(block[i]==1||run[i]==1) active[i]=1.k<=r.s<=n. for(i=1. else active[i]=0. } } if(u==0) { for(k=1. } for(k=1.k++) { if(totext[k]-totalloc[k]<0) { u=1.break. } for(k=1.104337811.i<=n.break. for(k=1.k++) { resalloc[p][k]+=newreq[k].i<=n.k<=r.k++) simalloc[k]=totalloc[k].i<=n. } } } if(j==0) { By K.doc j=0.i++) { totalloc[k]=j+resalloc[i][k]. j=totalloc[k]. Ravi Chythanya 17 .

totalloc[k]=newreq[k].k<=r.k++) { resalloc[p][k]=newreq[k]. Ravi Chythanya OUTPUT: 18 .k<=r. } } m=0.104337811. for(k=1.k++) simalloc[k]=resalloc[i][k].k<=r. for(k=1. } getch().doc active[i]=0. } By K. printf("Deadlock willn't occur"). } printf("Deadlock will occur"). } else { for(k=1.k++) resreq[p][k]=newreq[k].

j++) { scanf("%d". PROGRAM: #include<stdio.i<m.i<3. AIM: A program to simulate Bankers Algorithm for Deadlock Prevention.i++) 19 .j++) { ne[i][j]=cl[i][j]-al[i][j]. printf("\t%d".i. } printf("\nEnter avaliable matrix").i++) { for(j=0.av[10]. clrscr().j.104337811.i++) { for(j=0. scanf("%d %d". for(i=0. for(i=0.h> void main() { int cl[10][10].j++) { scanf("%d".c.i<m.av[i]).i<m.j<n.m.doc By K.&al[i][j]). for(i=0.ne[10][10]. printf("\nEnter the matrix").&n). } printf("\n").i<m.&cl[i][j]).k.&m. for(i=0. printf("Claim matrix:\n").al[10][10].n.flag=0. } } printf("\nEnter allocated matrix").i++) scanf("%d".j<n. Ravi Chythanya 4) Simulate Bankers Algorithm for Deadlock Prevention. for(i=0.i++) { for(j=0.h> #include<conio. printf("\nEnter the claim matrix"). } } printf("\nThe need matrix").j<n.ne[i][j]).

for(i=0.i<m.j<n. } if(flag==1) { flag=0. for(i=0.i++) { printf("\t%d". } for(k=0. } printf("\n").j++) { printf("\t%d". } } a: if(flag==0) { printf("unsafestate").j<n.j++) { printf("\t%d". if(flag==1&& j==n-1) goto a.k<m.i++) { for(j=0.i<m.al[i][j]). Ravi Chythanya 20 .k++) for(i=0.av[i]).i<3.i++) { av[j]+=al[i][j].i<m.i++) { for(j=0. } printf("\n allocated matrix:\n"). } printf("\n").cl[i][j]). } printf(" available matrix:\n").j<n.i++) { for(j=0. By K.j<n. for(i=0.j++) { if(av[j]>=ne[i][j]) flag=1.104337811. else break.doc { for(j=0.

Ravi Chythanya OUTPUT: 21 . for(i=0. } getch().104337811. } By K.i++) printf("\t available matrix:%d".i<n. } } printf("\n safe state").doc al[i][j]=1.av[i]).

i<12.h. } p=0. clrscr(). printf("Enter numbers:"). for(i=0.a[h]).doc By K. } } printf("\n%d".h> void main() { int a[5].h> #include<conio.q1=1. a[q]=b[i].u. if((p==0)&&(q1==3)) { printf("-->%c". m++.p=0.k.j.104337811.f).h<q1.b[i]).i++) {if(p==0) { if(q>=3) q=0.i++) scanf("%d". for(h=0.i<12.b[20]. for(i=0. if(q1<3) { q1=q. Ravi Chythanya 5) Simulate all Page Replacement Algorithms a) FIFO b) LRU c) Optimal a) FIFO: AIM: A program to simulate FIFO Page Replacement Algorithm PROGRAM: #include<stdio. q++.i. char f='F'.m=0.k++) { 22 .q=0.h++) printf("%d".&b[i]). printf("\t").k<q-1. for(k=0.

doc if(b[i+1]==a[k]) p=1.m).104337811. Ravi Chythanya OUTPUT: 23 . } } printf("\nNo of faults:%d". } By K. getch().

printf("\t").a[5]. for(h=0.h> #include<conio. for(i=0.a[h]).k++) { if(b[i+1]==a[k]) p=1. q++. } } printf("\n%d".b[20].f).u.i<12. char f='F'.h<q1.i++) {if(p==0) { if(q>=3) q=0.h++) printf("%d". if(q1<3) { q1=q. g=1. clrscr(). a[q]=b[i].i++) scanf("%d".i<12.k<q-1. if((p==0)&&(q1==3)&&(g!=1)) { printf("-->%c".i.j. printf("Enter no:").q=0. Ravi Chythanya b) LRU: AIM: A program to simulate LRU Page Replacement Algorithm PROGRAM: #include<stdio. for(i=0.b[i]).h. } p=0.k. m++.p=0.&b[i]). 24 .m=0. g=0.q1=1. if(q1==3) { for(k=0.h> void main() { int g=0.104337811.doc By K.

k<q. getch().m). Ravi Chythanya OUTPUT: 25 .j++) { u=0. k=i.doc } for(j=0. k--.j<q1. } By K.k++) { if(b[i+1]==a[k]) p=1. } } } printf("\nNo of faults:%d".104337811. } if(u==0) q=j. } } else { for(k=0. while(k>(i-2)&&(k>=0)) { if(b[k]==a[j]) u++.

m1[3]. j++.104337811. 26 .j.&pn[i]).m[3]={0.doc By K.f.i<3. Ravi Chythanya c) Optimal: AIM: A program to simulate Optimal Page Replacement Algorithm. for(i=0.h> #include<conio. PROGRAM: #include<stdio. j=0.for(k=0.k++) { if(m[k]==pn[j]) { flag=1. clrscr().i. for(i=0. } if(flag==0) { m[j]=pn[j].0.i<12. flag=1. } } for(i=j.pf=0.i++) scanf("%d".i<12.k<3.h> void main() { int pn[12].i++) { while(j<12) { flag=0.i++) { flag=0. } if(flag==1) break. int flag. } j++.0}.z. printf("enter pgs:"). if(flag==1) break.k. i--.

j++) { if(pn[i]==m[j]) flag=1. for(k=i+1. for(j=0. m1[1]=m1[2]=0.j++) { if(pn[z]==m[j]) { m[j]=pn[i].k++) { if(m[j]==pn[k]) { m1[j]=k. if(flag==0) { m1[0]=0.k<12. } } } } } printf("no of faults:%d".j<3.104337811.pf).j++) {f=0. pf++.doc By K. } if(f==1) break. } } z=(m1[0]>m1[1]||(m1[0]>m1[2])?m1[0]:m1[2])&&(m1[1]>m1[2]?m1[1]:m1[2]). } OUTPUT: 27 .j<3. getch(). f=1. for(j=0.j<3. Ravi Chythanya for(j=0.

sa[i]). printf("page%d\t address %u\n".h> #include<conio.i<np. PROGRAM: #include<stdio. sa=(int*)malloc(2*np). } OUTPUT: 28 .&ps). } getch(). int *sa.i+1. scanf("%d".104337811. AIM: A program to simulate Paging technique of memory management.i.&np). Ravi Chythanya 6) Simulate Paging technique of Memory Management. printf("enter the page size \n"). scanf("%d".i++) { sa[i]=(int)malloc(ps). clrscr().doc By K. printf("enter how many pages\n").h> main() { int np. for(i=0.ps.

Ravi Chythanya PART B 29 .doc By K.104337811.

str)==0|| strcmp("case".str)==0||strcmp("static". f1=fopen("input". fclose(f1).i=0. Ravi Chythanya 7) Write a program to design lexical analyzer.str)==0||strcmp("while". char c.j=0. else printf("\n%s is an identifier"./*gets(st1). while((c=getc(f1))!=EOF) { if(isdigit(c)) { tokenvalue=c-'0'. c=getc(f1)."w").h> #include<stdio.k=0.tokenvalue=0. } main() { FILE *f1.f1).str)==0||strcmp("float".str)==0|| strcmp("double".104337811.*/ f1=fopen("input".doc By K.h> void keyword(char str[10]) { if(strcmp("for".*f3.str). c=getc(f1).st1[10]. ungetc(c.lineno=0.f1).str)==0|| strcmp("int".str[10]. while(isdigit(c)) { tokenvalue*=10+c-'0'."w"). AIM: A program to design Lexical Analyzer.str).str)==0||strcmp("switch". while((c=getchar())!=EOF) putc(c. int num[100]. PROGRAM: #include<string.str)==0||strcmp("do".*f2."w").str)==0) printf("\n%s is a keyword". } num[i++]=tokenvalue.str)==0||strcmp("char". f3=fopen("specialchar". printf("\nEnter the c program")."r"). } else if(isalpha(c)) 30 . f2=fopen("identifier".h> #include<ctype.

printf("\nThe no's in the program are").f2). printf("\nSpecial characters are"). } } fclose(f2). keyword(str).f3). By K. f2=fopen("identifier". printf("\n"). for(j=0."r"). Ravi Chythanya 31 .f1). else putc(c. fclose(f3). } else if(c==' '||c=='\t') printf(" ").f2). c=getc(f1). fclose(f1). } fclose(f2). } putc(' '.j++) printf("%d".doc { putc(c. while((c=getc(f2))!=EOF) { if(c!=' ') str[k++]=c. else if(c=='\n') lineno++.104337811. else { str[k]='\0'.c). printf("The keywords and identifiersare:"). f3=fopen("specialchar". while(isdigit(c)||isalpha(c)||c=='_'||c=='$') { putc(c. printf("\n").f2).num[j]). while((c=getc(f3))!=EOF) printf("%c"."r"). c=getc(f1). k=0. ungetc(c.j<i. k=0.

of lines are:%d".lineno). of lines are: 1*/ 32 . } By K. Ravi Chythanya OUTPUT: Enter the C program a+b*c Ctrl-D The no’s in the program are: The keywords and identifiers are: a is an identifier and terminal b is an identifier and terminal c is an identifier and terminal Special characters are: +* Total no.doc fclose(f3). printf("Total no.104337811.

yytext) .yytext).} \} {if(!COMMENT) printf("\n BLOCK ENDS").yytext). Ravi Chythanya 8) Write a program to implement the lexical analyzer using lex tool.} {identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER".} int | float | char | double | while | for | do | if | break | continue | void | switch | case | long | struct | const | typedef | return | else | goto {printf("\n\t%s is a KEYWORD".} /*{printf("\n\n\t%s is a COMMENT\n".}*/ "*/" {COMMENT = 0.104337811.yytext). PROGRAM: /* program name is lexp.* { printf("\n%s is a PREPROCESSOR DIRECTIVE".yytext). %} identifier [a-zA-Z][a-zA-Z0-9]* %% #.}*/ {identifier}\( {if(!COMMENT)printf("\n\nFUNCTION\n\t%s".l */ %{ /* program to recognize a c program */ int COMMENT=0.} \{ {if(!COMMENT) printf("\n BLOCK BEGINS"). AIM: A program to implement the Lexical Analyzer.doc By K.yytext).} 33 .} "/*" {COMMENT = 1.} /* printf("\n\n\t%s is a COMMENT\n".

} int yywrap() { return 0.} [0-9]+ {if(!COMMENT) printf("\n\t%s is a NUMBER". exit(0). 34 ."r").)? {if(!COMMENT) printf("\n\t").yytext). return 0.104337811. } yyin = file. Ravi Chythanya \".printf("\n").char **argv) { if (argc > 1) { FILE *file.yytext).ECHO.argv[1]).} \( = ECHO. } yylex().yytext). file = fopen(argv[1].} \<= | \>= | \< | == | \> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR".c #include<stdio. } OUTPUT: /*Input: $vi var. printf("\n\n").b. {if(!COMMENT)printf("\n\t%s is an ASSIGNMENT OPERATOR".yytext).*\" {if(!COMMENT) printf("\n\t%s is a STRING".h> main() { int a.doc By K.} %% int main(int argc.} \)(\. if(!file) { printf("could not open %s \n".

out var. Ravi Chythanya 35 .l $cc lex.doc } Output: $lex lex.c #include<stdio.yy.104337811.h> is a PREPROCESSOR DIRECTIVE FUNCTION main ( ) BLOCK BEGINS int is a KEYWORD a IDENTIFIER b IDENTIFIER BLOCK ENDS*/ By K./a.c $.

void Error_Message(char *m) { fprintf(stderr. exit(1). struct entry { char *lexptr.h> #include<stdlib. } int look_up(char s[ ]) { int k."char".k>0.KEYWORD.m). int lastentry=0.KEYWORD.KEYWORD.k--) if(strcmp(symtable[k]. int token.h> #define SIZE 128 #define NONE -1 #define EOS '\0' #define NUM 257 #define KEYWORD 258 #define ID 259 #define DONE 260 #define MAX 999 char lexemes[MAX]. AIM: A program to implementation of Predictive Parser. int lookahead. PROGRAM: #include<stdio."else".h> #include<ctype.KEYWORD. }symtable[100]. 36 . int lineno=1.KEYWORD.KEYWORD.s)==0) return k.lineno. int tokenval=DONE.doc By K. int lastchar=-1. char buffer[SIZE]. struct entry keywords[]={"if". %s \n". "float"."ret urn"."line %d.104337811."struct".0.KEYWORD."int". for(k=lastentry."double".KEYWORD.KEYWORD.lexptr."for".h> #include<string. Ravi Chythanya 9) Design predictive parser for the given language.0}.

if(lastentry+1>=MAX) Error_Message("Symbpl table is full"). if(t==' '||t=='\t').>token.i=0. } else if(isalpha(t)) { while(isalnum(t)) { buffer[i]=t. if(lastchar+len+1>=MAX) Error_Message("Lexemes array is full"). scanf("%d".lexptr. Ravi Chythanya 37 . lastentry=lastentry+1. len=strlen(s).doc return 0. return lastentry.ptr.104337811.ptr->token).ptr+1) insert(ptr->lexptr. By K. symtable[lastentry]. } int insert(char s[ ]. strcpy(symtable[lastentry]. }*/ int lexer() { int t. while(1) { t=getchar().stdin). else if(t=='\n') lineno=lineno+1. int val. symtable[lastentry].lexptr=&lexemes[lastchar+1]. return NUM. else if(isdigit(t)) { ungetc(t. for(ptr=keywords.s).int tok) { int len. } /*void Initialize() { struct entry *ptr.&tokenval). lastchar=lastchar+len+1. t=getchar().token=tok. i=i+1.

return t.token. switch(lookahead) { case '(' : Match('('). else printf("\n Token %d tokenval %d". } void display(int t. else Error_Message("Syntax error"). else if(t==ID) printf("\n Identifier : %s".ID). if(t!=EOF) ungetc(t.t.symtable[tval]. return symtable[val].lexptr). By K. val=look_up(buffer). } void F() { //void E(). } buffer[i]=EOS. } else if(t==EOF) return DONE. else if(t==NUM) printf("\n Number: %d".stdin). tokenval=val. if(val==0) val=insert(buffer. } } } void Match(int t) { if(lookahead==t) lookahead=lexer().tval).104337811. Ravi Chythanya 38 . else { tokenval=NONE.doc if(i>=SIZE) Error_Message("Compiler error"). E().t).int tval) { if(t=='+'||t=='-'||t=='*'||t=='/') printf("\nArithmetic Operator: %c".tokenval).

F(). display(t.doc Match(')'). display(t. T(). break. T(). Match(lookahead). case '-' : t=lookahead. continue.NONE). } } } void E() { int t. default : return. case ID : display(ID. Ravi Chythanya 39 . continue. Match(NUM). break. continue. Match(lookahead).104337811. while(1) { switch(lookahead) { case '+' : t=lookahead. case '/' : t=lookahead. } } void T() { int t. F().NONE). break. display(t.NONE).tokenval). case NUM : display(NUM. Match(lookahead).tokenval). By K. while(1) { switch(lookahead) { case '*' : t=lookahead. Match(ID). default : Error_Message("Syntax error").

parser().'). Number: 2 Number: 3 Arithmetic Operator: * +3. Identifier: a Identifier: b Identifier: c Arithmetic Operator: * Arithmetic Operator: + 2*3. T(). Match('.NONE). printf("\n Program for recursive decent parsing "). Ravi Chythanya OUTPUT: Program for recursive decent parsing Enter the expression And place . } } main() { char ans[10].Syntax error Ctrl-Z 40 . display(t. printf("Press Ctrl-Z to terminate\n"). default : return. while(lookahead!=DONE) { E().doc Match(lookahead). printf("And place . printf("\n Enter the expression "). } } } void parser() { lookahead=lexer().104337811. line 5. at the end Press Ctrl-Z to terminate a+b*c. at the end\n"). continue. } By K.

$1).104337811. } .h> #include "y. expr: expr '+' term {$$=$1 + $3 .tab. Ravi Chythanya 10) Design LALR Bottom up Parser AIM: A program to design LALR Bottom up Parser. } %token <dval> DIGIT %type <dval> expr %type <dval> term %type <dval> factor %% line: expr '\n' { printf("%g\n". term: term '*' factor {$$=$1 * $3 . PROGRAM: <parser.} | term . } \n|. return yytext[0].l> %{ #include<stdio.y> %{ /*This YACC specification file generates the LALR parser for the program considered in experiment 4.dval=atof(yytext). return DIGIT.h> %} %union { double dval. %% <parser.doc By K.} | factor 41 .*/ #include<stdio.h" %} %% [0-9]+ {yylval.

factor: '(' expr ')' {$$=$2 .doc .tab.c –ll –lm $. %% int main() { yyparse().out 2+3 5./a. } By K. } yyerror(char *s) { printf("%s".y $cc lex.s).0000*/ 42 .} | DIGIT . Ravi Chythanya Output: $lex parser.104337811.l $yacc –d parser.yy.c y.

} {number} {strcpy(yylval.} [ \t] .y> 43 . return VAR.yytext). return WHILE. return yytext[0]. return ELSE.104337811.tab.l> %{ #include"y.h" #include<stdio. return RELOP. %} identifier [a-zA-Z][_a-zA-Z0-9]* number [0-9]+|([0-9]*\.[0-9]+) %% main\(\) return MAIN. \n LineNo++.doc By K. AIM: A program to Convert the BNF rules into YACC form and write code to generate abstract syntax tree.h> int LineNo=1. Ravi Chythanya 11) Convert the BNF rules into YACC form and write code to generate abstract syntax tree.var. PROGRAM: <int.yytext) . return NUM.} \< | \> | \>= | \<= | == {strcpy(yylval. %% < int.yytext). {identifier} {strcpy(yylval.var. if else while int | char | float return IF.h> #include<string. .var. return TYPE.

} %token <var> NUM VAR RELOP %token MAIN IF ELSE WHILE TYPE By K. char arg2[10].104337811. char arg1[10].' | CONDST | WHILEST . }stk.Ind. struct stack { int items[100]. int Index=0. DESCT: TYPE VARLIST 44 .h> struct quad { char op[5].doc %{ #include<string. extern int LineNo.tInd.' | ASSIGNMENT '.tIndex=0. }QUAD[30]. char result[10]. %} %union { char var[10]. int top. BLOCK: '{' CODE '}' .h> #include<stdio. STATEMENT: DESCT '. CODE: BLOCK | STATEMENT CODE | STATEMENT . Ravi Chythanya %type <var> EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP %left '-' '+' %left '*' '/' %% PROGRAM : MAIN BLOCK .StNo.

By K. strcpy(QUAD[Index].result. strcpy(QUAD[Index]. strcpy(QUAD[Index]. } | IFST ELSEST . Ind=pop()."==").} | EXPR '-' EXPR {AddQuadruple("-".$1. push(Index).result."").arg1.} | '-' EXPR {AddQuadruple("UMIN".Index).QUAD[Index++]. VARLIST: VAR '.$3).op.} | VAR | NUM .$2.arg2."-1")."-1").op.$2).$3.arg1. CONDST: IFST{ Ind=pop().$3."". IFST: IF '(' CONDITION ')' { strcpy(QUAD[Index].$1."GOTO").$$).$$).""). sprintf(QUAD[Ind].$1). Index++."%d".arg2. strcpy($$.$$).' VARLIST | VAR .result.$3).result."").doc .op.$$). push(Index). EXPR: EXPR '+' EXPR {AddQuadruple("+". strcpy(QUAD[Index]."%d".$$).$1.$3.arg2. Ravi Chythanya 45 ."="). } .$3.} | '(' EXPR ')' {strcpy($$. strcpy(QUAD[Index]."FALSE").$1. } BLOCK { strcpy(QUAD[Index].Index). strcpy(QUAD[Index].104337811.} | EXPR '/' EXPR {AddQuadruple("/". strcpy(QUAD[Index]. sprintf(QUAD[Ind]. strcpy(QUAD[Index].result). strcpy(QUAD[Index]. ASSIGNMENT: VAR '=' EXPR{ strcpy(QUAD[Index].result.} | EXPR '*' EXPR {AddQuadruple("*".arg1.

arg2. } . sprintf(QUAD[Ind].arg2.result.result. By K. strcpy(QUAD[Index]. Index++. %% 46 . Ind=pop()."%d". strcpy(QUAD[Index].arg1.result.result. push(Index)."%d".Index)."FALSE"). strcpy(QUAD[Index]."-1"). push(tInd).StNo)."%d". strcpy(QUAD[Index]. Index++."GOTO")."==").""). WHILELOOP: WHILE '(' CONDITION ')' { strcpy(QUAD[Index].Index)."-1").op. } . push(Index).$3). CONDITION: VAR R ELOP VAR {AddQuadruple($2. sprintf(QUAD[Ind]. strcpy(QUAD[Index].op. strcpy(QUAD[Index].result.$3. sprintf(QUAD[Ind]. } .Index). StNo=Index-1.$$). Ind=pop(). WHILEST: WHILELOOP{ Ind=pop(). sprintf(QUAD[Ind]. } .result. } BLOCK{ Ind=pop()."%d".104337811.$1. Ravi Chythanya ELSEST: ELSE{ tInd=pop().doc Index++. } BLOCK { strcpy(QUAD[Index].arg1. } | VAR | NUM ."").

} stk.QUAD[i].top++. for(i=0. } int pop() { int data.items[stk.i<Index. if(argc>1) { fp=fopen(argv[1]. Ravi Chythanya extern FILE *yyin.i++) { printf("\n\t\t %d\t %s\t %s\t %s\t %s". exit(0). exit(0). if(stk.items[stk. } yyparse()."r").top==100) { printf("\n Stack overflow\n"). int main(int argc.arg1. return 0. printf("\n\n").doc By K.char *argv[]) { FILE *fp. if(stk.104337811. int i. printf("\n\n\t\t ----------------------------""\n\t\t Pos Operator Arg1 Arg2 Result" "\n\t\t --------------------").QUAD[i].arg2.result).top==-1) { printf("\n Stack underflow\n").QUAD[i]. } printf("\n\t\t -----------------------").i.top--].top]=data. } void push(int data) { stk. } yyin=fp. } data=stk.QUAD[i]. 47 . exit(0).op. if(!fp) { printf("\n File not found").

"t%d". } if(a<=b) { c=a-b.op. Ravi Chythanya } void AddQuadruple(char op[5].arg1.l $yacc –d int. } Output: Input: $vi test.op).c. strcpy(QUAD[Index].arg2). } } Output: $lex int. By K.arg2. if(a<b) { a=a+b.char arg1[10]. } else { c=a+b.char arg2[10].c main() { int a.result).c 48 .out test.c –ll –lm $.char result[10]) { strcpy(QUAD[Index].doc return data.arg1).104337811./a.result.QUAD[Index++].LineNo). } while(a<b) { a=a+b.b. sprintf(QUAD[Index].y $gcc lex.c y. strcpy(QUAD[Index].yy.tab. } yyerror() { printf("\n Error on line no:%d". strcpy(result.tIndex++).

104337811.a b t5 13 = t5 c 14 GOTO 17 15 + a b t3 16 = t6 c */ 5 49 . Ravi Chythanya Pos Operator Arg1 Arg2 Result 0 < a b to 1 == to FALSE 5 2 + a b t1 3 = t1 a 4 GOTO 5 < a b t2 6 == t2 FALSE 10 5 7 + a b t3 8 = t3 a 9 GOTO 10 <= a b t4 11 == t4 FALSE 15 12 .doc By K.

104337811.ch. fscanf(fp1. fp2=fopen("target.i). } if(strcmp(op."w"). fp1=fopen(fname.result)."r")."%s". fprintf(fp2. fprintf(fp2.txt"."print")==0) { fscanf(fp1.operand2). if(fp1==NULL || fp2==NULL) { printf("\n Error opening the file").operand2[8].*fp2. if(strcmp(op."\n\t JMP %s.operand2).h> #include<string. label[no++]=atoi(operand2).operand1. int no=0."\nlabel#%d".op). Ravi Chythanya 12) A Program to Generate Machine Code. int main() { FILE *fp1.op[10]."\n"). } if(strcmp(op.h> int label[20].&fname)."%s". i++.operand1."\n\t OUT %s".label#%s". AIM: A Program to Generate Machine Code.result[8]. if(check_label(i)) fprintf(fp2. } while(!feof(fp1)) { fprintf(fp2.doc By K. char fname[10]."%s %s". char operand1[8]."[]=")==0) { 50 . scanf("%s".h> #include<stdlib."goto")==0) { fscanf(fp1.j=0. printf("\n Enter filename of the intermediate code"). PROGRAM: #include<stdio. exit(0).result). int i=0.

fprintf(fp2.%s". fprintf(fp2.result).operand1). fprintf(fp2."\n \t SUB R1.result).operand2."\n\t LOAD -%s.R1". fprintf(fp2.operand1.R1"."%s %s %s".operand1.operand1).result). Ravi Chythanya fscanf(fp1.operand2). fprintf(fp2."\n \t LOAD".operand2.result).operand2.R0")."\n \t LOAD %s."\n\t STORE %s[%s].result).operand2.operand1).result)."\n \t STORE R0.operand1). fprintf(fp2. break."%s %s %s". fprintf(fp2."\n \t ADD R1.result). fprintf(fp2.R0"."%s %s %s".result)."\n \t LOAD %s.result)."%s %s %s".%s". fprintf(fp2.R0"). fprintf(fp2."\n \t STORE R0. case '=': fscanf(fp1.operand2. fprintf(fp2. break.104337811. fprintf(fp2."%s %s %s". fprintf(fp2."%s %s"."uminus")==0) { fscanf(fp1. fprintf(fp2."\n \t LOAD %s.%s".doc By K.operand2."\n \t LOAD %s.result).R1".result). fprintf(fp2."\n \t DIV R1. case '/': fscanf(fp1.operand2).operand2."%s %s %s". fprintf(fp2.result).%s".%s"."\n \t STORE R0."\n \t DIV R1. fprintf(fp2. fprintf(fp2."\n \t LOAD %s.operand1). } switch(op[0]) { case '*': fscanf(fp1.result)."\n \t MUL R1. fprintf(fp2.operand1. fprintf(fp2.R0". case '-': fscanf(fp1.R0")."\n \t LOAD %s.R1". break. fprintf(fp2. 51 .operand1."\n \t LOAD %s.R1". break. fprintf(fp2.operand2).%s".operand1. break.operand2).R0")."\n \t STORE R0."\n\t STORE %s %s". case '+': fscanf(fp1."%s %s".R0")."\n \t STORE R0.operand1.result). case '>': j++."\n \t LOAD %s. case '%': fscanf(fp1.R0".operand1.operand2).operand1.operand1). fprintf(fp2."\n \t LOAD %s.operand1.result). break. fprintf(fp2.%s"."\n\t STORE R1.R0".operand1. } if(strcmp(op.result).R1".

operand1). break.i++) { if(k==label[i]) return 1."\n \t LOAD %s. fclose(fp1).R0".result).txt =t1 2 []=a 0 1 []=a 1 2 52 . Ravi Chythanya fscanf(fp1. } Output: Input: $vi int. for(i=0. if(fp2==NULL) { printf("Error opening the file\n"). case '<': fscanf(fp1."\n \t LOAD %s.doc By K."\n\t JGT %s."\n\t JLT %s.result). fclose(fp1).operand2.result). printf("%c". }while(ch!=EOF).operand1.operand2.label#%s".104337811. return 0."r").R0". label[no++]=atoi(result). label[no++]=atoi(result). fprintf(fp2. break. exit(0).ch)."%s %s %s".operand1). } int check_label(int k) { int i.txt". fprintf(fp2.result).operand2. } do { ch=fgetc(fp2). fp2=fopen("target.label#%d"."%s %s %s". fprintf(fp2.i<no.operand1. fprintf(fp2. } } fclose(fp2).operand2. } return 0.

R0 STORE R0.R0 STORE R0.label#11 By K.doc []=a 2 3 *t1 6 t2 +a[2] t2 t3 -a[2] t1 t2 /t3 t2 t2 uminus t2 t2 print t2 goto t2 t3 =t3 99 uminus 25 t2 *t2 t3 t3 uminus t1 t1 +t1 t3 t4 print t4 Output: Enter filename of the intermediate code: int.R1 SUB R1.R0 STORE R0.2 STORE a[2].R1 DIV R 1.txt STORE t1.t2 LOAD t3.t2 LOAD t2.R1 ADD R1.t3 LOAD a[t2].t3 LOAD a[2].3 LOAD t1.R0 LOAD t1.R1 STORE R1.1 STORE a[1].R0 STORE R0.R0 JGT 5. Ravi Chythanya 53 .2 STORE a[0].R1 ADD R1.104337811.t2 LOAD t2.R0 LOAD t2.R0 LOAD t2.R0 LOAD 6.

104337811.doc Label#11: OUT t2 JMP t2.R1 STORE R1.R0 LOAD t3.label#13 Label#13: STOR E t3.t1 LOAD t1.t2 LOAD t2.t4 OUT t4 By K.R1 ADD R1.R1 STORE R1.R1 MUL R1. Ravi Chythanya 54 .t3 LOAD t1.R0 STORE R0.R0 LOAD t3.R0 STORE R0.99 LOAD 25.

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.