Anda di halaman 1dari 53

Roll No: 10M81D5803

Week1: E-R model


Analyze 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 attributes
Bus:
Bus_No
Source
Destination
J_day
Type

: varchar(10) (primary key)


: varchar(20)
: varchar(20)
: varchar(3)
: varchar(3)

Passenger:
PNR_No
Ticket_No
Name
Age
Sex
PPNO

:
:
:
:
:
:

Reservation:
PNR_No
j_date
No_of_seats
Address
Contact_No
Status
Class

: number(9) (foreign key)


: date
: integer(8)
: varchar(50)
: number(9)
: char(2)
: varchar(2)

Cancel:
PNR_No
j_date
No_of_seats
Address
Contact_No
Status

: number(9)(foreign key)
: date
: integer(8)
: varchar(50)
: number(9)
: char(2)

Ticket:
Ticket_No
j_date
Age
Sex
Source
Destination
xDep_time

:
:
:
:
:
:
:

number(9) (primary key)


number(9)
varchar(15)
integer(4)
char(2) ; Male/Female
varchar(15)

number(9)(primary key)
date
int(4)
char(10)
varchar(20)
varchar(20)
varchar(4)

Page No:

Roll No: 10M81D5812

Week2: Concept design with E-R model.


Relate the entities appropriately. Apply cardinalities for each relation.

Page No:

Roll No: 10M81D5812

Week3: Relational Model


Represent all entities in a tabular fashion. Represent all relationships in a
tabular fashion.
The tabular representation of the above entities and relationships:
BUS:
Bus_no

Source

Destination

J_day

type

Passenger:
Pnr_No

Ticket_no

Name

Age

Sex

PPNO

Reservation:
Pnr_No

Journey_date

No_of_seat
s

Address

Contact_No

Status

Class

Cancel:
Pnr_No

Journey_date

No_of_seats

Address

Contact_N
o

Status

Ticket:
Ticket_N
o

J_date

Age

sex

source

Destinatio
n

Dep_tim
e

Page No:

Roll No: 10M81D5812

Week5: Installation of MySQL and practicing DDL commands.


1. Steps for installing MySQL
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.5 setup wizard. The setup wizard will install
MySQL Server 5.5 on your computer. To continue, click next.

Step 3: Accept the License Agreement and Choose the setup type that
best suits your needs. For common program features select Typical and its
recommended for general use. To continue, click next.

Page No:

Roll No: 10M81D5812

Step 4: This wizard is ready to begin installation. To continue, click next.

Step 5: The program features you selected are being installed. Please wait
while the setup wizard installs MySQL 5.5. This may take several minutes.

Page No:

Roll No: 10M81D5812

Step 6: To continue, click next.

Step 7: To continue, click next.

Page No:

Roll No: 10M81D5812

Step 8: Wizard Completed. Setup has finished installing MySQL 5.5. Check
the configure the MySQL server now to continue. Click Finish to exit the
wizard

Step 9: The configuration wizard will allow you to configure the MySQL
Server 5.5 server instance. To continue, click next.

Page No:

Roll No: 10M81D5812

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.

Step 11: Check on the install as windows service and include bin
directory in windows path. To continue, click next.

Page No:

Roll No: 10M81D5812

Step 12: Please set the security options by entering the root password and
confirm retype the password. To continue, click next.

Step 13: Ready to execute? Clicks execute to continue.

Page No:

Roll No: 10M81D5812

Step 14: Processing configuration in progress.

Step 15: Configuration file created. Windows service MySQL5.5 installed.


Press finish to close the wizard.

Page No:

Roll No: 10M81D5812

CREATE Database:
mysql> create database roadways;
Query OK, 1 row affected (0.00 sec)
mysql>
CREATE Tables
Step 1:

connect to a database which we created in the above step.

mysql> \r roadways
(or) \u roadways
Connection id: 3
Current database: roadways
Step 2: to create tables:
mysql> create table passenger (pnr_no integer(9) PRIMARY KEY,ticket_no
integer(9), name varchar(20), age int(4), sex char(10), ppno varchar(15));
Query OK, 0 rows affected (0.13 sec)
mysql> desc passenger;
+-----------+-------------+------+-----+---------+-------+
| Field
| Type
| Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+-------+
| pnr_no
| int(9)
| NO
| PRI |
|
|
| ticket_no | int(9)
| YES |
| NULL
|
|
| name
| varchar(20) | YES |
| NULL
|
|
| age
| int(4)
| YES |
| NULL
|
|
| sex
| char(10)
| YES |
| NULL
|
|
| ppno
| varchar(15) | YES |
| NULL
|
|
+-----------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

