Escolar Documentos
Profissional Documentos
Cultura Documentos
DATBASE
Assignment 1
Aim: Analyze the problem and come with the entities in it. Identify what Data has to be
persisted in the databases.
Bus:
Source : varchar(20)
Destination : varchar(20)
Passenger:
Ticket_No : Number(9)
Name : varchar(15)
Age : integer(4)
PPNO : varchar(15)
Reservation:
Journey_date : date
No_of_seats : integer(8)
Address : varchar(50)
Contact_No : Number(9)
Status : Char(2)
Cancellation :
Journey_date : date
2
No_of_seats : integer(8)
Address : varchar(50)
Contact_No : Number(9)
Status : Char(2)
Ticket:
Journey_date : date
Age : int(4)
Sex : Char(10)
Source : varchar
Destination :varchar
Dep_time : varchar
3
Assignment 2
Aim: Concept design with E-R model. Relate the entities appropriately. Apply cardinalities for
each relation.
4
Assignment 3
Aim: Represent all entities in a tabular fashion. Represent all relationships in a tabular fashion.
The fallowing are tabular representation of the above entities and relationships
BUS:
Passenger:
Reservation:
Cancellation:
Ticket:
5
Assignment 4
Step 1
Make sure you already downloaded the MySQL essential 5.0.45 win32.msi file. Double click
on the .msi file.
Step 2
This is MySQL Server 5.0 setup wizard. The setup wizard will install MySQL Server 5.0 release
5.0.45 on your computer. To continue, click next.
Step 3
Choose the setup type that best suits your needs. For common program features select Typical
and it’s recommended for general use. To continue, click next.
6
Step 4
7
Step 5
The program features you selected are being installed. Please wait while the setup wizard installs
MySQL 5.0. This may take several minutes.
Step 6
To continue, click next.
8
Step 7
To continue, click next.
Step 8
Wizard Completed. Setup has finished installing MySQL 5.0. Check the configure the MySQL
server now to continue. Click Finish to exit the wizard
d.
9
Step 9
The configuration wizard will allow you to configure the MySQL Server 5.0 server instance. To
continue, click next.
Step 10
Select a standard configuration and this will use a general purpose configuration for the server
that can be tuned manually. To continue, click next.
10
Step 11
Check on the install as windows service and include bin directory in windows path. To
continue, click next.
Step 12
Please set the security options by entering the root password and confirm retype the password.
To continue, click next.
11
Step 13
Ready to execute? Clicks execute to continue.
Step 14
Processing configuration in progress.
12
Step 15
Configuration file created. Windows service MySQL5 installed. Press finish to close the wizard.
a) Passenger Table
SQL> create table Passenger(PNR_NO Numeric(9) primary key , Ticket_NO Numeric(9), Name
varchar(20), Age Number(4), Sex char(10), PPNO varchar(15));
Table created.
TICKET_NO NUMBER(9)
NAME VARCHAR2(20)
AGE NUMBER(4)
SEX CHAR(10)
13
PPNO VARCHAR2(15)
b) Reservation Table
Table created.
PNR_NO NUMBER(9)
NO_OF_SEATS NUMBER(8)
ADDRESS VARCHAR2(50)
CONTACT_NO NUMBER(9)
STATUS CHAR(3)
c) Bus Table
SQL> create table Bus(Bus_No varchar(5) primary key, source varchar(20), destination
varchar(20));
Table created.
SOURCE VARCHAR2(20)
DESTINATION VARCHAR2(20)
d) Cancellation Table
14
Table created.
PNR_NO NUMBER(9)
NO_OF_SEATS NUMBER(8)
ADDRESS VARCHAR2(50)
CONTACT_NO NUMBER(9)
STATUS CHAR(3)
e) Ticket Table
SQL> create table Ticket(Ticket_No Numeric(9) primary key, age number(4), sex char(4) Not
Table created.
AGE NUMBER(4)
SOURCE VARCHAR2(2)
DESTINATION VARCHAR2(20)
DEP_TIME VARCHAR2(4)
15
Table altered.
Table altered.
Table altered.
2.3 INSERT
1 row created.
SQL> /
16
Enter value for age: 24
Enter value for sex: f
Enter value for ppno: sdqw34
old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex',
'&PPNO')
1 row created.
SQL> /
1 row created.
SQL> /
17
PNR_NO TICKET_NO NAME AGE SEX PPNO
1 1 SACHIN 12 m sd1234
2 2 rahul 34 m sd3456
3 3 swetha 24 f sdqw34
4 4 ravi 56 m sdqazx
1 row created.
SQL> /
1 row created.
SQL> /
18
1 row created.
SQL> /
1 row created.
SQL> /
ERROR at line 1:
1 row created.
19
SQL> insert into Reservation
values(&PNR_NO,&No_of_seats,'&Address',&Contact_No,'&Status');
ERROR at line 1:
1 row updated.
1 1 SACHIN 12 m sd1234
2 2 rahul 43 m sd3456
3 3 swetha 24 f sdqw34
4 4 ravi 56 m sdqazx
2.5 DELETE
1 row deleted.
20
SQL> select * from Passenger;
1 1 SACHIN 12 m sd1234
2 2 rahul 43 m sd3456
3 3 swetha 24 f sdqw34
Table dropped.
21
Assignment 5
PNR_NO
----------
7 rows selected.
NAME
--------------------
SACHIN
rahul
rafi
salim
riyaz
22
TICKET_NO NAME
---------- --------------------
1 SACHIN
2 rahul
3 swetha
23 rafi
12 salim
34 riyaz
21 neha
7 rows selected.
4. Display the source and destination having journey time more than 10 hours.
SOURCE DESTINATION
---------- --------------------
HYD BAN
SEC BAN
HYD MUM
5. Find the ticket number of passenger whose name starts with ‘S’ and ends with ‘H’
SQL> select Ticket_NO from Passenger where Name like'S%'and name like'%N';
TICKET_NO
----------
SQL> select Name from Passenger where age between 20 and 40;
23
NAME
--------------------
swetha
rafi
riyaz
neha
NAME
--------------------
rahul
rafi
riyaz
NAME
--------------------
SACHIN
neha
rafi
rahul
riyaz
salim
swetha
7 rows selected.
24
Assignment 6
Aim: Practice queries using Aggregate functions, Group by, having and Creation and Dropping
of views
1 2 sdfgh 1234543 s
1 3 msbtnk 123456789 s
2 2 ldkp 234567891 s
2 2 wertgfds 12212121 n
3 4 dskng 345678912 n
3 5 azxsdcvf 13243546 s
4 2 ddfdsfsdfdsf 3456789 s
4 5 abids 567891234 s
5 2 allbd 891234567 s
5 11 liopujth 43256787 s
6 1 koti 231456781 s
6 31 swebnht 453212345 s
7 2 dbdhfdbhf 90876543 s
7 3 jklhg 2345671 s
14 rows selected.
25
2. Find the distinct PNR_NO that are present
PNR_NO NOOCCURANCES
---------- ------------
1 1
2 1
3 1
4 1
5 1
6 1
7 1
7 rows selected.
PNR_NO SUM(NO_OF_SEATS)
---------- ----------------
1 3
6 1
2 2
4 5
5 2
3 6
7 3
7 rows selected.
26
4. Find the number of seats booked in each class where the number of
seats is greater than 1.
SQL> select class,sum(No_of_seats) from Reservation where class='a 'or class='b' or class=
CLASS SUM(NO_OF_SEATS)
---- ---------------
a 13
b 7
c 2
SUM(NO_OF_SEATS)
----------------
22
a) CREATE VIEW
SQL> create view male_pass as select PNR_NO,age from Passenger where sex='m';
View created.
PNR_NO AGE
---------- ----------
1 12
2 43
4 22
5 45
27
6 32
SQL> create view v1 as select * from Passenger full natural join Reservation;
View created.
b) INSERT
1 row created.
c) DROP VIEW
View dropped.
28
Assignment 7
a) CREATE OR RELPLACE TRIGGER trig1 before insert on Bus for each row
DECLARE a number;
BEGIN
if(:new.Bus_No is Null) then
raise_application_error(-20001,'error:: Bus_No cannot be null');
else
select count(*) into a from Bus where Bus_No =:new. Bus_No;
if(a=1) then
raise_application_error(-20002,'error:: cannot have duplicate Bus_No ');
end if;
end if;
END;
RESULT:
SQL> @trigger
Trigger created.
SQL> select * from Bus;
BUS_NO SOURCE DESTINATION
----- -------------------- --------------------
110 hyd ban
221 hyd chn
412 hyd mum
501 hyd kol
SQL> insert into Bus values(&Bus_No,'&source','&destination');
Enter value for Bus_No: null
Enter value for source: Chen
29
Enter value for destination: hyd
old 1: insert into Bus values(&Bus_No, '&source', '&destination')
new 1: insert into Bus values(null,Chen','hyd')
insert into Bus values(null,’Chen','hyd')
*
ERROR at line 1:
ORA-20001: error::Bus_No cannot be null
35
ORA-06512: at "SYSTEM.TRIG1", line 5
ORA-04088: error during execution of trigger 'SYSTEM.TRIG1'
SQL> /
Enter value for Bus_No: 110
Enter value for source:KOL
Enter value for destination: hyd
old 1: insert into Bus values(&Bus_No, '&source', '&destination')
new 1: insert into Bus values(110,KOL','hyd')
insert into Bus values(110,’KOL','hyd')
*
ERROR at line 1:
ORA-20002: error:: cannot have duplicate Bus_No
ORA-06512: at "SYSTEM.TRIG1", line 9
ORA-04088: error during execution of trigger 'SYSTEM.TRIG1'
30
End.
SQL> @trigger
Trigger created.
c) CREATE OR RELPLACE TRIGGER trig1 before insert on Passenger for each row
DECLARE a number;
BEGIN
if(:new.PNR_NO is Null) then
raise_application_error(-20001,'error:: PNR_NO cannot be null');
else
select count(*) into a from Passenger where PNR_NO =:new. PNR_NO;
if(a=1) then
raise_application_error(-20002,'error:: cannot have duplicate PNR_NO ');
end if;
end if;
END;
SQL> @trigger
Trigger created.
31
Assignment 8
Aim: To write a Cursor to display the list of Male and Female Passengers.
Analyst.
DECLARE
cursor c(jb varchar2) is select Name from Passenger where Sex=m;
pr Passenger.Sex%type;
BEGIN
open c('m');
dbms_RESULT.put_line(' Name of Male Passenger are:');
loop
fetch c into pr;
exit when c%notfound;
dbms_RESULT.put_line(pr);
end loop;
close c;
open c('f');
dbms_RESULT.put_line(' Name of female Passengers are:');
loop
fetch c into em;
exit when c%notfound;
dbms_RESULT.put_line(em);
end loop;
close c;
END;
RESULT:
Name of Male Passenger are:
SACHIN
rahul
rafi
salim
32
riyaz
Name of female Passengers are:
swetha
neha
PL/SQL procedure successfully completed.
33
PL/SQL procedure successfully completed.
PART II
COMPILER DESIGN
34
Program 1
#include<string.h>
#include<ctype.h>
#include<stdio.h>
void keyword(char str[10])
{
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||strcmp("int",str)==0||
strcmp("float",str)==0||strcmp("char",str)==0||strcmp("double",str)==0||strcmp("static",str)==0||
strcmp("switch",str)==0||strcmp("case",str)==0)
printf("\n%s is a keyword",str);
else
printf("\n%s is an identifier",str);
}
main()
{
FILE *f1,*f2,*f3;
char c,str[10],st1[10];
int num[100],lineno=0,tokenvalue=0,i=0,j=0,k=0;
printf("\nEnter the c program");/*gets(st1);*/
f1=fopen("input","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input","r");
f2=fopen("identifier","w");
f3=fopen("specialchar","w");
35
while((c=getc(f1))!=EOF)
{
if(isdigit(c))
{
tokenvalue=c-'0';
c=getc(f1);
while(isdigit(c))
{
tokenvalue*=10+c-'0';
c=getc(f1);
}
num[i++]=tokenvalue;
ungetc(c,f1);
}
else if(isalpha(c))
{
putc(c,f2);
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
putc(c,f2);
c=getc(f1);
}
putc(' ',f2);
ungetc(c,f1);
}
else if(c==' '||c=='\t')
printf(" ");
else if(c=='\n')
lineno++;
36
else
putc(c,f3);
}
fclose(f2);
fclose(f3);
fclose(f1);
printf("\nThe no's in the program are");
for(j=0;j<i;j++)
printf("%d",num[j]);
printf("\n");
f2=fopen("identifier","r");
k=0;
printf("The keywords and identifiersare:");
while((c=getc(f2))!=EOF)
{
if(c!=' ')
str[k++]=c;
else
{
str[k]='\0';
keyword(str);
k=0;
}
}
fclose(f2);
f3=fopen("specialchar","r");
printf("\nSpecial characters are");
while((c=getc(f3))!=EOF)
printf("%c",c);
printf("\n");
fclose(f3);
37
printf("Total no. of lines are:%d",lineno);
}
Output:
Enter the C program
a+b*c
Ctrl-D
38
Program 2
39
else |
goto {printf("\n\t%s is a KEYWORD",yytext);}
"/*" {COMMENT = 1;}
/*{printf("\n\n\t%s is a COMMENT\n",yytext);}*/
/* printf("\n\n\t%s is a COMMENT\n",yytext);}*/
{identifier}\( {if(!COMMENT)printf("\n\nFUNCTION\n\t%s",yytext);}
\{ {if(!COMMENT) printf("\n BLOCK BEGINS");}
\} {if(!COMMENT) printf("\n BLOCK ENDS");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\" {if(!COMMENT) printf("\n\t%s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n\t%s is a NUMBER",yytext);}
\)(\;)? {if(!COMMENT) printf("\n\t");ECHO;printf("\n");}
\( ECHO;
= {if(!COMMENT)printf("\n\t%s is an ASSIGNMENT OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
%%
40
if(!file)
{
printf("could not open %s \n",argv[1]);
exit(0);
}
yyin = file;
}
yylex();
printf("\n\n");
return 0;
}
int yywrap()
{
return 0;
}
41
Input:
$vi var.c
#include<stdio.h>
main()
{
int a,b;
}
Output:
$lex lex.l
$cc lex.yy.c
$./a.out var.c
FUNCTION
main (
BLOCK BEGINS
int is a KEYWORD
a IDENTIFIER
b IDENTIFIER
42
BLOCK ENDS
Program 3
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.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];
char buffer[SIZE];
int lastchar=-1;
int lastentry=0;
int tokenval=DONE;
int lineno=1;
int lookahead;
struct entry
{
char *lexptr;
int token;
}symtable[100];
43
struct entry
keywords[]={"if",KEYWORD,"else",KEYWORD,"for",KEYWORD,"int",KEYWORD,"float",
KEYWORD,"double",KEYWORD,"char",KEYWORD,"struct",KEYWORD,"return",KEYWO
RD,0,0};
void Error_Message(char *m)
{
fprintf(stderr,"line %d, %s \n",lineno,m);
exit(1);
}
int look_up(char s[ ])
{
int k;
for(k=lastentry;k>0;k--)
if(strcmp(symtable[k].lexptr,s)==0)
return k;
return 0;
}
int insert(char s[ ],int tok)
{
int len;
len=strlen(s);
if(lastentry+1>=MAX)
Error_Message("Symbpl table is full");
if(lastchar+len+1>=MAX)
Error_Message("Lexemes array is full");
lastentry=lastentry+1;
symtable[lastentry].token=tok;
symtable[lastentry].lexptr=&lexemes[lastchar+1];
lastchar=lastchar+len+1;
strcpy(symtable[lastentry].lexptr,s);
return lastentry;
44
}
/*void Initialize()
{
struct entry *ptr;
for(ptr=keywords;ptr->token;ptr+1)
insert(ptr->lexptr,ptr->token);
}*/
int lexer()
{
int t;
int val,i=0;
while(1)
{
t=getchar();
if(t==' '||t=='\t');
else if(t=='\n')
lineno=lineno+1;
else if(isdigit(t))
{
ungetc(t,stdin);
scanf("%d",&tokenval);
return NUM;
}
else if(isalpha(t))
{
while(isalnum(t))
{
buffer[i]=t;
t=getchar();
i=i+1;
if(i>=SIZE)
45
Error_Message("Compiler error");
}
buffer[i]=EOS;
if(t!=EOF)
ungetc(t,stdin);
val=look_up(buffer);
if(val==0)
val=insert(buffer,ID);
tokenval=val;
return symtable[val].token;
}
else if(t==EOF)
return DONE;
else
{
tokenval=NONE;
return t;
}
}
}
void Match(int t)
{
if(lookahead==t)
lookahead=lexer();
else
Error_Message("Syntax error");
}
void display(int t,int tval)
{
if(t=='+'||t=='-'||t=='*'||t=='/')
printf("\nArithmetic Operator: %c",t);
46
else if(t==NUM)
printf("\n Number: %d",tval);
else if(t==ID)
printf("\n Identifier: %s",symtable[tval].lexptr);
else
printf("\n Token %d tokenval %d",t,tokenval);
}
void F()
{
//void E();
switch(lookahead)
{
case '(' : Match('(');
E();
Match(')');
break;
case NUM : display(NUM,tokenval);
Match(NUM);
break;
case ID : display(ID,tokenval);
Match(ID);
break;
default : Error_Message("Syntax error");
}
}
void T()
{
int t;
F();
while(1)
{
47
switch(lookahead)
{
case '*' : t=lookahead;
Match(lookahead);
F();
display(t,NONE);
continue;
case '/' : t=lookahead;
Match(lookahead);
display(t,NONE);
continue;
default : return;
}
}
}
void E()
{
int t;
T();
while(1)
{
switch(lookahead)
{
case '+' : t=lookahead;
Match(lookahead);
T();
display(t,NONE);
continue;
case '-' : t=lookahead;
Match(lookahead);
T();
48
display(t,NONE);
continue;
default : return;
}
}
}
void parser()
{
lookahead=lexer();
while(lookahead!=DONE)
{
E();
Match(';');
}
}
main()
{
char ans[10];
printf("\n Program for recursive decent parsing ");
printf("\n Enter the expression ");
printf("And place ; at the end\n");
printf("Press Ctrl-Z to terminate\n");
parser();
}
49
Output:
Program for recursive decent parsing
Enter the expression And place ; at the end
Press Ctrl-Z to terminate
a+b*c;
Identifier: a
Identifier: b
Identifier: c
Arithmetic Operator: *
Arithmetic Operator: +
2*3;
Number: 2
Number: 3
Arithmetic Operator: *
+3;
line 5,Syntax error
Ctrl-Z
50
Program 4
<parser.l>
%{
#include<stdio.h>
#include "y.tab.h"
%}
%%
[0-9]+ {yylval.dval=atof(yytext);
return DIGIT;
}
\n|. return yytext[0];
%%
<parser.y>
%{
/*This YACC specification file generates the LALR parser for the program considered in
experiment 4.*/
#include<stdio.h>
%}
%union
{
double dval;
}
%token <dval> DIGIT
%type <dval> expr
%type <dval> term
%type <dval> factor
51
%%
line: expr '\n' {
printf("%g\n",$1);
};
expr: expr '+' term {$$=$1 + $3 ;}
| term
;
term: term '*' factor {$$=$1 * $3 ;}
| factor
;
factor: '(' expr ')' {$$=$2 ;}
| DIGIT
;
%%
int main()
{
yyparse();
}
yyerror(char *s)
{
printf("%s",s);
}
Output:
$lex parser.l
$yacc –d parser.y
$cc lex.yy.c y.tab.c –ll –lm
$./a.out
2+3
52
5.0000
Program 5
Aim: Convert The BNF rules into Yacc form and write code to generate abstract syntax tree.
<int.l>
%{
#include"y.tab.h"
#include<stdio.h>
#include<string.h>
int LineNo=1;
%}
identifier [a-zA-Z][_a-zA-Z0-9]*
number [0-9]+|([0-9]*\.[0-9]+)
%%
if return IF;
else return ELSE;
while return WHILE;
int |
char |
float return TYPE;
{identifier} {strcpy(yylval.var,yytext);
return VAR;}
{number} {strcpy(yylval.var,yytext);
53
return NUM;}
\< |
\> |
\>= |
\<= |
== {strcpy(yylval.var,yytext);
return RELOP;}
[ \t] ;
\n LineNo++;
. return yytext[0];
%%
<int.y>
%{
#include<string.h>
#include<stdio.h>
struct quad
{
char op[5];
char arg1[10];
char arg2[10];
char result[10];
}QUAD[30];
struct stack
{
int items[100];
54
int top;
}stk;
int Index=0,tIndex=0,StNo,Ind,tInd;
extern int LineNo;
%}
%union
{
char var[10];
}
%token <var> NUM VAR RELOP
%token MAIN IF ELSE WHILE TYPE
%%
CODE: BLOCK
| STATEMENT CODE
| STATEMENT
;
STATEMENT: DESCT ';'
55
| ASSIGNMENT ';'
| CONDST
| WHILEST
;
56
CONDST: IFST{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
| IFST ELSEST
;
BLOCK {
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
;
ELSEST: ELSE{
tInd=pop();
Ind=pop();
57
push(tInd);
sprintf(QUAD[Ind].result,"%d",Index);
}
BLOCK{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
58
strcpy(QUAD[Index].op,"GOTO");
strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
;
%%
extern FILE *yyin;
int main(int argc,char *argv[])
{
FILE *fp;
int i;
if(argc>1)
{
fp=fopen(argv[1],"r");
if(!fp)
{
printf("\n File not found");
exit(0);
}
yyin=fp;
}
yyparse();
printf("\n\n\t\t ----------------------------""\n\t\t Pos Operator Arg1 Arg2 Result" "\n\t\t
--------------------");
for(i=0;i<Index;i++)
{
printf("\n\t\t %d\t %s\t %s\t %s\t
%s",i,QUAD[i].op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i].result);
59
}
printf("\n\t\t -----------------------");
printf("\n\n");
return 0;
}
void push(int data)
{
stk.top++;
if(stk.top==100)
{
printf("\n Stack overflow\n");
exit(0);
}
stk.items[stk.top]=data;
}
int pop()
{
int data;
if(stk.top==-1)
{
printf("\n Stack underflow\n");
exit(0);
}
data=stk.items[stk.top--];
return data;
}
void AddQuadruple(char op[5],char arg1[10],char arg2[10],char result[10])
{
strcpy(QUAD[Index].op,op);
strcpy(QUAD[Index].arg1,arg1);
strcpy(QUAD[Index].arg2,arg2);
60
sprintf(QUAD[Index].result,"t%d",tIndex++);
strcpy(result,QUAD[Index++].result);
}
yyerror()
{
printf("\n Error on line no:%d",LineNo);
}
Input:
$vi test.c
main()
{
int a,b,c;
if(a<b)
{
a=a+b;
}
while(a<b)
{
a=a+b;
}
if(a<=b)
{
c=a-b;
}
else
{
c=a+b;
}
}
61
Output:
$lex int.l
$yacc –d int.y
$gcc lex.yy.c y.tab.c –ll –lm
$./a.out test.c
0 < a b to
1 == to FALSE 5
2 + a b t1
3 = t1 a
4 GOTO 5
5 < a b t2
6 == t2 FALSE 10
7 + a b t3
8 = t3 a
9 GOTO 5
10 <= a b t4
11 == t4 FALSE 15
12 - a b t5
13 = t5 c
14 GOTO 17
15 + a b t3
16 = t6 c
___________________________________________________
62
Program 6
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int label[20];
int no=0;
int main()
{
FILE *fp1,*fp2;
char fname[10],op[10],ch;
char operand1[8],operand2[8],result[8];
int i=0,j=0;
printf("\n Enter filename of the intermediate code");
scanf("%s",&fname);
fp1=fopen(fname,"r");
fp2=fopen("target.txt","w");
if(fp1==NULL || fp2==NULL)
{
printf("\n Error opening the file");
exit(0);
}
while(!feof(fp1))
{
fprintf(fp2,"\n");
fscanf(fp1,"%s",op);
i++;
if(check_label(i))
63
fprintf(fp2,"\nlabel#%d",i);
if(strcmp(op,"print")==0)
{
fscanf(fp1,"%s",result);
fprintf(fp2,"\n\t OUT %s",result);
}
if(strcmp(op,"goto")==0)
{
fscanf(fp1,"%s %s",operand1,operand2);
fprintf(fp2,"\n\t JMP %s,label#%s",operand1,operand2);
label[no++]=atoi(operand2);
}
if(strcmp(op,"[]=")==0)
{
fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n\t STORE %s[%s],%s",operand1,operand2,result);
}
if(strcmp(op,"uminus")==0)
{
fscanf(fp1,"%s %s",operand1,result);
fprintf(fp2,"\n\t LOAD -%s,R1",operand1);
fprintf(fp2,"\n\t STORE R1,%s",result);
}
switch(op[0])
{
case '*': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD",operand1);
fprintf(fp2,"\n \t LOAD %s,R1",operand2);
fprintf(fp2,"\n \t MUL R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
64
case '+': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n \t LOAD %s,R1",operand2);
fprintf(fp2,"\n \t ADD R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case '-': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n \t LOAD %s,R1",operand2);
fprintf(fp2,"\n \t SUB R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case '/': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n \t LOAD %s,R1",operand2);
fprintf(fp2,"\n \t DIV R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case '%': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n \t LOAD %s,R1",operand2);
fprintf(fp2,"\n \t DIV R1,R0");
fprintf(fp2,"\n \t STORE R0,%s",result);
break;
case '=': fscanf(fp1,"%s %s",operand1,result);
fprintf(fp2,"\n\t STORE %s %s",operand1,result);
break;
case '>': j++;
fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n\t JGT %s,label#%s",operand2,result);
65
label[no++]=atoi(result);
break;
case '<': fscanf(fp1,"%s %s %s",operand1,operand2,result);
fprintf(fp2,"\n \t LOAD %s,R0",operand1);
fprintf(fp2,"\n\t JLT %s,label#%d",operand2,result);
label[no++]=atoi(result);
break;
}
}
fclose(fp2);
fclose(fp1);
fp2=fopen("target.txt","r");
if(fp2==NULL)
{
printf("Error opening the file\n");
exit(0);
}
do
{
ch=fgetc(fp2);
printf("%c",ch);
}while(ch!=EOF);
fclose(fp1);
return 0;
}
int check_label(int k)
{
int i;
for(i=0;i<no;i++)
{
if(k==label[i])
66
return 1;
}
return 0;
}
Input:
$vi int.txt
=t1 2
[]=a 0 1
[]=a 1 2
[]=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.txt
STORE t1,2
STORE a[0],1
67
STORE a[1],2
STORE a[2],3
LOAD t1,R0
LOAD 6,R1
ADD R1,R0
STORE R0,t3
LOAD a[2],R0
LOAD t2,R1
ADD R1,R0
STORE R0,t3
LOAD a[t2],R0
LOAD t1,R1
SUB R1,R0
STORE R0,t2
LOAD t3,R0
LOAD t2,R1
DIV R1,R0
STORE R0,t2
LOAD t2,R1
STORE R1,t2
LOAD t2,R0
JGT 5,label#11
Label#11: OUT t2
JMP t2,label#13
Label#13: STORE t3,99
68
LOAD 25,R1
STORE R1,t2
LOAD t2,R0
LOAD t3,R1
MUL R1,R0
STORE R0,t3
LOAD t1,R1
STORE R1,t1
LOAD t1,R0
LOAD t3,R1
ADD R1,R0
STORE R0,t4
OUT t4
69