Date post: | 20-Nov-2014 |
Category: |
Documents |
Upload: | venugopal-chattu |
View: | 152 times |
Download: | 13 times |
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
DATBASE AND COMPILER LAB
JOGINPALLY B. R ENGINEERING COLLEGE (Affiliated to JNTU, Hyd. & Approved by AICTE New Delhi)
Dept of Computer Science and Engineering 09J21D5818
DATBASE AND COMPILER LAB
JOGINPALLY B.R. ENGINEERING COLLEGE 2
Dept of Computer Science and Engineering 09J21D5818
OBSERVATION BOOK
Rollno: 09J21D5818 Name: CH.VENUGOPAL
JOGINPALLY B.R. ENGINEERING COLLEGE 3
Dept of Computer Science and Engineering 09J21D5818
DATABASES AND COMPILERS LAB
Objective: This lab enables and students to practice the concepts learnt in the subject DBMS by developing a database for an example company named “Roadway Travels” whose description is as follows. The student is expected to practice the designing, developing and querying a database in the content of example database “Roadway Travels”. Students are expected to use “Mysql” database
Roadway TravelsRoadway Travels is in Business since 1997 with buses connecting different places in Indian. Its main office located in Hyderabad
The company wants to computerize its operations in the following areas:
ReservationsTicketingCancellations
Reservations:Reservations are directly handled by booking office. Reservations can be made 60 days in advance either cash or credit. In case the ticket is not available, await listed ticket is issued to the customer. This ticket is confirmed against the cancellation
Cancellation and Modification:Cancellations are also directly handed at the booking office. Cancellation charges will be charged .wait listed tickets that do not get confirmed are fully refunded
JOGINPALLY B.R. ENGINEERING COLLEGE 4
Dept of Computer Science and Engineering 09J21D5818
Week1: E-R modelAnalyze the problem and come with the entities in it. Identify what Data has to be persisted in the databases.
The Following are the entities and its attributesBus:Bus_No : varchar(10) (primary key)Source : varchar(20)Destination : varchar(20)
Passenger:PNR_No : Number(9) (primary key)Ticket_No : Number(9)Name : varchar(15)Age : integer(4)Sex : char(10) ; Male/FemalePPNO : varchar(15)
Reservation:PNR_No : number(9) (foreign key)Journey_date : dateNo_of_seats : integer(8)Address : varchar(50)Contact_No : Number(9)Status : Char(2)
Cancellation :PNR_No : number(9)(foreign key)Journey_date : dateNo_of_seats : integer(8)Address : varchar(50)Contact_No : Number(9)Status : Char(2)
Ticket:Ticket_No : number(9)(primary key)Journey_date : dateAge : int(4)Sex : Char(10)Source : varcharDestination :varcharDep_time : varchar
JOGINPALLY B.R. ENGINEERING COLLEGE 5
Dept of Computer Science and Engineering 09J21D5818
Week2: Concept design with E-R model.
Relate the entities appropriately. Apply cardinalities for each relation.
JOGINPALLY B.R. ENGINEERING COLLEGE 6
Dept of Computer Science and Engineering 09J21D5818
Week3: Relational Model
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:Bus_no Source Destination
Passenger:Pnr_No Ticket_no Name Age Sex PPNO
Reservation:Pnr_No Journey_date No_of_seats Address Contact_No Status
Cancellation:Pnr_No Journey_date No_of_seats Address Contact_No Status
Ticket:Ticket_No Journey_date Age sex source Destination Dep_time
JOGINPALLY B.R. ENGINEERING COLLEGE 7
Dept of Computer Science and Engineering 09J21D5818
Week5: Installation of MySQL and practicing DDL commands.
1. Steps for installing MySQL
Step 1Make sure you already downloaded the MySQL essential 5.0.45 win32.msi file. Double click on the .msi file.
Step 2This 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 3Choose 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.
JOGINPALLY B.R. ENGINEERING COLLEGE 8
Dept of Computer Science and Engineering 09J21D5818
Step 4
This wizard is ready to begin installation. Destination folder will be in C:\Program Files\MySQL\MySQL Server 5.0\. To continue, click next.
Step 5The program features you selected are being installed. Please wait while the setup wizard installs MySQL 5.0. This may take several minutes.
JOGINPALLY B.R. ENGINEERING COLLEGE 9
Dept of Computer Science and Engineering 09J21D5818
Step 6To continue, click next.
Step 7To continue, click next.
JOGINPALLY B.R. ENGINEERING COLLEGE 10
Dept of Computer Science and Engineering 09J21D5818
Step 8Wizard Completed. Setup has finished installing MySQL 5.0. Check the configure the MySQL server now to continue. Click Finish to exit the wizard
d.
JOGINPALLY B.R. ENGINEERING COLLEGE 11
Dept of Computer Science and Engineering 09J21D5818
Step 9The configuration wizard will allow you to configure the MySQL Server 5.0 server instance. To continue, click next.
Step 10Select a standard configuration and this will use a general purpose configuration for the server that can be tuned manually. To continue, click next.
Step 11
Check on the install as windows service and include bin directory in windows path. To continue, click next.
JOGINPALLY B.R. ENGINEERING COLLEGE 12
Dept of Computer Science and Engineering 09J21D5818
Step 12Please set the security options by entering the root password and confirm retype the password. To continue, click next.
JOGINPALLY B.R. ENGINEERING COLLEGE 13
Dept of Computer Science and Engineering 09J21D5818
Step 13Ready to execute? Clicks execute to continue.
Step 14Processing configuration in progress.
JOGINPALLY B.R. ENGINEERING COLLEGE 14
Dept of Computer Science and Engineering 09J21D5818
Step 15Configuration file created. Windows service MySQL5 installed. Press finish to close the wizard.
2. Practicing DDL commands
2.1 CREATE Table
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.SQL> desc passenger Name Null? Type ----------------------------------------- -------- ---------------------------- PNR_NO NOT NULL NUMBER(9) TICKET_NO NUMBER(9) NAME VARCHAR2(20) AGE NUMBER(4) SEX CHAR(10) PPNO VARCHAR2(15)b) Reservation Table
SQL> create table Reservation(PNR_NO Numeric(9), No_of_seats Number(8), Address varchar(50), Contact_No Numeric(9), Status char(3));Table created.SQL> desc Reservation Name Null? Type ----------------------------------------- -------- ---------------------------- PNR_NO NUMBER(9) NO_OF_SEATS NUMBER(8) ADDRESS VARCHAR2(50)
JOGINPALLY B.R. ENGINEERING COLLEGE 15
Dept of Computer Science and Engineering 09J21D5818
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.SQL> desc bus; Name Null? Type ----------------------------------------- -------- ---------------------------- BUS_NO NOT NULL VARCHAR2(5) SOURCE VARCHAR2(20) DESTINATION VARCHAR2(20)d) Cancellation Table
SQL> create table Cancellation(PNR_NO Numeric(9), No_of_seats Number(8), Address varchar(50), Contact_No Numeric(9), Status char(3));Table created.SQL> desc Cancellation Name Null? Type ----------------------------------------- -------- ---------------------------- 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) Notnull, source varchar(2), destination varchar(20), dep_time varchar(4));Table created.SQL> desc Ticket Name Null? Type ----------------------------------------- -------- ---------------------------- TICKET_NO NOT NULL NUMBER(9) AGE NUMBER(4) SEX NOT NULL CHAR(4) SOURCE VARCHAR2(2) DESTINATION VARCHAR2(20) DEP_TIME VARCHAR2(4)2.2 ALTER Table
SQL> ALTER TABLE Reservation ADD FOREIGN KEY (PNR_NO) REFERENCES Passenger(PNR_NO);Table altered.SQL> ALTER TABLE Cancellation ADD FOREIGN KEY (PNR_NO) REFERENCES Passenger(PNR_NO);Table altered.SQL> alter table Ticket add constraint check_age check(age>18);Table altered.2.3 INSERT
JOGINPALLY B.R. ENGINEERING COLLEGE 16
Dept of Computer Science and Engineering 09J21D5818
SQL> insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex', '&PPNO');Enter value for pnr_no: 1Enter value for ticket_no: 1Enter value for name: SACHINEnter value for age: 12Enter value for sex: mEnter value for ppno: sd1234old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex',
'&PPNO')
new 1: insert into Passenger values(1,1,'SACHIN',12,'m','sd1234')
1 row created.
SQL> /Enter value for pnr_no: 2Enter value for ticket_no: 2Enter value for name: rahulEnter value for age: 34Enter value for sex: mEnter value for ppno: sd3456old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex', '&PPNO')new 1: insert into Passenger values(2,2,'rahul',34,'m','sd3456')1 row created.SQL> /Enter value for pnr_no: 3Enter value for ticket_no: 3Enter value for name: swethaEnter value for age: 24Enter value for sex: fEnter value for ppno: sdqw34old 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex', '&PPNO')new 1: insert into Passenger values(3,3,'swetha',24,'f','sdqw34')1 row created.SQL> /Enter value for pnr_no: 4Enter value for ticket_no: 4Enter value for name: raviEnter value for age: 56Enter value for sex: mEnter value for ppno: sdqazxold 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex', '&PPNO')new 1: insert into Passenger values(4,4,'ravi',56,'m','sdqazx')1 row created.SQL> /Enter value for pnr_no: 4Enter value for ticket_no: 5Enter value for name: asif
JOGINPALLY B.R. ENGINEERING COLLEGE 17
Dept of Computer Science and Engineering 09J21D5818
Enter value for age: 33Enter value for sex: mEnter value for ppno: iuyhjkold 1: insert into Passenger values(&PNR_NO,&TICKET_NO, '&Name', &Age, '&Sex', '&PPNO')new 1: insert into Passenger values(4,5,'asif',33,'m','iuyhjk')insert into Passenger values(4,5,'asif',33,'m','iuyhjk')*ERROR at line 1: ORA-00001: unique constraint (SYSTEM.SYS_C004023) violated
SQL> select * from Passenger;
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
SQL> insert into Bus values('&Bus_No','&source','&destination');Enter value for bus_no: 1Enter value for source: hydEnter value for destination: ban
old 1: insert into Bus values('&Bus_No','&source','&destination')new 1: insert into Bus values('1','hyd','ban')1 row created.SQL> /Enter value for bus_no: 2Enter value for source: hydEnter value for destination: chn
old 1: insert into Bus values('&Bus_No','&source','&destination')new 1: insert into Bus values('2','hyd','chn')1 row created.SQL> /Enter value for bus_no: 4Enter value for source: hydEnter value for destination: mum
old 1: insert into Bus values('&Bus_No','&source','&destination')new 1: insert into Bus values('4','hyd','mum')
1 row created.SQL> /Enter value for bus_no: 5Enter value for source: hydEnter value for destination: kol
old 1: insert into Bus values('&Bus_No','&source','&destination')new 1: insert into Bus values('5','hyd','kol')1 row created.SQL> /Enter value for bus_no: 5
JOGINPALLY B.R. ENGINEERING COLLEGE 18
Dept of Computer Science and Engineering 09J21D5818
Enter value for source: secEnter value for destination: ban
old 1: insert into Bus values('&Bus_No','&source','&destination')new 1: insert into Bus values('5','sec','ban')insert into Bus values('5','sec','ban')*ERROR at line 1:ORA-00001: unique constraint (SYSTEM.SYS_C004025) violatedSQL> insert into Reservation values(&PNR_NO, &No_of_seats, '&Address', &Contact_No , '&Status');Enter value for pnr_no: 1Enter value for no_of_seats: 2Enter value for address: masabtankEnter value for contact_no: 9009897812Enter value for status: s
old 1: insert into Reservation values(&PNR_NO, &No_of_seats, '&Address', &Contact_No,' &Status')new 1: insert into Reservation values(1,2,'masabtank',9009897812,'s')1 row created.
SQL> insert into Reservation values(&PNR_NO,&No_of_seats,'&Address',&Contact_No,'&Status');Enter value for pnr_no: 8Enter value for no_of_seats: 3Enter value for address: cbtEnter value for contact_no: 9090887753Enter value for status: s
old 1: insert into Reservation values(&PNR_NO, &No_of_seats, '&Address', &Contact_No, '&Status')new 1: insert into Reservation values(8,3,'cbt',9090887753,'s')insert into Reservation values(8,3,'cbt',9090887753,'s')*ERROR at line 1:ORA-02291: integrity constraint (SYSTEM.SYS_C004024) violated - parent key not found
JOGINPALLY B.R. ENGINEERING COLLEGE 19
Dept of Computer Science and Engineering 09J21D5818
2.4 UPDATE Table
SQL> update Passenger set age='43' where PNR_NO='2';1 row updated.SQL> select * from Passenger; PNR_NO TICKET_NO NAME AGE SEX PPNO---------- ---------- -------------------- ---------- ---------- --------------- 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 SQL> delete from Passenger where PNR_NO='4';1 row deleted.SQL> select * from Passenger; PNR_NO TICKET_NO NAME AGE SEX PPNO---------- - --------- -------------------- ---------- ---------- --------------- 1 1 SACHIN 12 m sd1234 2 2 rahul 43 m sd3456 3 3 swetha 24 f sdqw34
2.5 DROP Table
SQL> drop table Cancellation;Table dropped.
JOGINPALLY B.R. ENGINEERING COLLEGE 20
Dept of Computer Science and Engineering 09J21D5818
Week7: Practice the fallowing Queries
1. Display Unique PNR_NO of all Passengers
SQL> select PNR_NO from Passenger; PNR_NO ---------- 1 2 3 4 5 6 7
7 rows selected.2. Display all the names of male Passengers
SQL> select Name from Passenger where Sex='m';NAME--------------------SACHINrahulrafisalimriyaz
3. Display Ticket numbers and names of all Passengers
SQL> select Ticket_NO,Name from Passenger; 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.
SQL> select source, destination from Ticket where Journey_Dur>10; 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 ---------- 1
JOGINPALLY B.R. ENGINEERING COLLEGE 21
Dept of Computer Science and Engineering 09J21D5818
6. Find the names of the passenger whose age is between 20 and 40
SQL> select Name from Passenger where age between 20 and 40;
NAME--------------------swetharafiriyazneha
7. Display all the name of the passengers beginning with ‘r’
SQL> select Name from Passenger where Name like 'r%';NAME--------------------rahulrafiriyaz
8. Display the sorted list of Passenger Names
SQL> select Name from Passenger ORDER BY Name;NAME--------------------SACHINneharafirahulriyazsalimswetha7 rows selected.
JOGINPALLY B.R. ENGINEERING COLLEGE 22
Dept of Computer Science and Engineering 09J21D5818
Week8 and week9: Practice queries using Aggregate functions, Group by, having and Creation and Dropping of views
1. Write a query to Display the information present in the Cancellation and Reservation Tables
SQL> select * from Reservation UNION select * from Cancellation; PNR_NO NO_OF_SEATS ADDRESS CONTACT_NO STATUS---------- - ---------- -------------------- ---------- --- -------------- 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 PNR_NO NO_OF_SEATS ADDRESS CONTACT_NO STATUS---------- -- --------- -------------------- ---------- 6 31 swebnht 453212345 s 7 2 dbdhfdbhf 90876543 s 7 3 jklhg 2345671 s14 rows selected.2. Find the distinct PNR_NO that are present
SQL> SELECT PNR_NO, COUNT(*) AS NoOccurances FROM Passenger GROUP BY PNR_NO HAVING COUNT(*)>0;
PNR_NO NOOCCURANCES---------- ------------ 1 1 2 1 3 1 4 1 5 1 6 1 7 1
7 rows selected.
JOGINPALLY B.R. ENGINEERING COLLEGE 23
Dept of Computer Science and Engineering 09J21D5818
3. Find the No of Seats booked for each PNR_NO using GROUP BY Clause.
SQL> select PNR_NO,sum(No_of_seats) from Reservation group by PNR_NO; PNR_NO SUM(NO_OF_SEATS)---------- ---------------- 1 3 6 1 2 2 4 5 5 2 3 6 7 3
7 rows selected.
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='c' group by class having sum(No_of_seats)>1;
CLASS SUM(NO_OF_SEATS)---- ---------------a 13b 7c 2
5. Find the total number of cancelled seats.
SQL> select sum(No_of_seats) from Cancellation;SUM(NO_OF_SEATS)---------------- 22
6. Creating and dropping views
a) CREATE VIEW
SQL> create view male_pass as select PNR_NO,age from Passenger where sex='m';View created.SQL> select * from male_pass;
PNR_NO AGE---------- ---------- 1 12 2 43 4 22 5 45 6 32
JOGINPALLY B.R. ENGINEERING COLLEGE 24
Dept of Computer Science and Engineering 09J21D5818
Create a view from two tables with all columns.SQL> create view v1 as select * from Passenger full natural join Reservation;View created.
b) INSERT
SQL> insert into male_pass values(&PNR_NO,&age);Enter value for pnr_no: 12Enter value for age: 22old 1: insert into male_pass values(&PNR_NO,&age)new 1: insert into male_pass values(12,22)1 row created.
c) DROP VIEW
SQL> drop view male_pass;View dropped.
JOGINPALLY B.R. ENGINEERING COLLEGE 25
Dept of Computer Science and Engineering 09J21D5818
Week10: Create of insert trigger, delete trigger and update trigger.
1. To write a TRIGGER to ensure that Bus table does not contain duplicate of null values in Bus_No column.
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
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:
JOGINPALLY B.R. ENGINEERING COLLEGE 26
Dept of Computer Science and Engineering 09J21D5818
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'
b) Create Trigger updchek before update on Ticket
For Each Row
Begin
If New.Ticket_No>60 Then
Set New.Ticket_No=Ticket_No;
Else
Set New.Ticket_No=0;
End If
End.
SQL> @trigger
Trigger created.
JOGINPALLY B.R. ENGINEERING COLLEGE 27
Dept of Computer Science and Engineering 09J21D5818
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.
JOGINPALLY B.R. ENGINEERING COLLEGE 28
Dept of Computer Science and Engineering 09J21D5818
Week 12: Cursors
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
riyaz
Name of female Passengers are:
swetha
neha
JOGINPALLY B.R. ENGINEERING COLLEGE 29
Dept of Computer Science and Engineering 09J21D5818
PL/SQL procedure successfully completed.
b) To write a Cursor to display List of Passengers from Passenger Table.
DECLARE
cursor c is select PNR_NO, Name, Age, Sex from Passenger ;
i Passenger.PNR_NO%type;
j Passenger.Name%type;
k Passenger.Age%type;
l Passenger.Sex%type;
BEGIN
open c;
dbms_RESULT.put_line('PNR_NO, Name, Age, Sex of Passengers are:= ');
loop
fetch c into i, j, k, l;
exit when c%notfound;
dbms_RESULT.put_line(i||' '||j||' '||k||' '||l);
end loop;
close c;
END;
RESULT:
SQL>@Passenger
PNR_NO NAME AGE SEX
---------- -------------------- ---------- ----------
1 SACHIN 12 m
2 rahul 43 m
3 swetha 24 f
4 rafi 22 m
PL/SQL procedure successfully completed.
JOGINPALLY B.R. ENGINEERING COLLEGE 30
Dept of Computer Science and Engineering 09J21D5818
PART II
COMPILER DESIGN
JOGINPALLY B.R. ENGINEERING COLLEGE 31
Dept of Computer Science and Engineering 09J21D5818
Program 1
Aim: Write A Program to Design Lexical Analyzer.
#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");
while((c=getc(f1))!=EOF)
{
if(isdigit(c))
{
tokenvalue=c-'0';
JOGINPALLY B.R. ENGINEERING COLLEGE 32
Dept of Computer Science and Engineering 09J21D5818
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++;
else
putc(c,f3);
}
fclose(f2);
fclose(f3);
fclose(f1);
printf("\nThe no's in the program are");
for(j=0;j<i;j++)
JOGINPALLY B.R. ENGINEERING COLLEGE 33
Dept of Computer Science and Engineering 09J21D5818
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);
printf("Total no. of lines are:%d",lineno);
}
Output:
Enter the C program
a+b*c
Ctrl-D
The no’s in the program are:
JOGINPALLY B.R. ENGINEERING COLLEGE 34
Dept of Computer Science and Engineering 09J21D5818
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. of lines are: 1
JOGINPALLY B.R. ENGINEERING COLLEGE 35
Dept of Computer Science and Engineering 09J21D5818
Program 2
Aim: Implement the Lexical Analyzer Using Lex Tool.
/* program name is lexp.l */
%{
/* program to recognize a c program */
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* { printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}
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",yytext);}
"/*" {COMMENT = 1;}
/*{printf("\n\n\t%s is a COMMENT\n",yytext);}*/
JOGINPALLY B.R. ENGINEERING COLLEGE 36
Dept of Computer Science and Engineering 09J21D5818
"*/" {COMMENT = 0;}
/* 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);}
%%
int main(int argc,char **argv)
{
if (argc > 1)
{
FILE *file;
file = fopen(argv[1],"r");
if(!file)
{
printf("could not open %s \n",argv[1]);
exit(0);
}
yyin = file;
}
yylex();
JOGINPALLY B.R. ENGINEERING COLLEGE 37
Dept of Computer Science and Engineering 09J21D5818
printf("\n\n");
return 0;
}
int yywrap()
{
return 0;
}
Input:
$vi var.c
#include<stdio.h>
main()
{
int a,b;
}
Output:
JOGINPALLY B.R. ENGINEERING COLLEGE 38
Dept of Computer Science and Engineering 09J21D5818
$lex lex.l
$cc lex.yy.c
$./a.out var.c
#include<stdio.h> is a PREPROCESSOR DIRECTIVE
FUNCTION
main (
)
BLOCK BEGINS
int is a KEYWORD
a IDENTIFIER
b IDENTIFIER
BLOCK ENDS
JOGINPALLY B.R. ENGINEERING COLLEGE 39
Dept of Computer Science and Engineering 09J21D5818
Program 3
Aim:Implementation of Predictive Parser.
#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];
struct entry
keywords[]={"if",KEYWORD,"else",KEYWORD,"for",KEYWORD,"int",KEYWORD,"flo
at",KEYWORD,"double",KEYWORD,"char",KEYWORD,"struct",KEYWORD,"return",KE
YWORD,0,0};
void Error_Message(char *m)
JOGINPALLY B.R. ENGINEERING COLLEGE 40
Dept of Computer Science and Engineering 09J21D5818
{
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;
}
/*void Initialize()
{
struct entry *ptr;
for(ptr=keywords;ptr->token;ptr+1)
insert(ptr->lexptr,ptr->token);
}*/
int lexer()
JOGINPALLY B.R. ENGINEERING COLLEGE 41
Dept of Computer Science and Engineering 09J21D5818
{
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)
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;
}
JOGINPALLY B.R. ENGINEERING COLLEGE 42
Dept of Computer Science and Engineering 09J21D5818
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);
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();
JOGINPALLY B.R. ENGINEERING COLLEGE 43
Dept of Computer Science and Engineering 09J21D5818
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)
{
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()
{
JOGINPALLY B.R. ENGINEERING COLLEGE 44
Dept of Computer Science and Engineering 09J21D5818
int t;
T();
while(1)
{
switch(lookahead)
{
case '+' : t=lookahead;
Match(lookahead);
T();
display(t,NONE);
continue;
case '-' : t=lookahead;
Match(lookahead);
T();
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 ");
JOGINPALLY B.R. ENGINEERING COLLEGE 45
Dept of Computer Science and Engineering 09J21D5818
printf("And place ; at the end\n");
printf("Press Ctrl-Z to terminate\n");
parser();
}
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
JOGINPALLY B.R. ENGINEERING COLLEGE 46
Dept of Computer Science and Engineering 09J21D5818
Program 4
Aim: Design LALR Bottom up Parser.
<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
%%
line: expr '\n' {
printf("%g\n",$1);
};
expr: expr '+' term {$$=$1 + $3 ;}
JOGINPALLY B.R. ENGINEERING COLLEGE 47
Dept of Computer Science and Engineering 09J21D5818
| 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
5.0000
JOGINPALLY B.R. ENGINEERING COLLEGE 48
Dept of Computer Science and Engineering 09J21D5818
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]+)
%%
main\(\) return MAIN;
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);
return NUM;}
\< |
\> |
\>= |
JOGINPALLY B.R. ENGINEERING COLLEGE 49
Dept of Computer Science and Engineering 09J21D5818
\<= |
== {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];
int top;
}stk;
int Index=0,tIndex=0,StNo,Ind,tInd;
extern int LineNo;
%}
%union
JOGINPALLY B.R. ENGINEERING COLLEGE 50
Dept of Computer Science and Engineering 09J21D5818
{
char var[10];
}
%token <var> NUM VAR RELOP
%token MAIN IF ELSE WHILE TYPE
%type <var> EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP
%left '-' '+'
%left '*' '/'
%%
PROGRAM : MAIN BLOCK
;
BLOCK: '{' CODE '}'
;
CODE: BLOCK
| STATEMENT CODE
| STATEMENT
;
STATEMENT: DESCT ';'
| ASSIGNMENT ';'
| CONDST
| WHILEST
;
DESCT: TYPE VARLIST
;
VARLIST: VAR ',' VARLIST
| VAR
;
JOGINPALLY B.R. ENGINEERING COLLEGE 51
Dept of Computer Science and Engineering 09J21D5818
ASSIGNMENT: VAR '=' EXPR{
strcpy(QUAD[Index].op,"=");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,$1);
strcpy($$,QUAD[Index++].result);
}
;
EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);}
| EXPR '-' EXPR {AddQuadruple("-",$1,$3,$$);}
| EXPR '*' EXPR {AddQuadruple("*",$1,$3,$$);}
| EXPR '/' EXPR {AddQuadruple("/",$1,$3,$$);}
| '-' EXPR {AddQuadruple("UMIN",$2,"",$$);}
| '(' EXPR ')' {strcpy($$,$2);}
| VAR
| NUM
;
CONDST: IFST{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
| IFST ELSEST
;
IFST: IF '(' CONDITION ')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
JOGINPALLY B.R. ENGINEERING COLLEGE 52
Dept of Computer Science and Engineering 09J21D5818
push(Index);
Index++;
}
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();
push(tInd);
sprintf(QUAD[Ind].result,"%d",Index);
}
BLOCK{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$);
StNo=Index-1;
}
| VAR
| NUM
;
WHILEST: WHILELOOP{
Ind=pop();
JOGINPALLY B.R. ENGINEERING COLLEGE 53
Dept of Computer Science and Engineering 09J21D5818
sprintf(QUAD[Ind].result,"%d",StNo);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
WHILELOOP: WHILE '(' CONDITION ')' {
strcpy(QUAD[Index].op,"==");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"FALSE");
strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK {
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");
JOGINPALLY B.R. ENGINEERING COLLEGE 54
Dept of Computer Science and Engineering 09J21D5818
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);
}
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);
}
JOGINPALLY B.R. ENGINEERING COLLEGE 55
Dept of Computer Science and Engineering 09J21D5818
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);
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
JOGINPALLY B.R. ENGINEERING COLLEGE 56
Dept of Computer Science and Engineering 09J21D5818
{
c=a+b;
}
}
Output:
$lex int.l$yacc –d int.y$gcc lex.yy.c y.tab.c –ll –lm$./a.out test.c
Pos Operator Arg1 Arg2 Result
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
JOGINPALLY B.R. ENGINEERING COLLEGE 57
Dept of Computer Science and Engineering 09J21D5818
___________________________________________________
Program 6
Aim: A Program to Generate Machine Code.
#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))
fprintf(fp2,"\nlabel#%d",i);
if(strcmp(op,"print")==0)
JOGINPALLY B.R. ENGINEERING COLLEGE 58
Dept of Computer Science and Engineering 09J21D5818
{
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;
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);
JOGINPALLY B.R. ENGINEERING COLLEGE 59
Dept of Computer Science and Engineering 09J21D5818
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);
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;
}
JOGINPALLY B.R. ENGINEERING COLLEGE 60
Dept of Computer Science and Engineering 09J21D5818
}
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])
return 1;
}
return 0;
}
Input:
$vi int.txt
=t1 2
[]=a 0 1
[]=a 1 2
JOGINPALLY B.R. ENGINEERING COLLEGE 61
Dept of Computer Science and Engineering 09J21D5818
[]=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
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
JOGINPALLY B.R. ENGINEERING COLLEGE 62
Dept of Computer Science and Engineering 09J21D5818
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
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
JOGINPALLY B.R. ENGINEERING COLLEGE 63
Dept of Computer Science and Engineering 09J21D5818
JOGINPALLY B.R. ENGINEERING COLLEGE 64