mysql> create table reservation(pnr_no int(9),jdate date,no_of_seats int(8),


address varchar(50),contact_no int(12),status char(3));
Query OK, 0 rows affected (0.06 sec)
mysql> desc reservation;
+-------------+-------------+------+-----+---------+-------+
| Field
| Type
| Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| pnr_no
| int(9)
| YES |
| NULL
|
|
| jdate
| date
| YES |
| NULL
|
|
| no_of_seats | int(8)
| YES |
| NULL
|
|
| address
| varchar(50) | YES |
| NULL
|
|
| contact_no | int(12)
| YES |
| NULL
|
|
| status
| char(3)
| YES |
| NULL
|
|
+-------------+-------------+------+-----+---------+-------+
6 rows in set (0.02 sec)

Page No:

Roll No: 10M81D5812

mysql> create table bus(bus_no varchar(5) PRIMARY KEY, source


varchar(20), destination varchar(20));
Query OK, 0 rows affected (0.05 sec)
mysql> desc bus;
+-------------+-------------+------+-----+---------+-------+
| Field
| Type
| Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| bus_no
| varchar(5) | NO
| PRI |
|
|
| source
| varchar(20) | YES |
| NULL
|
|
| destination | varchar(20) | YES |
| NULL
|
|
| j_day
| varchar(3) | YES |
| NULL
|
|
| type
| varchar(3) | YES |
| NULL
|
|
+-------------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

mysql> create table cancel(pnr_no int(9),jdate date,no_of_seats int(8),


address varchar(50), contact_no int(12),status char(2));
Query OK, 0 rows affected (0.06 sec)
mysql> desc cancel;
+-------------+-------------+------+-----+---------+-------+
| Field
| Type
| Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| pnr_no
| int(9)
| YES |
| NULL
|
|
| jdate
| date
| YES |
| NULL
|
|
| no_of_seats | int(8)
| YES |
| NULL
|
|
| address
| varchar(50) | YES |
| NULL
|
|
| contact_no | int(12)
| YES |
| NULL
|
|
| status
| char(2)
| YES |
| NULL
|
|
+-------------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

mysql> create table ticket(ticket_no int(9) primary key, age int(3), sex
varchar (2)not null, source varchar(20), destination varchar(20), dep_time
varchar(4));
Query OK, 0 rows affected (0.05 sec)
mysql> desc ticket;
+-------------+-------------+------+-----+---------+-------+
| Field
| Type
| Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| ticket_no
| int(9)
| NO
| PRI |
|
|
| age
| int(3)
| YES |
| NULL
|
|
| sex
| varchar(2) | NO
|
|
|
|
| source
| varchar(20) | YES |
| NULL
|
|
| destination | varchar(20) | YES |
| NULL
|
|
| dep_time
| varchar(4) | YES |
| NULL
|
|
+-------------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

Page No:

Roll No: 10M81D5812

Week 6: Practicing DML commands


1.1

ALTER Table

mysql> alter table reservation add foreign key (pnr_no) references


passenger(pnr_no);
Query OK, 0 rows affected (0.14 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> alter table cancel add foreign key (pnr_no) references
passenger(pnr_no);
Query OK, 0 rows affected (0.13 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> alter table ticket add constraint check_age check(age>18);
Query OK, 0 rows affected (0.11 sec)
Records: 0 Duplicates: 0 Warnings: 0
1.2

INSERT

mysql> insert into passenger(pnr_no,ticket_no,name,age,sex)


values(101,1,"Ramakrishna",28,"M");
Query OK, 1 row affected (0.02 sec)
mysql> insert into passenger(pnr_no,ticket_no,name,age,sex)
values(102,2,"Ashok",28,"M");
Query OK, 1 row affected (0.02 sec)
mysql> insert into passenger(pnr_no,ticket_no,name,age,sex)
values(103,3,"Bhavani",27,"F");
Query OK, 1 row affected (0.02 sec)
mysql> insert into passenger(pnr_no,ticket_no,name,age,sex)
values(104,4,"Jyothi",22,"F");
Query OK, 1 row affected (0.02 sec)
mysql> insert into passenger(pnr_no,ticket_no,name,age,sex)
values(105,5,"Saritha",18,"F");
Query OK, 1 row affected (0.02 sec)
mysql> insert into passenger(pnr_no,ticket_no,name,age,sex)
values(106,6,"Raghu",28,"M");
Query OK, 1 row affected (0.02 sec)
mysql> select * from passenger;
+--------+-----------+-------------+------+------+------+
| pnr_no | ticket_no | name
| age | sex | ppno |
+--------+-----------+-------------+------+------+------+
|
101 |
1 | Ramakrsihna |
28 | M
| NULL |
|
102 |
2 | Ashok
|
28 | M
| NULL |
|
103 |
3 | Bhavani
|
27 | F
| NULL |
|
104 |
4 | Jyothi
|
22 | F
| NULL |
|
105 |
5 | Saritha
|
18 | F
| NULL |
|
106 |
6 | Raghu
|
28 | M
| NULL |
+--------+-----------+-------------+------+------+------+
6 rows in set (0.00 sec)

mysql> insert into bus(bus_no,source,destination)


values(2233,"GNT","HYD");
Page No:

Roll No: 10M81D5812

Query OK, 1 row affected (0.01 sec)


mysql> insert into bus(bus_no,source,destination)
values(2244,"GNT","TPTY");
Query OK, 1 row affected (0.02 sec)
mysql> insert into bus(bus_no,source,destination)
values(2255,"GNT","BZA");
Query OK, 1 row affected (0.02 sec)
mysql> insert into bus(bus_no,source,destination) values(2266,"GNT","VSP");
Query OK, 1 row affected (0.03 sec)
mysql> insert into bus(bus_no,source,destination)
values(2277,"GNT","KKD");
Query OK, 1 row affected (0.03 sec)
mysql> select * from bus;
+--------+--------+-------------+
| bus_no | source | destination |
+--------+--------+-------------+
| 2233
| GNT
| HYD
|
| 2244
| GNT
| TPTY
|
| 2255
| GNT
| BZA
|
| 2266
| GNT
| VSP
|
| 2277
| GNT
| KKD
|
+--------+--------+-------------+
5 rows in set (0.00 sec)

mysql> insert into reservation(pnr_no, jdate,no_of_seats, address,


contact_no, status) values(101,'2011-08-17',5,"KODAD",
2266114,"CNF");
Query OK, 1 row affected (0.02 sec)
mysql> insert into reservation(pnr_no, jdate,no_of_seats, address,
contact_no, status) values(102,'2011-08-17',4,"NEHRU NAGAR,
NALGOND", 2266414,"CNF");
Query OK, 1 row affected (0.02 sec)
mysql> insert into reservation(pnr_no, jdate,no_of_seats, address,
contact_no, status) values(103,'2011-08-17',6,"ARUNDELPET,
HYDBAD", 263415,"CNF");
Query OK, 1 row affected (0.03 sec)
mysql> insert into reservation(pnr_no, jdate,no_of_seats, address,
contact_no, status) values(104,'2011-08-17',2,"BRODIPET,
SECBAD",261545,"CNF");
Query OK, 1 row affected (0.01 sec)
mysql> insert into reservation(pnr_no, jdate,no_of_seats, address,
contact_no, status) values(105,'2011-08-17',2,"KHAMMAM",
261534,"CNF");
Query OK, 1 row affected (0.02 sec)
mysql> SELECT * FROM RESERVATION;
+--------+------------+-------------+-----------------+------------+--------+
| pnr_no | jdate
| no_of_seats | address
| contact_no | status |
+--------+------------+-------------+-----------------+------------+--------+
|
101 | 2011-08-17 |
5 | KODAD
|
2266114 | CNF
|
|
102 | 2011-08-17 |
4 | NEHRU NAGAR,NLD |
2266414 | CNF
|
|
103 | 2011-08-17 |
6 | ARUNDELPET, HYD |
263415 | CNF
|
|
104 | 2011-08-17 |
2 | BRODIPET, SECBAD|
261545 | CNF
|

Page No:

Roll No: 10M81D5812

|
105 | 2011-08-17 |
2 | KHAMMAM
|
261534 | CNF
|
+--------+------------+-------------+-----------------+------------+--------+
5 rows in set (0.00 sec)

1.3

UPDATE Table:

mysql> update passenger set age=22 where ticket_no=5;


Query OK, 1 row affected (0.03 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> update passenger set name="M.Ramakrishna" where pnr_no=101;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from passenger;
+--------+-----------+---------------+------+------+------+
| pnr_no | ticket_no | name
| age | sex | ppno |
+--------+-----------+---------------+------+------+------+
|
101 |
1 | Ramakrishna
|
28 | M
| NULL |
|
102 |
2 | Ashok
|
28 | M
| NULL |
|
103 |
3 | Bhavani
|
27 | F
| NULL |
|
104 |
4 | Jyothi
|
22 | F
| NULL |
|
105 |
5 | Saritha
|
22 | F
| NULL |
|
106 |
6 | Raghu
|
28 | M
| NULL |
+--------+-----------+---------------+------+------+------+
6 rows in set (0.00 sec)

1.4 Delete from table:


mysql> CREATE TABLE d_bus LIKE roadways.bus;
mysql> INSERT d_bus SELECT * FROM bus;
mysql> select * from d_bus;
+--------+--------+-------------+
| bus_no | source | destination |
+--------+--------+-------------+
| 2233
| GNT
| HYD
|
| 2244
| GNT
| TPTY
|
| 2255
| GNT
| BZA
|
| 2266
| GNT
| VSP
|
| 2277
| GNT
| KKD
|
+--------+--------+-------------+

5 rows in set (0.00 sec)


mysql> delete from d_bus where destination="KKD";
Query OK, 1 row affected (0.02 sec)
mysql> select * from d_bus;
+--------+--------+-------------+
| bus_no | source | destination |

Page No:

Roll No: 10M81D5812

+--------+--------+-------------+
| 2233
| GNT
| HYD
|
| 2244
| GNT
| TPTY
|
| 2255
| GNT
| BZA
|
| 2266
| GNT
| VSP
|
+--------+--------+-------------+

4 rows in set (0.00 sec)


1.5

Drop table:

mysql> show tables;


+--------------------+
| Tables_in_roadways |
+--------------------+
| bus
|
| cancel
|
| d_bus
|
| passenger
|
| reservation
|
| ticket
|
+--------------------+
6 rows in set (0.00 sec)

mysql> drop table d_bus;


Query OK, 0 rows affected (0.03 sec)
mysql> show tables;
+--------------------+
| Tables_in_roadways |
+--------------------+
| bus
|
| cancel
|
| passenger
|
| reservation
|
| ticket
|
+--------------------+
5 rows in set (0.00 sec)

Page No:

Roll No: 10M81D5812

Week7: Practice the following Queries


1) Display unique PNR_no of all passengers
mysql> select pnr_no from passenger;
+--------+
| pnr_no |
+--------+
|
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
+--------+
6 rows in set (0.03 sec)

2) Display all the names of male passengers.


mysql> select name from passenger where sex="M";
+-------------+
| name
|
+-------------+
| Ramakrishna |
| Ashok
|
| Raghu
|
+-------------+
3 rows in set (0.00 sec)

3) Display the ticket numbers and names of all the passengers.


mysql> select ticket_no,name from passenger;
+-----------+-------------+
| ticket_no | name
|
+-----------+-------------+
|
1 | Ramakrishna |
|
2 | Ashok
|
|
3 | Bhavani
|
|
4 | Jyothi
|
|
5 | Saritha
|
|
6 | Raghu
|
+-----------+-------------+
6 rows in set (0.00 sec)

4) Display the source and destination having journey time more


than 10 hours.
mysql> select source,destination from ticket where dep_time>10;
+--------+-------------+
| source | destination |
+--------+-------------+
| GNT
| VSP
|
| GNT
| HYD
|
+--------+-------------+
2 rows in set (0.00 sec)

5) Find the ticket numbers of the passengers who name start


with A and ends with K.
mysql> select * from passenger where name REGEXP '^[a].*k$';
+--------+-----------+-------+------+------+------+
| pnr_no | ticket_no | name | age | sex | ppno |
+--------+-----------+-------+------+------+------+
|
102 |
2 | Ashok |
28 | M
| NULL |
|
107 |
7 | alok |
16 | M
| NULL |
+--------+-----------+-------+------+------+------+
2 rows in set (0.00 sec)

Page No:

Roll No: 10M81D5812

6) Find the names of passengers who age is between 20 and 28.


mysql> select * from passenger where age>20 and age<28;
+--------+-----------+---------+------+------+------+
| pnr_no | ticket_no | name
| age | sex | ppno |
+--------+-----------+---------+------+------+------+
|
103 |
3 | Bhavani |
27 | F
| NULL |
|
104 |
4 | Jyothi |
22 | F
| NULL |
|
105 |
5 | Saritha |
22 | F
| NULL |
+--------+-----------+---------+------+------+------+
3 rows in set (0.00 sec)

7) Display all the passengers names beginning with A.


mysql> select * from passenger where name like 'a%';
+--------+-----------+-------+------+------+------+
| pnr_no | ticket_no | name | age | sex | ppno |
+--------+-----------+-------+------+------+------+
|
102 |
2 | Ashok |
28 | M
| NULL |
|
107 |
7 | alok |
16 | M
| NULL |
+--------+-----------+-------+------+------+------+
2 rows in set (0.00 sec)

8) Display the sorted list of passengers names


mysql> select * from passenger order by name;
+--------+-----------+-------------+------+------+------+
| pnr_no | ticket_no | name
| age | sex | ppno |
+--------+-----------+-------------+------+------+------+
|
107 |
7 | alok
|
16 | M
| NULL |
|
102 |
2 | Ashok
|
28 | M
| NULL |
|
103 |
3 | Bhavani
|
27 | F
| NULL |
|
104 |
4 | Jyothi
|
22 | F
| NULL |
|
106 |
6 | Raghu
|
28 | M
| NULL |
|
101 |
1 | Ramakrishna |
28 | M
| NULL |
|
108 |
8 | revok
|
16 | M
| NULL |
|
105 |
5 | Saritha
|
22 | F
| NULL |
+--------+-----------+-------------+------+------+------+
8 rows in set (0.00 sec)

9) Display the
Wednesday

Bus

numbers

that

travel

on

Sunday

and

mysql> select * from bus where j_day="SUN" || j_day="WED";


+--------+--------+-------------+-------+------+
| bus_no | source | destination | j_day | type |
+--------+--------+-------------+-------+------+
| 2222
| KDD
| TYTY
| WED
| AC
|
| 2266
| GNT
| VSP
| SUN
| AC
|
| 2299
| KDD
| RYJ
| WED
| NAC |
| 3333
| KDD
| MAS
| SUN
| NAC |
+--------+--------+-------------+-------+------+
4 rows in set (0.00 sec)
Page No:

Roll No: 10M81D5812

10) Display the details of passengers who are traveling either in AC


or NON_AC (Using only IN operator)
mysql> select passenger.name, reservation.address,ticket.age from
passenger, reservation,ticket where
passenger.pnr_no=reservation.pnr_no and
passenger.pnr_no=ticket.ticket_no and ticket.b_type in
('AC','NAC');
+-------------+---------------------+------+
| name
| address
| age |
+-------------+---------------------+------+
| Ramakrishna | GUNTUR
|
28 |
| Ashok
| NEHRU NAGAR, GUNTUR |
28 |
| Bhavani
| ARUNDELPET, GUNTUR |
27 |
| Jyothi
| BRODIPET, GUNTUR
|
22 |
| Saritha
| KHAMMAM
|
22 |
| Raghu
| KODAD
|
45 |
+-------------+---------------------+------+
6 rows in set (0.00 sec)

Page No:

Roll No: 10M81D5812

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
mysql> select * from cancel union select * from reservation;
+--------+------------+-----------+---------------------+------------+--------+
| pnr_no | jdate
| noofseats | address
| contact_no | status |
+--------+------------+-----------+---------------------+------------+--------+
|
101 | 2011-08-22 |
2 | GUNTUR
|
2266114 | CN
|
|
108 | 2011-08-22 |
2 | KHAMMAM
|
6523456 | CN
|
|
107 | 2011-08-22 |
1 | KODAD
|
234551 | CN
|
|
101 | 2011-08-17 |
5 | GUNTUR
|
2266114 | CNF
|
|
102 | 2011-08-17 |
4 | NEHRU NAGAR, GUNTUR |
2266414 | CNF
|
|
103 | 2011-08-17 |
6 | ARUNDELPET, GUNTUR |
263415 | CNF
|
|
104 | 2011-08-17 |
2 | BRODIPET, GUNTUR
|
261545 | CNF
|
|
105 | 2011-08-17 |
2 | KHAMMAM
|
261534 | CNF
|
|
106 | 2011-08-22 |
2 | KODAD
|
234561 | CNF
|
|
107 | 2011-08-22 |
2 | KODAD
|
234551 | CNF
|
|
108 | 2011-08-22 |
5 | KHAMMAM
|
6532456 | CNF
|
+--------+------------+-----------+---------------------+------------+--------+
11 rows in set (0.00 sec)

2.

Find the distinct PNR_NO that are present


mysql> select pnr_no, count(*) as no_of_occurances from passenger
group by pnr_no having count(*)>0;
+--------+------------------+
| pnr_no | no_of_occurances |
+--------+------------------+
|
101 |
1 |
|
102 |
1 |
|
103 |
1 |
|
104 |
1 |
|
105 |
1 |
|
106 |
1 |
|
107 |
1 |
|
108 |
1 |
+--------+------------------+
8 rows in set (0.00 sec)

3. Find the No of Seats booked for each PNR_NO using GROUP BY


Clause.
mysql> select pnr_no, sum(no_of_seats) from reservation group by
pnr_no;
+--------+------------------+
| pnr_no | sum(no_of_seats) |
+--------+------------------+
|
101 |
5 |
|
102 |
4 |
|
103 |
6 |
|
104 |
2 |
|
105 |
2 |
|
106 |
2 |
|
107 |
2 |
|
108 |
5 |
+--------+------------------+
8 rows in set (0.00 sec)

Page No:

Roll No: 10M81D5812

4.
Find the number of seats booked in each class where
the number of seats is greater than 1.
mysql> select * from reservation;
+--------+------------+-------------+----------+------------+--------+-------+
| pnr_no | jdate
| no_of_seats | address | contact_no | status | class |
+--------+------------+-------------+----------+------------+--------+-------+
|
101 | 2011-08-07 |
4 | GUNTUR
|
235456 | CNF
| A
|
|
102 | 2011-08-17 |
5 | KODAD
|
325456 | CNF
| A
|
|
103 | 2011-08-17 |
4 | KODAD
|
325478 | CNF
| B
|
|
104 | 2011-08-07 |
4 | GUNTUR
|
3456314 | CNF
| B
|
|
105 | 2011-08-22 |
7 | NALGONDA |
4456314 | CNF
| B
|
|
106 | 2011-08-22 |
7 | KHAMMAM |
4564314 | CNF
| B
|
|
107 | 2011-08-22 |
3 | KHAMMAM |
4614314 | CNF
| A
|
|
108 | 2011-08-22 |
3 | NALGONDA |
4684314 | CNF
| A
|
|
108 | 2011-08-22 |
8 | NALGONDA |
4684314 | CNF
| A
|
|
109 | 2011-08-23 |
1 | NALGONDA |
2684314 | CNF
| C
|
|
110 | 2011-08-23 |
1 | HYD
|
6284314 | CNF
| D
|
|
111 | 2011-08-22 |
2 | HYD
|
6824314 | CNF
| E
|
+--------+------------+-------------+----------+------------+--------+-------+
12 rows in set (0.00 sec)

mysql> select class,sum(no_of_seats) from reservation where


class='A' or class="B" or class="C" or class="D" or class="E"
group by class having sum(no_of_seats)>1;
+-------+------------------+
| class | sum(no_of_seats) |
+-------+------------------+
| A
|
23 |
| B
|
22 |
| E
|
2 |
+-------+------------------+
3 rows in set (0.00 sec)

5.

Find the total number of cancelled seats.


mysql> select sum(no_of_seats) from cancel;
+------------------+
| sum(no_of_seats) |
+------------------+
|
5 |
+------------------+
1 row in set (0.00 sec)

Page No:

Roll No: 10M81D5812

Creating and dropping views


a) CREATE VIEW
mysql> create or replace view male_pass as select pnr_no,
age,sex from passenger where sex='M';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT * FROM male_pass;
+--------+------+------+
| pnr_no | age | sex |
+--------+------+------+
|
101 |
28 | M
|
|
102 |
28 | M
|
|
106 |
28 | M
|
|
107 |
16 | M
|
|
108 |
16 | M
|
+--------+------+------+
6 rows in set (0.00 sec)

b) INSERT
mysql> insert into male_pass(pnr_no,age,sex) values(201,22,M);
Query OK, 1 row affected (0.01 sec)
mysql> insert into male_pass(pnr_no,age,sex) values(202,25,F);
Query OK, 1 row affected (0.01 sec)
mysql> insert into male_pass(pnr_no,age,sex) values(201,24,F);
Query OK, 1 row affected (0.01 sec)
c) Display VIEW
mysql> SELECT * FROM male_pass;
+--------+------+------+
| pnr_no | age | sex |
+--------+------+------+
|
101 |
28 | M
|
|
102 |
28 | M
|
|
106 |
28 | M
|
|
107 |
16 | M
|
|
108 |
16 | M
|
|
201 |
22 | M
|
+--------+------+------+
6 rows in set (0.00 sec)

d) DROP VIEW
mysql> drop view male_pass;
Query OK, 0 row affected (0.01 sec)

Page No:

Roll No: 10M81D5812

Week10: Create of Insert trigger, Update trigger and Delete


trigger.
1.
table: BUS

Write a TRIGGER to maintain the log details of the

a) Trigger for Insert


CREATE OR RELPLACE TRIGGER trig1 before insert on Bus for each row

mysql> create table bus_log(bus_no varchar(5),j_day varchar(3), type


varchar(3), lastinserted time);
Query OK, 0 rows affected (0.08 sec)
mysql> delimiter $$
mysql>
->
->
->
->

create trigger bus_trig


after insert on bus
for each row
BEGIN
insert into bus_log values(new.bus_no,new.j_day, new.type,
curtime());
-> END$$
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> SELECT * FROM BUS_LOG;
Empty set (0.00 sec)
mysql> insert into bus values(3355,"RAJ","MAS","MON","AC");
Query OK, 1 row affected (0.03 sec)
mysql> SELECT * FROM BUS_LOG;
+--------+-------+------+--------------+
| bus_no | j_day | type | lastinserted |
+--------+-------+------+--------------+
| 3355
| MON
| AC
| 15:34:34
|
+--------+-------+------+--------------+
1 row in set (0.00 sec)

b) Update trigger:
mysql> select * from ticket;
+-----------+------+-----+--------+-------------+----------+--------+
| ticket_no | age | sex | source | destination | dep_time | b_type |
+-----------+------+-----+--------+-------------+----------+--------+
|
101 |
28 | M
| GNT
| VSP
|
10 | AC
|
|
102 |
28 | M
| GNT
| BZA
|
11 | NAC
|
|
103 |
27 | F
| GNT
| KKD
|
11 | AC
|
|
104 |
22 | F
| GNT
| HYD
|
12 | AC
|
+-----------+------+-----+--------+-------------+----------+--------+
5 rows in set (0.01 sec)

mysql> delimiter $$

Page No:

Roll No: 10M81D5812

mysql> create trigger tickt_updcheck 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$$
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> insert into ticket values(20,23,"M","GNT","BZA",20,"NAC");
Query OK, 1 row affected (0.03 sec)
mysql> SELECT * FROM TICKET;
+-----------+------+-----+--------+-------------+----------+--------+
| ticket_no | age | sex | source | destination | dep_time | b_type |
+-----------+------+-----+--------+-------------+----------+--------+
|
20 |
23 | M
| GNT
| BZA
|
20 | NAC
|
|
101 |
28 | M
| GNT
| VSP
|
10 | AC
|
|
102 |
28 | M
| GNT
| BZA
|
11 | NAC
|
|
103 |
27 | F
| GNT
| KKD
|
11 | AC
|
|
104 |
22 | F
| GNT
| HYD
|
12 | AC
|
+-----------+------+-----+--------+-------------+----------+--------+
5 rows in set (0.00 sec)

mysql> update ticket set age=20 where ticket_no=20;


Query OK, 1 row affected (0.03 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from ticket;
+-----------+------+-----+--------+-------------+----------+--------+
| ticket_no | age | sex | source | destination | dep_time | b_type |
+-----------+------+-----+--------+-------------+----------+--------+
|
0 |
20 | M
| GNT
| BZA
|
20 | NAC
|
|
101 |
28 | M
| GNT
| VSP
|
10 | AC
|
|
102 |
28 | M
| GNT
| BZA
|
11 | NAC
|
|
103 |
27 | F
| GNT
| KKD
|
11 | AC
|
|
104 |
22 | F
| GNT
| HYD
|
12 | AC
|
+-----------+------+-----+--------+-------------+----------+--------+
5 rows in set (0.00 sec)

c) Delete Trigger :
mysql> drop trigger bus_trig;
Query OK, 0 rows affected (0.01 sec)

Page No:

Roll No: 10M81D5812

Week 11: Procedures


Creation of stored procedure, Execution of procedure and modification of
procedure. Practice procedures using the above database.
How to Create a Stored Procedure in MySQL
A procedure can be creating in MySQL by using the following syntax:
CREATE PROCEDURE ProcedureName()
(
param1 int,
param2 varchar(20)
)
BEGIN
Text of stored procedure here
END;
Note that the name of the parameters cannot be the same as the names of
any columns in tables that are referenced within the stored procedure.
Ex:

mysql> delimiter $$
mysql> create procedure myproc()
-> BEGIN
-> SELECT count(ticket_no) from ticket where age>=27;
-> END $$
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;

How to Call a Stored Procedure in MySQL


mysql> call ProcedureName()
mysql> call myproc();
+------------------+
| count(ticket_no) |
+------------------+
|
4 |
+------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Modify a Stored Procedure


MySQL provides an ALTER PROCEDURE statement to modify a routine,
but only allows for the ability to change certain characteristics. If you need
to alter the body or the parameters, you must drop and recreate the
procedure.

Page No:

Roll No: 10M81D5812

Delete a Stored Procedure


DROP PROCEDURE IF EXISTS ProcedureName ;

Page No:

Roll No: 10M81D5803

Delete a Stored Procedure


DROP PROCEDURE IF EXISTS ProcedureName ;
mysql> show procedure status;
+----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+
| Db
| Name
| Type
| Definer
| Modified
| Created
| Security_type | Comment |
+----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+
| roadways | myproc | PROCEDURE | root@localhost | 2011-09-02 11:50:24 | 2011-09-02 11:50:24 | DEFINER
|
|
+----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+
1 row in set (0.00 sec)
mysql> drop procedure if exists myproc;
Query OK, 0 rows affected (0.02 sec)
mysql> show procedure status;
Empty set (0.00 sec)

Page No:

Roll No: 10M81D5803

Week 12: Cursors:


We will define a cursor that defines a result set. Open the cursor to
establish the Result set. Fetch the data into local variables as needed from
the cursor one Row at a time. Then we will close the cursor.
A) Write a Cursor to display the list of Male and Female
Passengers.
mysql> DELIMITER $$
mysql>
->
->
->
->
->
->
->
->
->
->
->
->
->
->
->
->

create procedure male_female_list()


BEGIN
declare mf varchar(3);
declare na varchar(30);
declare cur1 cursor for select name,sex from passenger where sex="m";
declare cur2 cursor for select name,sex from passenger where sex="f";
open cur1;
select 'Male Passenger Names List is:';
fetch cur1 into na, mf;
select name from passenger where sex=mf;
close cur1;
open cur2;
select 'Female Passengers Names List is:';
fetch cur2 into na,mf;
select name from passsenger where sex=mf;
close cur2;
end $$
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;
mysql> call male_female_list();
+-------------------------------+
| Male Passenger Names List is: |
+-------------------------------+
| name
|
+-------------------------------+
| Ramakrishna
|
| Ashok
|
| Raghu
|
| alok
|
| revok
|
| Venu
|
+-------------------------------+
6 rows in set (0.02 sec)
+----------------------------------+
| Female Passengers Names List is: |
+----------------------------------+
| name
|
+----------------------------------+
| Bhavani
|
| Jyothi
|
| Saritha
|
| Renu
|
| Aarshitha
|
+----------------------------------+
5 rows in set (0.02 sec)
Query OK, 0 rows affected (0.02 sec)

Page No:

Roll No: 10M81D5803

B) Write a cursor to print the list of buses available to RAJAMANDRY


(RAJ)
mysql> delimiter $$
mysql>
->
->
->
->

create procedure bus_details()


begin
declare busn varchar(10);
declare dest varchar(20);
declare cur3 cursor for select bus_no, destination from bus where
destination="RAJ";
-> OPEN CUR3;
-> FETCH CUR3 INTO BUSN,DEST;
-> SELECT * FROM BUS WHERE DESTINATION=DEST;
-> CLOSE CUR3;
-> END $$
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;
mysql> call bus_details();
+--------+--------+-------------+-------+------+
| bus_no | source | destination | j_day | type |
+--------+--------+-------------+-------+------+
| 2222
| HYD
| RAJ
| MON
| NAC |
| 2233
| KDD
| RAJ
| TUE
| NAC |
+--------+--------+-------------+-------+------+
2 rows in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
mysql> \t

Page No:

Roll No: 10M81D5803

Program 1: 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;
clrscr();
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';
Page No:

Roll No: 10M81D5803

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++)
printf("%d",num[j]);
printf("\n");
f2=fopen("identifier","r");
k=0;
printf("The keywords and identifiersare:");
while((c=getc(f2))!=EOF)
Page No:

Roll No: 10M81D5803

{
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);
getch();
}
Output:
Enter the c program:
a+b*c
d/f
^Z
The no's in the program are
The keywords and identifiersare:
a is an identifier
b is an identifier
c is an identifier
d is an identifier
f is an identifier
Special characters are+*/
Total no. of lines are:2

Page No:

Roll No: 10M81D5803

Program 2: 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);}*/
"*/" {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");}
\(
Page No:

Roll No: 10M81D5803

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();
printf("\n\n");
return 0;
}int yywrap()
{
return 0;
}
Input:
$vi var.c
#include<stdio.h>
main()
{
int a,b;
}

Page No:

Roll No: 10M81D5803

Output:
$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

Page No:

Roll No: 10M81D5803

Program 3: 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",KEYWOR
D,
"float",KEYWORD,"double",KEYWORD,"char",KEYWORD,"struct",KEYWORD,"r
et
urn",KEYWORD,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);
Page No:

Roll No: 10M81D5803

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()
{
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)

Page No:

Roll No: 10M81D5803

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);
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;
Page No:

Roll No: 10M81D5803

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()
{
int t;
T();
while(1)
{
switch(lookahead)
{
case '+' : t=lookahead;
Match(lookahead);
T();
display(t,NONE);
continue;
case '-' : t=lookahead;
Match(lookahead);
Page No:

Roll No: 10M81D5803

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 ");
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

Page No:

Roll No: 10M81D5803

Program 4: 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 ;}
| term
;

Page No:

Roll No: 10M81D5803

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

Page No:

Roll No: 10M81D5803

Page No:

Roll No: 10M81D5803

Program 5: 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;}
\< |
\> |
\>= |
\<= |
==
{strcpy(yylval.var,yytext);
return RELOP;}
[ \t] ;
\n LineNo++;
. return yytext[0];
%%
Page No:

Roll No: 10M81D5803

<int.y>
%{
#include<string.h>
#include<stdio.h>
struct quad
{
char
char
char
char

op[5];
arg1[10];
arg2[10];
result[10];

}QUAD[30];
struct stack
{
int items[100];
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
%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
Page No:

Roll No: 10M81D5803

;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");
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;
Page No:

Roll No: 10M81D5803

}| VAR
| NUM
;
WHILEST: WHILELOOP{
Ind=pop();
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");
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++)
{
Page No:

Roll No: 10M81D5803

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);
}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);
}

Page No:

Roll No: 10M81D5803

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;
}
}
Output:
$lex int.l
$yacc d int.y
$gcc lex.yy.c y.tab.c ll lm
$./a.out test.c
Pos
0
1
2
3
GOTO
5
5
<
a
b
t2
6
==
t2
FALSE
10
7
+
a

Operator
<
==
+
=

Arg1
a
to
a
t1

Arg2
b
FALSE
b
a

Result
to
5
t1
4

Page No:

Roll No: 10M81D5803

Program 6: 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)
{
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);
Page No:

Roll No: 10M81D5803

}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);
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;
Page No:

Roll No: 10M81D5803

}
}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 []=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:
Page No:

Roll No: 10M81D5803

Enter filename of the intermediate code: int.txt


STORE
STORE
STORE
STORE

t1,2
a[0],1
a[1],2
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
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

Page No:

Anda mungkin juga menyukai