Вы находитесь на странице: 1из 136

UNIVERSITY OF MUMBAI

INSTITUTE OF DISTANCE AND OPEN LEARNING (IDOL)*


*(Institute of Distance Education (IDE) is renamed)

CERTIFICATE
THE EXPERIMENTS DULY SIGNED IN THIS JOURNAL REPRESENT
THE BONAFIDE WORK BY MISS ______________________________
ROLL NO.
IN SEMESTER III OF SECOND YEAR OF MASTER IN
COMPUTER APPLICATION (MCA) IN THE COMPUTER LABORATORY
OF PCP CENTER SHREE RAM COLLAGE, BHANDUP FOR SUBJECT
_______________________ DURING ACADEMIC YEAR 2014 -2015 .

____________________

____________________________

LECTURE IN CHARGE

HEAD, DEPARTEMENT OF MCA

______________________
EXTERNAL EXAMINER

INDEX
Database Management System
SR.NO

CONTENT

1.
2.

Creation of banking enterprise database.


Creation of employee table.

3.
4.
5.

Creation of department table.


Types of cursor.
Creation of function.

6.

Creation of stored procedure.

7.

Creation of package.

8.

Creation of trigger.

9.

Write a block that accept names and display


its 5 times in output screen.
Write a PL/Sql block that accepts principal,
duration (in months) and rate of interest and
calculate maturity amount.
Write a block that accepts radius and
calculate area of circle use PI as constant.
Write a block that accepts number and
display whether is less than or equal or
greater than 10.

10.

11.
12.

SIGNATURE

Practical No.1
Aim: Creation of banking enterprise database.

create table branch


(br_name varchar(15) primary key,
br_city varchar(10),
asset int) ;
create table account
(acc_no varchar(10) primary key,
br_name varchar(15),
balance int,
foreign key(br_name) references branch) ;
create table depositor
(cust_name varchar(15),
acc_no varchar(10) foreign key references account,
foreign key(cust_name) references customer) ;
create table customer
(cust_name varchar(15) primary key,
cust_street varchar(20),
cust_city char(10)) ;
create table borrower
(cust_name varchar(15) foreign key references customer,
loan_no varchar(15) foreign key references loan) ;
create table loan
(loan_no varchar(15) primary key,
br_name varchar(15) foreign key references branch,
amount int) ;

insert into customer values('Adams','Spring','Pittsfield')


insert into customer values('Brooks','Senator','Brooklyn')
insert into customer values('Curry','North','Rey')
insert into customer values('Glenn','Sand Hill','Woodside')
insert into customer values('Glenn','Walnut','Stamford')
insert into customer values('Hayes','Main','Harrison')
insert into customer values('Johnson','Alma','Palo Alto')

insert into customer values('Jones','Main','Harrison')


insert into customer values('Lindsay','Park','Pittsfield')
insert into customer values('Smith','North','Rey')
insert into customer values('Turner','Putnam','Stamford')
insert into customer values('Williams','Nassau','Princeton')

insert into depositor values('Hayes','A-102')


insert into depositor values('Johnson','A-101')
insert into depositor values('Johnson','A-201')
insert into depositor values('Jones','A-217')
insert into depositor values('Lindsay','A-222')
insert into depositor values('Smith','A-215')
insert into depositor values('Turner','A-305')
select * from depositor
insert into branch values('Brighton','Brooklyn',7100000)
insert into branch values('Downtown','Brooklyn',9000000)
insert into branch values('Mianus','Horseneck',400000)
insert into branch values('North Town','Rye',3700000)
insert into branch values('Perryridge','Horseneck',17000000)
insert into branch values('Pownal','Bennington',300000)
insert into branch values('Redwood','Palo Alto',2100000)
insert into branch values('Round Hill','Horseneck',8000000)
select * from branch

insert into account values('A-101','Downtown',500)


insert into account values('A-102','Perryridge',400)
insert into account values('A-201','Brighton',900)
insert into account values('A-215','Mianus',700)
insert into account values('A-217','Brighton',750)
insert into account values('A-222','Redwood',700)
insert into account values('A-305','Round Hill',350)
select * from account

insert into loan values('L-11','Round Hill',900)


insert into loan values('L-14','Downtown',1500)
insert into loan values('L-15','Perryridge',1500)
insert into loan values('L-16','Perryridge',1300)
insert into loan values('L-17','Downtown',1000)
insert into loan values('L-23','Redwood',2000)

insert into loan values('L-93','Mianus',500)


select * from loan
insert into borrower values('Adams','L-16')
insert into borrower values('Curry','L-93')
insert into borrower values('Hayes','L-15')
insert into borrower values('Johnson','L-14')
insert into borrower values('Jones','L-17')
insert into borrower values('Smith','L-11')
insert into borrower values('Smith','L-23');
insert into borrower values('Williams','L-17');
select * from borrower;
1)Find the names of all branches in the loan relation.
SQL> select distinct br_name
2 from loan;
2)Find all loan numbers for loans made at the perryridge branch with loan amount greater
than 1200.
SQL> select l_no
2 from loan
3 where br_name='perryridge' and amt>1200;
3)Find the loan number with loan amounts between 90000 and 100000.
SQL> select l_no
2 from loan
3 where amt between 90000 and 100000;
4)Find all customers who have a loan from the bank, Find their names,loan numbers and
loan amount.
SQL> select c_name,b.l_no,l.amt
2 from borrower b,loan l
3 where b.l_no=l.l_no;
williams
l-17
1000
5)Find the customer names,loan numbers and loan amounts for all loans at th perryridge
branch.
SQL> select c_name,b.l_no,amt
2 from borrower b,loan l
3 where b.l_no=l.l_no and br_name='perryridge';
6)Find the names of all branches that have assets greater than at least one branch located
in Brooklyn.

SQL> select distinct t.br_name


2 from branch t,branch s
3 where t.assets>s.assets and s.br_city='brooklyn';
7)Find the names of all customers whose street address includes the substring main.
SQL> select c_name
2 from customer
3 where c_street like '%main%';
8)Find in alphabetic order all customers who have a loan at the Perryridge branch.
SQL> select distinct c_name
2 from borrower b,loan l
3 where b.l_no=l.l_no and
4 br_name='perryridge'
5 Order by c_name;
9)Find all customers having a loan ,an account or both at the bank.
SQL> select c_name
2 from depositor
3 union
4 select c_name
5 from borrower;
10)Find all customers who have both a loan and an account at the bank.
SQL> select c_name
2 from depositor
3 intersect
4 select c_name
5 from borrower;

11)Find the average account balance at each branch.


SQL> select br_name,avg(bal)
2 from account
3 group by br_name;
12)Find the number of depositors for each branch.
SQL> select br_name,count(distinct c_name)
2 from depositor d,account a
3 where d.acc_no=a.acc_no
4 group by br_name;
13)Find the branch name whose average balance is greater than 1200.

SQL> select br_name,avg(bal)


2 from account
3 group by br_name
4 having avg(bal)>1200;
14)Find the average balance for each customer who lives in Harrison and has at least three
accounts.
SQL> select d.c_name,avg(bal)
2 from depositor d,account a,customer c
3 where d.acc_no=a.acc_no and d.c_name=c.c_name and
4 c_city='harrison'
5 group by d.c_name
6 having count(distinct d.acc_no)>=3;
15)Find the loan numbers in the loan relation with null values for amount.
SQL> select l_no
2 from loan
3 where amt is null;
16)Find those customers who are borrowers from bank.
SQL> select distinct c_name
2 from borrower
3 where c_name in(select c_name from depositor);

17)Find all customers who have both an account and a loan at the perryridge branch.
SQL> select distinct c_name
2 from borrower b,loan l
3 where b.l_no=l.l_no and br_name='perryridge' and
4 (br_name,c_name)in
5 (select br_name,c_name
6 from depositor d,account a
7 where d.acc_no=a.acc_no);
18)Find all customers who do have a loan at the bank,but do not have an account at the
bank.
SQL> select distinct c_name
2 from borrower
3 where c_name not in(select c_name from depositor);
19)Find the names of all branches that have assets greater than those of at least one branch
located in Brooklyn.

SQL> select br_name


2 from branch
3 where assets>some(select assets from branch
4 where br_city='brooklyn');
20)Find those customers who are borrowers from bank.
SQL> select distinct c_name
2 from borrower
3 where c_name in(select c_name from depositor);
21)Find an delete branch name where it is perryridge.
SQL-> Delete from account where br_name= perryridge
22) Delete all loans with loan amounts between 1300 and 1500
SQL-> delete from loan where amount between 1300 and 1500

23) Delete ball account tuples at every branch located in Needham


SQL-> Delete from account
where br_namein(select br_name from branch where br_city=needham)

Practical No.2
Aim: Creation of employee table.

create table Employee (Empno number(4),Ename varchar(20),desig varchar(8),


cader number(4),Doj date,Salary nuber(7,3),comm number(7,3),deptno number(2));

1. Make EmpNo as primary key.


Alter table Employee add constraint pk2 primary key (empno);

2. Select all employees who are under the manager designation or have salary
Greater than 10000.
Select Empno,Ename,design,salary from Employee where design ="Manager" or salary>10000

3. List all employee whose name begin with "v"


Select * from employee where ename like "v%"

4. Display all employee with their salary listed in descending order.


Select * from employee order by salary Desc

5. Give a query to increase the salary of the manager to 10%


Update employee set salary =1.1 *salary where design="Manager"

6. Find the highest & lowest salaries & the difference between them.
Select Max(salary),Min(salary),max(salary)-min(salary)from employee.

7.Find the total salary & total commissions of managers.


Select sum (salary), sum(comm)from Employee where design="Manager"

8. Display all employee who have joined on 10 may 2002.


select * from employee where doj=10-may-2002

9. Find the average salary of AGM.


Select avg(salary)from employee where desg=AGM

Practical No.3
Aim: Creation of department table.

Create table Depat(DepatNO number(2),Dname varchar(20),Location varchar(15));

1.Make DeptNo as primary key.


Alter table Dpat add constraint pk2 primary key (deptno);

2.Give the command to view the details of tables Depat.


Desc Depat.

3.Increase the column width by 1 from deptno in depat table.


Alter table depat modify deptno mumber(3);

4. Insert records in Depat table.


Insert into Depat values(301,Web,Chennai);
Insert into Depat values(302,Hr,Bombay);
Insert into Depat values(303,Sales,Chennai);

5. Select all records from Depat tables


Select * from Depat.

Practical No.4
Aim: Study of Cursor.
Types of cursor
1) Implicit cursors.
2) Explicit cursors.
Implicit cursors.
A bank manager has decided to transfer employees across branches. Write PL/SQL code to
accept an employee number and the branch number followed by updating the branch
number of that employee to which he belongs. Display an appropriate message using
SQL%NOYFOUND based on the non-existence of the record in the EMP MSTR table.
BEGIN
UPDATE EMP_MSTR SET BRANCH_NO = &BRANCH_NO
WHERE EMPNO = &EMPNO
IF SQL%FOUND THEN
DBMS_OUTPUT.PUT_LINE ("Employee successfully transferred");
END IF;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE ("Employee number does not exist");
END IF;
END;

The bank manager of Bandra branch decides to activate all those accounts which were previously
marked as inactive for performing no transactions in the last 365 days. Write a PL/SQL block to
update the status of accounts. Display an appropriate message based on the number of rows
affected by the update fired.
DECLARE
Rows_Affected char(4);
BEGIN
UPDATE ACCT_MSTR SET STATUS = 'A' WHERE STATUS = `S' AND BRANCH_NO IN
(SELECT BRANCH_NO FROM BRANCH_MSTR WHERE NAME = `Bandra');
Rows_Affected := TO_CHAR(SQL%ROWCOUNT);
IF SQL%ROWCOUNT > 0 THEN
DBMS_OUTPUT.PUT_LINE(Rows_Affected II 'accounts activated successfully');
ELSE
DBMS_OUTPUT.PUT_LINE(`Currently there are no inactive accounts in the Bandra
branch');
END IF;
END;

Explicit Cursor:
The bank manager has decided to mark all those accounts as inactive (I) on which there are no
transactions performed in the last 365 days. Whenever any such update takes place, a record for
the same is maintained in the INACTIVE_MSTR table which contains the account number, the
opening date and the type of account. Write a PL/SQL block to implement this.
We first create the INACTIVE_MSTR table as follows:

CREATE TABLE INACTIVE_MSTR


(ACCTNO VARCHAR2(10),
OPENDT DATE,
TYPE VARCHAR2(2));
Now we write the PL/SQL code block:
DECLARE
CURSOR Crsr NoTrans IS
SELECT ACCTNO, STATUS, OPENDT, TYPE FROM ACCT_MSTR WHERE ACCTNO IN
(SELECT ACCTNO FROM TRANS_MSTR
GROUP BY ACCTNO HAVING MAX(SYSDATE OPENDT) > 365;
/* declare memory variables to hold data fetched from the cursor a/
str_ACCTNO ACCTMSTR.ACCTNO%TYPE; str_STATUS ACCTMSTR.STATUS%TYPE;
dt_OPENDT ACCTMSTR.OPENDT%TYPE; strTYPE ACCTMSTR.TYPE%TYPE;
BEGIN
OPEN CrsrNoTrans;
/* if the cursor is open, continue with the data processing else display an appropriate error
message */
IF Crsr NoTrans%ISOPEN THEN
100P
FETCH Crsr_NoTrans INTO str_ACCTNO, str_STATUS, dt_OPENDT, str_TYPE;
EXIT WHEN CrsrNoTrans%NOTFOUND;
IF Crsr NoTrans%FOUND THEN
/*update status to 'I' and insert each record into the INACTIVE_MSTR table a/
UPDATE ACCTMSTR SET STATUS = 'I' WHERE ACCTNO = str ACCTNO;
INERT INTO INACTIVE_MSTR VALUE (str_ACCTNO, dt_opendt, str TYPE);
END IF;
END LOOP;
/*make the changes permanent!
COMMIT
ELSE
Dbms_outputput_line ('Error: Unable to open cursor');
END IF;
CLOSE Crsr_NoTrans;
END;
In the above example, the %TYPE means that the data type of these variables will be as that from
the table.
Since the query may return more than one row, a loop is created which does the following:

(i)
(ii)

Fetch the data retrieved by the cursor into the variable.


Check if any data is retrieved
a.
Update the status field of the AACT_MSTR table to indicate that the account is inactive.
b. Insert a record in the INACTIVE_MSTR table
(iii)
Repeat the above steps until the data retrieval process is completed.
(iv) Finally, the COMMIT statement is executed to make the changes permanent.
Write a PL/SQL block that will display the customer name, the fixed deposit number and
the fixed deposit amount of the first 5 customers holding the highest amount in fixed
deposits.
DECLARE
CURSOR Crsr_HiFD IS
SELECT Fname II
FDNO, AMT
FROM CUST_MSTR C, ACCT_FD_CUST_DETAlLS A, FD_DETAILS F WHERE
C.CUSTNO = A.CUSTNO AND A.FDNO = F.FDSRNO
ORDER BY AMT Desc;
str_NAME VARCHAR2(40);
str_FDNO FD_DETAILS.FDNO%type; num_AMT FD_DETAILS.AMT%type;
BEGIN

OPEN
Crsr_HiFD;
dbms_output.put_line (Name FD No. Amount');
dbms_output.put_line (`
LOOP
FETCH Crsr HiFD INTO str NAME, str FDNO, num_AMT; EXIT WHEN
(Crscr_HiFD%it.OWCOUNT-1) = 5 OR
Crscr HiFD%NOTFOUND;
dbms_output.put_line (str_NAME ,str_FDNO)' 'II num_AMT);
END LOOP;
END;
The bank manager has decided to marks all those accounts as inactive (I) on which there are no
transactions performed in the last 365 days. Whenever any such update takes place, a record for
the same is maintained in the INACTIVE MSTR table. This table consists of the fields account
number, opening date and type of account. Write PL/SQL code block to do the same.
First we create the INACTIVE_MSTR table.
CREATE TABLE IANCTIVE_MSTR (
ACCTNO VARCHAR2(10), OPENDT DATE,
ACCTYPE VARCHAR2(2));
Now we write the PL/SQL code block:
DECLARE
CURSOR Crsr_NoTrans IS
SELECT ACCTNO, STATUS, OPENDT, ACCTYPE FROM ACCTMSTR WHERE ACCTNO
IN (SELECT ACCTNO FROM TRANSMSTR
GROUP BY ACCTNO
HAVING MAX(SYSDATE OPENDT) > 365;

BEGIN
/* we use the cursor FOR loop */
FOR NoTransRec IN Crsr NoTrans
/* update the inactive status and insert each record into the INACTIVE_MSTR table */ UPDATE
ACCT_MSTR SET STATUS = 'I'
WHERE ACCTNO= NoTransRec.ACCTNO;
INSERT INTO INACTIVE_MSTR
VALUES(NoTransRec.ACCTNO, NoTransRec.OPENDATE, NoTransRec.ACCTYPE); END
LOOP;
COMMIT;
END;
Write a PL/SQL code block that will merge the data available in the newly created table
NEW_BRANCHES with the data available in the table BRANCH MASTER. If the data in the first
table already exists in the second table, then that data should be skipped.
CREATE TABLE NEW_BRANCHES( BRANCHNO VARCHAR2(1 0), NAME
VARCHAR2(30));
INSERT INTO NEW_BRANCHES (BRANCHNO, NAME) VALUES (`B4', `MAHIM');
INSERT INTO NEW_BRANCHES (BRANCHNO, NAME) VALUES (`BS', `MATUNGA');
INSERT INTO NEW_BRANCHES (BRANCHNO, NAME) VALUES (`BC, `DADAR');
INSERT INTO NEW_BRANCHES (BRANCHNO, NAME) VALUES (`BT, `KHAR');
Now WE WRITE THE PL/SQL CODE BLOCK:
DECLARE
/* This cursor retrieves all records of NEW_BRANCHES table 5/
CURSOR Crsr_Newbranches (str_BRANCHNAME VARCHAR2) IS SELECT * FROM
NEW_BRANCHES;
/* this cursor accepts the value of NAME from the current row of the cursor Crsr Nevvbranches
*/ CURSOR Crsr_Branchchk (str_BRANCHNAME varchar2) IS
SELECT BRANCHNO FROM BRANCHMSTR
WHERE NAME = strBRANCHNAME;
/* we create variables that hold the data from the cursor Crsr Newbranches */
str BRANCHNO BRANCH_MSTRBRANCHNO.%TYPE;
str BRANCHNNAME BRANCH_MSTR.NAME.%TYPE;
/* we create a variable that holds data from the cursor Crsr_Branchchk */ temp VARCHAR2(10);
BEGIN
/* open the Crsr_Newbranches cursor */ OPEN CrsrNewbranches;
LOOP
/* fetch the records from the Crsr_Newbranches cursor */
FETCH Crsr_Newbranches INTO str_BRANCHNO, str BRANCHNAME; EXIT WHEN Crsr
Newbranches%NOTFOUND;
/* open the Crsr_Branchchk cursor. Note that the value of variable passed to the CrsrBranchchk
cursor is set to the value of NAME in the current row of the cursor Crsr Newbranches */
OPEN Crsr_Branchchk(str_BRANCHNAME); FETCH CrsrBranchchk INTO temp;
IF Crsr BRANCHCHK%FOUND THEN
dbms_output.put_line (`Branch ' II str_BRANCHNAME II `exists');
ELSE

dbms_output.put_line (`Branch II str_BRANCHNAME II 'does not exist. Inserting


new branch in database');
INSERT INTO BRANCH_MSTR VALUES (str_BRANCHNO,
str_BRANCHNAME);
END IF;
CLOSE Crsr_BRANCHCHK;
END LOOP;
CLOSE Crsr_Newbranches;
COMMIT;
END;

Practical No.5
Aim: Creation of function.

Consider the tables TRANS_MSTR and ACCT_MSTR. Bothe the tables belong to the banking
system. The TRANS_MSTR table issued to register the deposit or withdrawal performed .As a
batch process the initial opening balance value must be written to the TRANS_MSTR table
wherever an account is opened with the bank. Write a pl/sql block of code that would insert a
records representing the opening balance with the bank. in the TRANS_MSTR tables depend on
ACCT_NO is not present in the TRANS_MSTR table.i.e there is no entry made for the initial
deposit then a record is inserted in TRANS_MSTR table representing the initial deposit ,then a
rerecord is inserted in the TRANS_MSTR table representing the initial payment made while
opening an account .The function will search fro a matching value. in the TRANS_MSTR table
when a value is passed it to when begin invoked.
The function will return 1 indication that a match is found or 0 indication that no match is found
the value returned by the function is used to make a decision to insert a ;record or skip the
insertion in the TRANS_MSTR table.
create function for use
A store function is created to perform the function the ACCT_NO check .CChkAcctNO is the name of the
function which accepts a variable ACCT_NO and return a value to the host environment the value
changes from(i.e if Acct_NO does not exist) to 1(i.e if Acct_No exists) depending on the recording
received

Create or replace function F_CheckACCTNO(VACCT_NO IN VARCHA2)


RETURN NUMBER IS
DUMMY ACCINO VARCHAR2( 10);
BEGIN
SELECT DISTINCT ACCT. NO INTO DUNIMYACCIN
WHERE ACCT_NOaVACCI_NO:
RETURN 1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
END:

Output:
Function created

Calling the Function F_CHKACCTNO in A PL/SQL Code Block


DECLARE
CURSOR SCANTABLE IS SELECT ACCT_NO,TYPE FROM ACCT_MSTR;
MACCT_NO ACCT_MSTR TPE%TYPE;

VALEXIST NUMBER( I );
BEGIN
OPEN SCANTABLE;
LOOP
FETCH SCANTABLE INTO MACCT NO,MTYPE;
EXIT WHEN SCANTABLE%NOTFOUND;
VALEXISTS: =F CIIKACCTNONACCT NO);
IF VALEXISTS=0) THEN
IF MTYPE=SB' THEN
INSERT INTO TRANS MSTR (TRANS NO,ACCT
NO,DT,TYPE,PARTICULAR, DR_CR,AMT, BALANCE)
VALUES(SELECT T' ||
TO CHAR(MAX(TO NUMBER(SUBSTR(TRANS N0,2))+1 )FROM
TRANS_MSTR),MACCT_NO,SYSDATE,'C','INITTAL PAYEMENT',D,500,500);
ELSE
INSERT INTO TRANS MSTR (TRANS NO,ACCT
N0,DT,TYPE,PARTICULAR DR_CR,ANIT, BALANCE)
VALUES((SELECT 'T' ||
TOCHAR(MAX(TO NUMBER(SUBSTR(TRANS N0,2)))+ 1)FROM
TRANS MSTR),MA-COINO,SYSDATE/C,INITIA1 PAY EMENT',D',200,200);
END IF;
END IF;
END LOOP;
CLOSE SCANTABLE;
COMMIT;
END;

Output :PL/SQL procedure successfully completed.


Deleting Function:
DROP FUNCTION F_CHLACCTNO;

Practical No.6
Aim: Creation of Stored Procedure.
Using a procedure
Example.
The current example deals with the Fixed Deposit Maturity system. The tables involved with this
processing are FD_DTLS,Trans_MSTR and ACCT_MSTR.Whenever a fixed deposit is due for
payment and if there are instruction given to the bank for crediting the fixed deposit amount on
maturity to their account held in the bank an entity is passed in the TRANS_MSTR table for
deposit of the fixed .Finally the status of that fixed deposit is updated to reflect the increase of
the current balance, Finally the status of that fixed deposits is updated to reflect the increase of
the current balance. In order to simply of that fixed deposit is updated as Mie. Matured in the
FD_DTLS tables. In order to simplify the job of insertion and updating of three
tables(TRANS_MSTR,FD_DTLS and ACCT_MSTR)each time a fixed deposit is due for
payment a procedure is created .This procedure is then called in the PL/SQL block while
checking for those fixed deposits due for payment.

CREATE OR REPLACE PROCEDURE PROC_INSUPD(VFD_NO IN VARCHAR2, VACCT_NO IN


VARCHAR2, AMT IN NUMBER) IS
/* Variable declarations */
mCurBal number;
BEGIN
/* Retrieving the current balance */
SELECT CURBAL INTO mCurBal FROM ACCT_MSTR WHERE ACCT_NO = vACCT_NO;
/* Inserting a record in the TRANS_MSTR table */
INSERT INTO TRANS_MSTR (TRANS_NO, ACCT_NO, DT, TYPE, PARTICULAR, DR_CR,
AMT, BALANCE)
VALUES((SELECT 'T' || TO_CHAR(MAX(TO_NUMBER(SUBSTR(TRANS_NO, 2))) + 1)
FROM TRANS_MSTR), vACCT_NO, SYSDATE, 'C', 'Fixed Deposit Payment', 'D', vAMT, (mCurBal +
vAMT));
/* Updating the CURBAL in the ACCT_MSTR table */
UPDATE ACCT_MSTR SET CURBAL = CURBAL + vAMT WHERE ACCT_NO = vACCT_NO;
/* Updating the STATUS in the FD_DTLS table */
UPDATE FD_DTLS SET STATUS = 'M' WHERE FD_NO = vFD_NO;
END;
DECLARE
/* Cursor CRSR_FDCHK retrieves all the records of table FD_DTLS which are active and due for
payment */
CURSOR CRSR_FDCHK IS

SELECT FD_NO, PAYTO_ACCTNO, DUEAMT FROM FD_DTLS


WHERE TO_CHAR(DUEDT,'DD-MM-YY') = TO_CHAR(SYSDATE,'DD-MM-YY')
AND STATUS = 'A' AND PAYTO_ACCTNO IS NOT NULL;
/* Declaration of memory variables that will hold values */
mFD_NO VARCHAR2(10);
mPAYTO_ACCTNO VARCHAR2(10);
mAMT NUMBER(8,2);
mState NUMBER := 0;

BEGIN
/* Opening the cursor */
OPEN CRSR_FDCHK;
LOOP
FETCH CRSR_FDCHK INTO mFD_NO, mPAYTO_ACCTNO, mAMT;
EXIT WHEN CRSR_FDCHK%NOTFOUND;
/* Call procedure proc_insupd to perform insert/update operations on tables. */
proc_insupd(mFD_NO, mPAYTO_ACCTNO, mAMT);
/* Updating the state to 1 i.e. there are fds due for payment */
mState := 1;
END LOOP;
/* Display a message if no FDs are due for payment based on the mState variable */
IF mState = 0 THEN
DBMS_OUTPUT.PUT_LINE('Currently there are no fixed deposits due for payment.');
END IF;
CLOSE CRSR_FDCHK;
COMMIT;
END;

Output:
Currently there is no fixed deposit due to payment.
PL/SQl procedure successfully completed.

Deleting a Stored Procedure


DROP PROCEDURE PROC_INSUPD;

Practical No.7
Aim: Creation Package.

The first step to creating a package is to create its specification. the specification declares the
object that are contained in the body of the package. A package is created using Oracles SQL *
Plus interactive tool. A package can include Function and Procedure. The Variable declared
within the package can be accessed by any Function Procedure within the package. To Create a
specification issue the CREATE PACKAGE command

Example 1:
CREATE OR REPLACE PACKAGE TRANSACTION_MGMT AS
PROCEDURE PERFORM_TRANS(mACCT_NO VARCHAR2, MD VARCHAR2, AMT NUMBER);
PROCEDURE CANCEL_FD(mFD_NO VARCHAR2);
BAL NUMBER;
P_ACCT_NO VARCHAR2(10);
D_AMT NUMBER;
END TRANSACTION_MGMT;

Output:Package Created.
Example 2:
CREATE OR REPLACE PACKAGE BODY TRANSACTION_MGMT AS
PROCEDURE PERFORM_TRANS(mACCT_NO VARCHAR2, MD VARCHAR2, AMT NUMBER) IS
BEGIN
SELECT CURBAL INTO BAL FROM ACCT_MSTR WHERE ACCT_NO = mACCT_NO;
IF MD = 'D' THEN
INSERT INTO TRANS_MSTR(TRANS_NO, ACCT_NO, DT, TYPE, PARTICULAR,
DR_CR, AMT, BALANCE)
VALUES((SELECT 'T' || TO_CHAR(MAX(TO_NUMBER(SUBSTR( TRANS_NO, 2))) + 1)
FROM TRANS_MSTR), mACCT_NO, SYSDATE, 'C', 'Deposit', MD, AMT, (BAL + AMT));
UPDATE ACCT_MSTR SET CURBAL = CURBAL + AMT
WHERE ACCT_NO = mACCT_NO;
ELSE
IF AMT < BAL THEN
INSERT INTO TRANS_MSTR(TRANS_NO, ACCT_NO, DT, TYPE, PARTICULAR, DR_CR,
AMT, BALANCE) VALUES((SELECT 'T' || TO_CHAR(MAX(TO_NUMBER(SUBSTR(
TRANS_NO, 2))) + 1) FROM TRANS_MSTR), mACCT_NO, SYSDATE, 'C', 'Withdrawal', MD,
AMT, (BAL - AMT));
UPDATE ACCT_MSTR SET CURBAL = CURBAL - AMT
WHERE ACCT_NO = mACCT_NO;
END IF;
END IF;
END;

Example 3.
CREATE OR REPLACE PROCEDURE PROC_INSUPD(VFD_NO IN VARCHAR2, VACCT_NO IN
VARCHAR2, vAMT IN NUMBER) IS
/* Variable declarations */
mCurBal number;
BEGIN
/* Retrieving the current balance */
SELECT CURBAL INTO mCurBal FROM ACCT_MSTR WHERE ACCT_NO = vACCT_NO;
/* Inserting a record in the TRANS_MSTR table */
INSERT INTO TRANS_MSTR (TRANS_NO, ACCT_NO, DT, TYPE, PARTICULAR, DR_CR, AMT,
BALANCE)
VALUES((SELECT 'T' || TO_CHAR(MAX(TO_NUMBER(SUBSTR(TRANS_NO, 2))) + 1) FROM
TRANS_MSTR), vACCT_NO, SYSDATE, 'C', 'Fixed Deposit Payment', 'D', vAMT, (mCurBal + vAMT));
/* Updating the CURBAL in the ACCT_MSTR table */
UPDATE ACCT_MSTR SET CURBAL = CURBAL + vAMT WHERE ACCT_NO = vACCT_NO;
/* Updating the STATUS in the FD_DTLS table */
UPDATE FD_DTLS SET STATUS = 'M' WHERE FD_NO = vFD_NO;
END;

Example 4.
CREATE OR REPLACE FUNCTION F_CHKACCTNO(vACCT_NO IN VARCHAR2)
/* Variable that hold data from the TRANS_MSTR table */
dummyAcctNo VARCHAR2(10);
BEGIN
SELECT DISTINCT ACCT_NO INTO dummyAcctNo FROM TRANS_MSTR
WHERE ACCT_NO = vACCT_NO;
/* If the SELECT statement retrieves data, return value is set to 1. */
RETURN 1;
EXCEPTION
/* If the SELECT statement does not retrieve data, return value is set to 0 */
WHEN NO_DATA_FOUND THEN
RETURN 0;
END;
DECLARE
/* Cursor SCANTABLE retrieves the required data from the table ACCT_MSTR */
CURSOR SCANTABLE IS
SELECT ACCT_NO, TYPE FROM ACCT_MSTR;
/* Variables that hold data from the cursor scantable */
mACCT_NO ACCT_MSTR.ACCT_NO%type;
mTYPE ACCT_MSTR.TYPE%type;

/* Variable that stores the value returned by the f_ChkAccctNo function i.e. 1 or 0 */
valexists NUMBER(1);
BEGIN
OPEN SCANTABLE;
LOOP
FETCH SCANTABLE INTO MACCT_NO, MTYPE;
EXIT WHEN SCANTABLE%NOTFOUND;
/* Call function F_CHKACCTNO to check if ACCT_NO is present in TRANS_MSTR table */
valexists := F_CHKACCTNO(MACCT_NO);
/* If ACCT_NO does not exist insert a record in the TRANS_MSTR table */
IF valexists = 0 THEN
IF mTYPE = 'SB' THEN
INSERT INTO TRANS_MSTR (TRANS_NO, ACCT_NO, DT, TYPE, PARTICULAR, DR_CR,
AMT, BALANCE)
VALUES((SELECT 'T' || TO_CHAR(MAX(TO_NUMBER(SUBSTR( TRANS_NO, 2))) + 1)
FROM TRANS_MSTR), mACCT_NO, SYSDATE, 'C', 'Initial Payment', 'D', 500, 500);
ELSE
INSERT INTO TRANS_MSTR (TRANS_NO, ACCT_NO, DT, TYPE, PARTICULAR, DR_CR,
AMT, BALANCE) VALUES((SELECT 'T' || TO_CHAR(MAX(TO_NUMBER(SUBSTR(
TRANS_NO, 2))) + 1) FROM TRANS_MSTR), mACCT_NO, SYSDATE, 'C', 'Initial Payment',
'D', 2000, 2000);
END IF;
END IF;
END LOOP;
CLOSE SCANTABLE;
COMMIT;
END;

Package body
CREATE OR REPLACE PACKAGE BODY PCK_DEL IS
PROCEDURE DEL_EMP_BRANCH(mBRANCH_NO VARCHAR2) IS noemp NUMBER;
BEGIN
noemp := CNT_EMP_BRANCH(mBRANCH_NO);
IF noemp < 2 AND noemp > 0 THEN
DELETE EMP_MSTR WHERE BRANCH_NO = mBRANCH_NO;
DBMS_OUTPUT.PUT_LINE('All the employees belonging to the branch ' ||
mBRANCH_NO || ' deleted sucessfully');
DELETE BRANCH_MSTR WHERE BRANCH_NO = mBRANCH_NO;
DBMS_OUTPUT.PUT_LINE('Branch ' || mBRANCH_NO || ' deleted sucessfully');
END IF;
IF noemp = 0 THEN
DBMS_OUTPUT.PUT_LINE('There exist no employees in the branch.');
END IF;
IF noemp >= 2 THEN
DBMS_OUTPUT.PUT_LINE('There exist ' || noemp || ' employees in the branch ' ||

mBRANCH_NO || ' Skipping Deletion.');


END IF;
END;
FUNCTION CNT EMP BRANCH)mBRANCH_NO_VARCHAR)RETURN NUMBER
noemp NUMBER;
BEGIN
SELECT COUT(*) INTO noemp FROM EMP_MSTR WHERE
BRANCH NO =mBRANCHNO;
RETURN noemp;
EXCEPTION WHEN NO_DATA_FOUND THEN
RETURN ):
END
END PCK_DEL:

Output:
Package Body created
OVERLOADING PROCEDURE AND FUNCTION
Example 1:

Create a package to check that a numeric value is greater than zero and a date is less than or equal to
sysdate.
CREATE OR REPLACE PACKAGE CHECK_FUNC IS FUNCTION VALUE_OK(DATE_IN
INDATE)RETURN VARCHAR2;
FUNCTION VALUE_OK (NUMBER_IN IN NUMBER) RETURN VARCHAR2;
END;

Output:
PACKAGE CREATED
CREATE OR REPLACE PACKAGE BODY CHECK FUNC IS FUNCTION VALUE_OK
END;
(DATE_IN IN DATE) RETURN VARC2 IS BEGIN
IF DATE_IN==SYSDATE THEN
RETURN output from the first-over function true;
END IF;
END
FUNCTION VALUE_OK(NUMBER_IN IN NUMBER)RETURN VARCHAR2 IS
BEGIN
IF NUMBER_IN>0 THEN
RETURN OUTPUT FROM THE SECOND OVER LOADED FUNCTION:TRUE;
ELSE
RETURN OUTPUT FROM THE SECOND OVER LOADED FUNCTION:FALSE;
END IF;
END;
END;
OUTPUT:
Package body created.

Example 2:

The bank manager decides to activate all those accounts, which were previously marked as inactive or
performing no transactions in last 365 days.
Create a package spec and a package body named ACCT_MNTC that includes two procedures of the
same name and the second procedure accepts branch name.
Package Specification:
CREATE OR REPLACE PACKAGE ACCT_MNTC IS PROCEDURE
ACT_ACCTS(vBRANCH_NO IN NUMBER);
PROCEDURE ACT ACCTS(v NAME IN VARCHAR2);
END;
OUTPUT:
Package created.
Package Body:
CREATE OR REPLACE PACKAGE BODY ACCT_MNTC IS PROCEDURE
ACT_ACCTS(v BRANCH_NO IN NUMBERS)IS
BEGIN
UPDATE ACCT_MSTR SET STATUS = `A`
WHERE BRANCH NO=`B`|| v BRANCH_NO AND STATUS =`S`
IF SQL%ROWCQNT> O THEN
DBMS OUTPUT. PUT_LINE(TO_CHAR(SQL%ROWCOUNT) || ACCOUNTS ACTIVATED
SUCCESSFULLY`);
ELSE
DBMS_OUTPUT.PUT_LINE(CURRENTLY THERE EXIST NO INACTIVE ACCOUNTS IN
THE BRANCH NO|| v BRANCH_NO);
END IF;

PACKAGE BODY
CREATE OR REPLACE PACKAGE BODY PCK_DEL IS PROCEDURE
DELEMP_BRANCH(m BRANCH_NO VARCHAR)IS noemp number;
BEGIN
noemap:=CNT_EMP_BRANCH(m BRANCH_NO);
IF noemap<2 AND noemap> 0 THEN
DELETE EMP MSTR WHERE BRANCH_NO=mBRANCH_NO;
DBMS_OUTPUT.PUT_LINE(*All the employees belonging to the branch*
m BRANCHNO I deleted successfully);
DELETE Branch_MSTR WHERE BRANCH_NO= m BRANCHNO;
DBMSS_OUTPUT.PUT_LINE(*Branch*||m BRANCH_NO||DELEATED SUCCESSFULLY),
END IF;

END
PROCEDURE ACT_ACCTS(vname IN varchar2) IS

BEGIN
UPDATE ACCT_MSTR SET STATUS =A WHERE STATUS=S
AND BRANCH_NO IN (SELECT BRANCH_NO FROM BRANCH_MSTR WHER NAME=Vname);
IF SQL%ROWCOUTN>0 THEN
DBMS_OUTPUT.PUT_LINE(TO CHAR(SQL%ROWCOUNT)||ACCOUNTS ACTIVIATED
SUCCESSFULLY);
ELSE
DBMS_OUTPUT.PUT_LINE(currently there exist no inactive accounts in the branch,vNames);
ENDIF;
END;
END ACCT_MNTC;

Output:
package body created.
EXECUTE ACCTMNTC_ACCTACCTS(1);
EXECUTE ACCT_MNTC.ACCT ACCTS(Vile Parle);

Practical No.8
Aim: Creation Triggers.
Create a transparent audit system for a table CUST_MSTR. The system must keep track of the
records that are being deleted or updated. The functionality being when a record is deleted or
modified the original record details and the date of operation are stored in the audit table, then the
delete or update operation is allowed to go through.
The table definition for audit system is given below:

Create table statement for the AUDIT_CUST table:


CREATE TABLE AUDIT_CUST(
CUST_NO VARCHAR2(10),FNAME VARCHAR2(25),MNAME VARCHAR2(25),
LNAME VARCHAR2(25), DOB_lNC DATE NOT NULL,OCCUP VARCHAR2(25),PHOTOGRAPH
VARCHAR2(25), SIGNATURE VARCHAR2(25), PANCOPY VARCHAR2(1),FORM60
VARCHAR2(1), OPERATION VARCHAR2(20),USERID VARCHAR2(20),ODATE DATE);

Output:
Table created.
CREATE TRIGGER AUDIT_TRAIL
AFTER UPDATE OR DELETE ON CUST_MSTR
FOR EACH ROW
DECLARE
OPER VARCHAR2(8);
BEGIN
IF updating THEN
OPER := 'UPDATE';
END IF;
IF deleting THEN
OPER := 'DELETE';
END IF;
INSERT INTO AUDIT_CUST VALUES (:OLD.CUST_NO, :OLD.FNAME, :OLD.MNAME,:OLD.LNAME,.
:OLD.D0B_INC, :OLD.OCCUP, :OLD.PHOTOGRAPH,:OLD.SIGNATURE, :OLD.PANCOPY, :OLD.FORM60,
OPER, USER, SYSDATE);
END;

Output:
Trigger created.
Example 2

Write a database trigger on the TRANS_MSTR that checks the following:

The account number for which the transaction is being performed is a valid account number

The Transaction Amount is not zero and is positive and


In case of a withdrawal the amount does not exceed the current balance for that account number

CREATE OR REPLACE TRIGGER TRANS_CHECK


BEFORE INSERT ON TRANS_MSTR FOR EACH ROW
DECLARE
v_CNT_ACCT_NO VARCHAR2(10);
v_CURBAL NUMBER(10);
BEGIN
SELECT COUNT(ACCT_NO) INTO v_CNT_ACCT_NO
FROM ACCT_MSTR WHERE ACCT_NO = :new.ACCT_NO;
IF v_CNT_ACCT_NO = 0 THEN
RAISE_APPLICATlON_ERROR( -20000,'The Account number is invalid.');
END IF;
IF :new.AMT <= 0 THEN
RAISE_APPLICATlON_ERROR(-20001,'The Transaction amount cannot' be negative or zero.');
END IF;
SELECT CURBAL INTO v_CURBAL
FROM ACCT_MSTR WHERE ACCT_NO= :new.ACCT_NO;
IF v_CURBAL < :new.AMT AND :new.DR_CR = 'W' THEN
RAISE_APPLICATION_ERROR(-20002,'The amount of withdrawal cannot exceed the balance held in the
account.');
END IF;
END;

Output:
Trigger created.
Example 3
Generating Primary Key Using Sequences
Sequence Creation
CREATE SEQUENCE CUST_SEQ INCREMENT BY 1 START WITH 1;
Output:
Sequence created.
Database Trigger Creation
CREATE OR REPLACE TRIGGER CUST_NO_GENERATION
BEFORE INSERT ON CUST_MSTR FOR EACH ROW
DECLARE
PRIMARY_KEY_VALUE VARCHAR2(10);
BEGIN
SELECT C||TO_CHAR(CUST_SEQ.NEXTVAL) INTO PRIMARY_KEY_VALUE FROM DUAL;
:NEW.CUST_NO:=PRIMARY_KEY_VALUE;
END;

Output: Trigger created

Practical No.9
Aim: Write a program that accepts names and display it 5 times in output screen.

DECLARE
NAME VARCHAR2 (15) =&NAME;
N NUMBER (2) =1;
BEGIN
WHILE N <=5
LOOP
DBMS_OUTPUT.PUT_LINE (NAME);
N=N+1;
END LOOP;
END

Output:
SQL
SQL
SQL
SQL
SQL

Practical No.10
Aim: Write a program that accepts principal,duration(in months) and rate of interest &
calculate Maturity amount.

DECLARE
PRINCIPAL NUMBER: =&PRINCIPAL;
MONTHS NUMBER: =&AMOUNT;
ROI NUMBER: =&ROI
MAMOUNT NUMBER;
BEGIN
MAMOUNT: =PRINCIPAL+ (PRINCIPAL*ROI/100)*MONTHS;
DBMS_OUTPUT.PUT_LINE (MAMOUNT);
END

Output:
PRINCIPAL=400
ROI=5%
MONTHS=6
MAMOUNT=5200

Practical No.11
Aim: Write a program that accepts radius &calculate area of circle. Use PI as Constant.

DECLARE
RADIUS NUMBER: = &RADIUS
PI NUMBER: = 3.14;
AREA NUMBER;
BEGIN
AREA: = PI *(RADIUS * RADIUS);
DBMS_OUTPUT.PUT_LINE (AREA IS ||AREA);
END

Output :
RADIUS = 40
AREA IS 5024

Practical No.12
Aim: Write a program that accepts number & display whether it is less than or equal to or
greater than 10.

DECLARE
N NUMBER: = 5;
BEGIN
IF N =10 THEN
DBMS_OUTPUT.PUT_LINE (GIVEN NUMBER IS EQUAL TO 10);
ELSE IF N <10 THEN
DBMS_OUTPUT.PUT_LINE (GIVEN NUMBRE IS LESS THAN 10);
ELSE IF N >10 THEN
DBMS_OUTPUT.PUTLIN (GIVEN NUMBER IS GREATER THAN 10);
END IF;
END

Output:
GIVEN NUMBER IS LESS THAN 10.

UNIVERSITY OF MUMBAI
INSTITUTE OF DISTANCE AND OPEN LEARNING (IDOL)*
*(Institute of Distance Education (IDE) is renamed)

CERTIFICATE
THE EXPERIMENTS DULY SIGNED IN THIS JOURNAL REPRESENT
THE BONAFIDE WORK BY MISS ______________________________
ROLL NO.
IN SEMESTER II OF FIRST YEAR OF MASTER IN
COMPUTER APPLICATION (MCA) IN THE COMPUTER LABORATORY
OF PCP CENTER SHREE RAM COLLAGE, BHANDUP FOR SUBJECT
_______________________ DURING ACADEMIC YEAR 2014 -2015 .

____________________

____________________________

LECTURE IN CHARGE

HEAD, DEPARTEMENT OF MCA

______________________
EXTERNAL EXAMINER

INDEX
Data Communication & Networking
SR.NO
1.
2.
3.
4.
5.

6.
7.
8.
9.
10.
11.
12.

CONTENT
Write a program to implement VRC
Write a program to implement LRC
Write a program to implement CRC
Write a program to implement checksum method
Write a program to check and correct the error in
the data at receiver end by implementing hamming
code.
Write a program to generate chipping sequence
using Walsh matrix method
Write a program to implement character level
encryption by mono alphabetic encryption method
Write a program to implement character level
encryption by poly alphabetic encryption method
Write a program to implement bit stuffing
Write a program to shortest path routing algorithm
Write a program to implement RSA Algorithm
Write a program to implement sink tree

SIGNATURE

INDEX
Data Communication & Networking

SR.NO
1.
2.
3.
4.
5.

6.
7.

8.

9.
10.
11.
12.

CONTENT
Write a program to implement VRC
Write a program to implement LRC
Write a program to implement CRC
Write a program to implement
checksum method
Write a program to check and correct
the error in the data at receiver end by
implementing hamming code.
Write a program to generate chipping
sequence using Walsh matrix method
Write a program to implement
character level encryption by mono
alphabetic encryption method
Write a program to implement
character level encryption by poly
alphabetic encryption method
Write a program to implement bit
stuffing
Write a program to shortest path
routing algorithm
Write a program to implement RSA
Algorithm
Write a program to implement sink
tree

Date

Sign

UNIVERSITY OF MUMBAI
INSTITUTE OF DISTANCE AND OPEN LEARNING (IDOL)*
*(Institute of Distance Education (IDE) is renamed)

CERTIFICATE
THE EXPERIMENTS DULY SIGNED IN THIS JOURNAL REPRESENT
THE BONAFIDE WORK BY MISS ______________________________
ROLL NO.
IN SEMESTER III OF SECOND YEAR OF MASTER IN
COMPUTER APPLICATION (MCA) IN THE COMPUTER LABORATORY
OF PCP CENTER SHREE RAM COLLAGE, BHANDUP FOR SUBJECT
_______________________ DURING ACADEMIC YEAR 2014 -2015 .
____________________
LECTURE IN CHARGE

____________________________
HEAD, DEPARTEMENT OF MCA
______________________
EXTERNAL EXAMINER

Practical No .1
#include <stdio.h>
#include <conio.h>
#define MAXSIZE 5
struct stack
/* Structure definition for stack */
{
int stk[MAXSIZE];
int top;
};
typedef struct stack STACK;
STACK s;
/* Function declaration/Prototype*/
void push (void);
int pop(void);
void display (void);
int main ()
{
int choice;
int option = 1;
s.top = -1;
printf ("STACK OPERATION\n");
while (option)
{
printf ("------------------------------------------\n");
printf ("
1
-->
PUSH
\n");
printf ("
2
-->
POP
\n");
printf ("
3
-->
DISPLAY
\n");
printf ("
4
-->
EXIT
\n");
printf ("------------------------------------------\n");
printf ("Enter your choice\n");
scanf ("%d", &choice);
switch (choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: return 0;
}

fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf ("%d", &option);
}
}
/*Function to add an element to the stack*/
void push ()
{
int num;
if (s.top == (MAXSIZE - 1))
{
printf ("Stack is Full\n");
return;
}
else
{
printf ("Enter the element to be pushed\n");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
}
return;
}
/*Function to delete an element from the stack*/
int pop ()
{
int num;
if (s.top == - 1)
{
printf ("Stack is Empty\n");
return (s.top);
}
else
{
num = s.stk[s.top];
printf ("poped element is = %d\n", s.stk[s.top]);
s.top = s.top - 1;
}
return(num);
}
/*Function to display the status of the stack*/
void display ()
{
int i;

if (s.top == -1)
{
printf ("Stack is empty\n");
return;
}
else
{
printf ("\nThe status of the stack is\n");
for (i = s.top; i >= 0; i--)
{
printf ("%d\n", s.stk[i]);
}
}
printf ("\n");
}

Output :

DATA STRUCTURES

INDEX
SR.NO

CONTENT

Write a program create a Stack& addelements into the


stack,delete elementsfrom the same stack.
Write a program to create a Stack.
Write a program to create a Queue, addelements into
the queue & delete elementsfrom the same queue.
Write a program to create a Queue.
Write a program to traverse binary tree in :
1 ) In-order form
2 )Pre-order form
3 )Post-order form
Write a program to count the leaf nodes in binary tree.
Write a program to create a SingleLinked
List, Insert & Delete elements from it.
Write a program to create a singlelinked list
Write a program to implement Bubble Sort
Write a program to implement Heap Sort
Write a program to implement Insertion
Sort
Write a program to sort the given numbers by using
Bubble sort technique.
Write a program to join circular linked lists.
Write a program to join single linked lists.

2
3
4
5

6
7
8
9
10
11
12
13
14

SIGNATURE

Practical No. 2
#include<stdio.h>
#include<conio.h>
#include<alloc.h>

struct stack
{
int data;
struct stack *next;
};

struct stack *pop(struct stack *top);


struct stack *push(struct stack *top);

void main()
{
struct stack *top;
int reply,option,data;
clrscr();
top=NULL;
do
{
printf("\nStack Operations: \n");
printf(" --------------------- ");
printf("\n 1.push \n 2.pop \n 3.exit\n\n");
printf("Select Your option:");
scanf(" %d" ,&option);
switch(option)
{

case 1:top=push(top);
break;
case 2:top=pop(top);
break;
case 3: exit(0);
break;
}
}
while(1);
}
struct stack *push(struct stack *top)
{
struct stack *c;
c=(struct stack*)malloc(sizeof(struct stack));
if(c==NULL)
{
printf("\nlnsufficient Memory! ");
return(top);
}
printf("\nEnter data: ");
scanf("%d",&c->data);
c->next=NULL;
printf("\n\tTha Data item %d has been pushed into the stack \n\n",c->data);
if(top==NULL)
top=c;
else
{
c->next=top;
top=c;
}

return(top);
}
struct stack *pop(struct stack *top)
{
struct stack *c;
if(top== NULL)
{
printf("stack is empty");
return(top);
}
printf("\n\t Popped data is: %d\n\n",top->data);
c=top;
top=top->next;
free(c);
return(top);
}

Output:

Practical No. 3
#include<stdio.h>
#include<conio.h>
#include<alloc.h>

int queue[50],item;
int ch,n=0,front,rear,i;
void main()
{
void create();
void add();
void deletelast();
void display();
do
{
clrscr();
printf("Queue operations");
printf("\n ------------------- \n");
printf("\n1:Create\n2.Add\n3.Delete last\n4.Display\n5.Exit");
printf("\n Enter Your Choice:");
scanf("%d",&ch);
if(ch==1)
{
printf("\nEnter maximum size of queue you wish to have:");
scanf("%d",&n);
}
switch(ch)
{
case 1:create();getch();break;
case 2:add();getch();break;

case 3:deletelast();getch();break;
case 4:display();getch();break;
case 5:exit(0);getch();break;
default:
printf("Invalid choice! Try again ");
break;
}
}
while (ch!=5);
getch();
}
void create()
{
printf("\nCreating a Queue ");
printf("\n---------------------- \n ");
front=0,rear=0;
printf("\nQueue created");
return;
}
void add()
{
if(rear>=n){
printf("\nQueue is full !");
getch();
return;
} else {
printf("\nAdding eleme_ntinto a queue");
printf("\n------------------------- \n");
printf("Enter item to be inserted: ");
scanf("%d",&item);

rear++;
queue[rear]=item;
if(front==0)
front=1 ;
printf("\nItem %d has been inserted into queue" ,item);
printf("\nItems of queue are: ");
for(i=front;i<=rear;i++ )
{
printf(" %d",queue[i]);
}
return;
}
}
void deletelast()
{
printf("\nDeleting element from queue");
printf("\n----------------------------- \n");
if(front==rear){
printf("\nQueue is empty! ");
getch();
return;
}
front++;
item=queue[front];
printf("\nItem %d has been deleted from queue",item);
printf("\nItems of queue are:");
for(i=front;i<=rear;i++)
{
printf(" %d",queue[i]);
}

return;
}
void display(){
printf("\nDisplay all elements of Queue");
printf("\nItems of queue are:");
for(i=front;i<=rear;i++)
{
printf(" %d",queue[i]);
}
return;
}

Output:

Practical No. 4
#include<stdio.h>
#include<conio.h>
#define max 3

int queue[max],data;
int front,rear,reply,option,x;
void main()
{
clrscr();
front=rear=-1;
do {
printf("\nQueue Operations : \n1.Insert into Queue \n2.Delete from Queue\n3.Exit");
printf("\nEnter Your choice: ");
scanf("%d",&option);
switch(option)
{
case 1: printf("\nEnter data to insert:");
scanf("%d", &data);
reply=insertq(queue,&rear,&data);
if(reply==-1)
printf("\nQueue is full! ");
else
printf("\nData %d inserted into Queue successfully !",data);
break;
case 2: reply=deleteq(queue,&rear,&data);
if(reply==-1)
printf("\nQueue is Empty! ");
else
printf("\nData %d is deleted ....",data);

break;
case 3:exit(0);
default: printf("\nInvalide choice ..Try again ");
break;
}
} while(1);
}
int insertq(int queue[max],int *rear, int *data)
{
if(*rear == max-1)
return (-1);
else //doubt about brackets
*rear=*rear+1;
queue[*rear]=*data;
return (1);

}
int deleteq(int queue[max],int *front, int *rear,int *data)
{
if(*front==*rear)
return (-1);
else//doubt about brackets
(*front)++;
*data=queue[*front];
return(1);

Output:

Practical No. 5
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

struct treerec
{
struct treerec *lchild;
struct treerec *rchild;
char data;
};

struct treerec *item;


struct treerec *rdata[50];
void main()
{
int i,n;
clrscr();
printf("\nEnter no of data-items to be entered in tree: ");
scanf("%d" ,&n);
printf("\nEnter data-items: ");
for(i=1;i<=n;i++)
{
rdata[i]=(struct treerec *)malloc(sizeof(struct treerec));
scanf("\r%c",&rdata[i]->data);
rdata[i]->lchild=NULL;
rdata[i]->rchild= NULL;
}
for(i=1;i<=n;i++)
{

rdata[i]->lchild=rdata[2*i];
rdata[i]->rchild=rdata[2*i+1];
}
item=rdata[1];
printf("\nGiven Data in Tree\n");
for(i=1 ;i<=n;i++)
{
printf("%c " ,rdata[i]->data);
}

printf("\n\nInorder tree traversal - \t");


inorder(item);
printf("\n\nPreorder tree traversal - \t");
preorder(item);
printf("\n\nPostorder tree traversal - \t");
postorder(item);
getch();
}
inorder(cnode)
struct treerec *cnode;
{
if(cnode != NULL)
{
inorder(cnode->lchild);
if(cnode->data != '_')
{
printf("%c" ,cnode->data);
}
inorder(cnode->rchild);
}

return (1);
}
preorder(cnode)
struct treerec *cnode;
{
if(cnode != NULL)
{
if(cnode->data != '_')
{
printf("%c" ,cnode->data);
}
preorder(cnode->lchild);
preorder(cnode->rchild);
}
return (1);
}
postorder(cnode)
struct treerec *cnode;
{
if(cnode != NULL)
{
postorder(cnode->lchild);
postorder(cnode->rchild);
if(cnode->data != '_')
{
printf("%c" ,cnode->data);
}
}
return (1);
}

Output:

Practical No. 6
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<alloc.h>

struct node {
int data;
struct node*left;
struct nade*right;
};

unsigned int getleafcount(struct node* node){


if(node==NULL)
return 0;
if(node->left==NULL && node->right==NULL)
return 1;
else
return (getleafcount(node->left)+getleafcount(node->right));
}

struct node*newnode(int data){


struct node*node=(struct node*)malloc(sizeof(struct node));
node->data=data;
node->left= NULL;
node->right= NULL;
return(node);
}
int main(){

struct node *root=newnode(1);


clrscr();
root->left=newnode(2);
root->right=newnode(3);
root->left->left=newnode(4);
root->left->right=newnode(5);
printf("Leaf count of the tree is %d",getleafcount(root));
getch();
return 0;
}

Output:

Practical No. 7
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct studinfo{
int data;
struct studinfo *next;
};
struct studinfo *start=NULL,*ptr,*disp;

void insertnode();
void deletenode();
void display();
void main() {
int ch;
clrscr();
do{
printf("\nMenu:\n------------");
printf("\n1.Insert node \n2.Delete node\n3.Display\n4.Exit");
printf("\nEnter Your Choice:");
scanf("%d",&ch);
fflush(stdin);
switch(ch){
case 1: insertnode();
break;
case 2: deletenode();
break;
case 3: display();
break;

case 4: exit(1);
break;
default:printf("\nInvalid choice entered! Enter again..");
break;
}
} while(1);
}

void insertnode(){
struct studinfo *newnode;
newnode=(struct studinfo *)malloc(sizeof(struct studinfo ));
printf("\nEnter data of for the node to be inserted .");
scanf("%d",&newnode->data);
ptr=start;
if(start == NULL){
start=newnode;
newnode->next= NULL;
ptr=newnode;
printf("\n\New node with data:%d inserted",newnode->data);
} else {
ptr->next=newnode;
newnode->next= NULL;
ptr=newnode;
printf("\nNew node with data:%d inserted",newnode->data);
}
fflush(stdin);
}

void deletenode(){
struct studinfo *del;

if( start== NULL)


printf("\nList is empty");
else {
ptr=start;
start=start->next;
free(ptr);
printf("\nDeleted");
}
}

void display(){
ptr=start;
for(disp=start; disp!=NULL; disp=disp->next){
if(ptr== NULL)
printf("\nList is empty");
else{
ptr=ptr->next;
printf("\nData: %d",disp->data);
}
}
}

Output:

Practical No. 8
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node* add(struct node *head, int data)
{
struct node *tmp;
if(head == NULL)
{
head=(struct node *)malloc(sizeof(struct node));
if(head == NULL)
{
printf("\nError! memory is not available");
exit(0);
}
head-> data = data;
head-> next = head;
}
else
{
tmp = head;
while (tmp-> next != head)
tmp = tmp-> next;
tmp-> next = (struct node *)malloc(sizeof(struct node));
if(tmp -> next == NULL)
{

printf("\nError! memory is not available");


exit(0);
}
tmp = tmp-> next;
tmp->data = data;
tmp->next = head;
}
return head;
}

void printlist(struct node *head){


struct node *current;
current = head;
if(current!= NULL){
do{
printf("%d\t",current->data);
current = current->next;
} while (current!= head);
printf("\n");
} else
printf("\nThe list is empty");
}

void destroy(struct node *head){


struct node *current, *tmp;
current = head->next;
head->next = NULL;
while(current != NULL){
tmp = current->next;
free(current);

current = tmp;
}
}

void main(){
struct node *head = NULL;
clrscr();
head = add(head,1);
printlist(head);
head = add(head,20);
printlist(head);
head = add(head,10);
printlist(head);
head = add(head,5);
printlist(head);
destroy(head);
getch();
}

Output:

Practical No. 9
#include <stdio.h>
#include <conio.h>

void main(){
int i, j, temp;
int arr[5] = {25, 17,31,13,2};
clrscr();
printf("Bubble sort.\n" );
printf("\nArray before sorting:\n");
for (i = 0; i <= 4; i++)
printf("%d\t", arr[i]);

for (i = 0; i <= 3; i++){


for ( j = 0 ; j <= 3 - i ; j++ ){
if(arr[j] > arr[j+1]){
temp = arr[j] ;
arr[j] = arr[j + 1] ;
arr[j + 1] = temp;
}
}
}
printf ( "\n\nArray after sorting:\n") ;
for ( i = 0 ; i <= 4 ; i++ )
printf ( "%d\t", arr[i] ) ;
getch();
}

Output:

Practical No. 10
#include <stdio.h>
#include <conio.h>
void makeheap (int [], int);
void heapsort (int [], int);

void main(){
int arr[10] = {11,2,9,13,57,25,17,1,90,3};
int i ;
clrscr();
printf("Heap Sort.\n");
makeheap(arr, 10);
printf("\nBefore Sorting:\n");
for(i=0; i<=9; i++)
printf("%d\t", arr[i]);
heapsort(arr, 10);
printf("\nAfter Sorting:\n");
for (i=0;i<=9;i++)
printf ("%d\t", arr[i]);
getch();
}
void makeheap(int x[],int n){
int i, val, s, f;
for (i=1;i < n;i++){
val = x[i];
s=i;
f=(s-1)/2;
while (s>0 && x[f]<val){
x[s] = x[f];
s=f;

f=(s-1)/2;
}
x[s] = val;
}
}

void heapsort (int x[], int n){


int i, s, f, ivalue ;
for (i=n-1;i>0;i--){
ivalue=x[i];
x[i]=x[0];
f=0;
if(i== 1)
s=-1;
else
s=1;
if(i>2 && x[2]>x[1])
s=2;
while(s>=0 && ivalue<x[s]){
x[f]=x[s];
f=s;
s=2*f+1;
if(s+1<=i-1 && x[s]<x[s+1])
s++;
if (s>i-1)
s=-1;
}
x[f]=ivalue;
}
}

Output:

Practical No. 11
#include <stdio.h>
#include <conio.h>
void main(){
int arr[5] = {25,17,31,13,2};
int i,j,k,temp;
clrscr();
printf ("Insertion sort.\n");
printf ("\nArray before sorting:\n");
for (i=0; i<=4; i++)
printf("%d\t", arr[i]);
for (i=1; i<=4; i++){
for (j=0; j<i; j++){
if (arr[j] > arr[i]){
temp = arr[j];
arr[j] = arr[i];
for (k=i; k>j; k--)
arr[k] = arr[k - 1];
arr[k + 1] = temp;
}
}
}
printf("\n\nArray after sorting:\n");
for(i=0; i<=4; i++)
printf( "%d\t", arr[i]);
getch();
}

Output:

Practical No. 12
#include <stdio.h>
#include <conio.h>
void main(){
int i, j,arr[50],temp;
clrscr();
for(i=0;i<5;i++){
printf("Enter no. %d: ",i+ 1);
scanf("%d" ,&arr[i]);
}
printf ( "\nBubble sort.\n" ) ;
printf ( "\n\nArray before sorting:\n\n\t") ;
for ( i = 0 ; i <= 4; i++ )
printf("%d\t", arr[i]) ;
for ( i= 0 ; i <= 3 ; i++ ){
for (j = 0 ; j <= 3 - i ;j++ ){
if ( arr[j] > arr[j + 1] ){
temp = arr[j] ;
arr[j] = arr[j + 1] ;
arr[j + 1] = temp;
}
}
}
printf ( "\n\nArray after sorting:\n\n") ;
for ( i = 0 ; i <= 4 ; i++ )
printf("\t%d", arr[i] );
getch();
}

Output:

UNIVERSITY OF MUMBAI
INSTITUTE OF DISTANCE AND OPEN LEARNING (IDOL)*
*(Institute of Distance Education (IDE) is renamed)

CERTIFICATE
THE EXPERIMENTS DULY SIGNED IN THIS JOURNAL REPRESENT
THE BONAFIDE WORK BY MISS ______________________________
ROLL NO.
IN SEMESTER III OF SECOND YEAR OF MASTER IN
COMPUTER APPLICATION (MCA) IN THE COMPUTER LABORATORY
OF PCP CENTER SHREE RAM COLLAGE, BHANDUP FOR SUBJECT
_______________________ DURING ACADEMIC YEAR 2014 -2015 .

____________________

____________________________

LECTURE IN CHARGE

HEAD, DEPARTEMENT OF MCA

______________________
EXTERNAL EXAMINER

INDEX
Object Oriented Programming in c++
SR.NO

1.
2.
3.
4.

5.
6.

7.
8.
9.
10.

CONTENT

Write a program to handle inline function


Write a program to handle function
overloading.
Write a program for constructor overloading.
Write a program using simple array of
character as well as c++ string try reversal of
string.
Write a program for counting words, lines,
and character.
Write a program to create bank account class
which maintains info of account holder as
array of objects.
Write a program to implement operator
overloading for string concatenation.
Write a program for exception with
arguments & try with multiple catch.
Write a program to specify data in exception
class & extracting data from exception object.
Write a program to open a file in binary
mode.

SIGNATURE

INDEX
Object Oriented Programming in c++
SR.NO
1.
2.
3.
4.

5.
6.

7.

CONTENT
Write a program to handle inline
function
Write a program to handle function
overloading.
Write a program for constructor
overloading.
Write a program using simple array of
character as well as c++ string try reversal
of string.
Write a program for counting words,
lines, and character.
Write a program to create bank account
class which maintains info of account
holder as array of objects.
Write a program to implement operator
overloading for string concatenation.

8.

Write a program for exception with


arguments &try with multiple catch.

9.

Write a program to specify data in


exception class & extracting data from
exception object.
Write a program to open a file in binary
mode.

10.

Date

Sign

Aim: Program to demonstrate inline function.

#include<iostream.h>
#include<conio.h>
class line
{
public:
inline float mul(float x,float y)
{
return(x*y);
}
inline float cube(float x)
{
return(x*x*x);
}
};
void main()
{
line obj;
float val1,val2;
clrscr();
cout<<"Enter two values:";
cin>>val1>>val2;
cout<<"\nMultiplication value is:"<<obj.mul(val1,val2);
cout<<"\n\nCube value is:"<<obj.cube(val1)<<"\t"<<obj.cube(val2);
getch();
}

Output:Enter two values: 5 7


Multiplication Value is: 35
Cube Value is: 25 and 343

Aim: Program to demonstrate function overloading.

#include<iostream.h>
#include<stdlib.h>
#include<conio.h>
#define pi 3.14
class fn
{
public:
void area(int); //circle
void area(int,int); //rectangle
void area(float ,int,int);

//triangle

};
void fn::area(int a)
{
cout<<"Area of Circle:"<<pi*a*a;
}
void fn::area(int a,int b)
{
cout<<"Area of rectangle:"<<a*b;
}
void fn::area(float t,int a,int b)
{
cout<<"Area of triangle:"<<t*a*b;
}
void main()
{
int ch;
int a,b,r;
clrscr();
fn obj;
cout<<"\n\t\tFunction Overloading";
cout<<"\n1.Area of Circle\n2.Area of Rectangle\n3.Area of
Triangle\n4.Exit\n:;
cout<<Enter your Choice:";
cin>>ch;

switch(ch)
{
case 1:
cout<<"Enter Radious of the Circle:";
cin>>r;
obj.area(r);
break;
case 2:
cout<<"Enter Sides of the Rectangle:";
cin>>a>>b;
obj.area(a,b);
break;
case 3:
cout<<"Enter Sides of the Triangle:";
cin>>a>>b;
obj.area(0.5,a,b);
break;
case 4:
exit(0);
}
getch();
}

Output: Function Overloading


1. Area of Circle
2. Area of Rectangle
3. Area of Triangle
4. Exit
Enter Your Choice: 2
Enter the Sides of the Rectangle: 5 5
Area of Rectangle is: 25

Aim: Program to demonstrate constructor overloading.

#include<iostream>
#include<conio.h>
using namespace std;
class Example

// Variable Declaration
int a,b;
public:
//Constructor wuithout Argument
Example()

// Assign Values In Constructor


a=50;
b=100;
cout<<"\nIm Constructor";
}
//Constructor with Argument
Example(int x,int y)

// Assign Values In Constructor


a=x;
b=y;
cout<<"\nIm Constructor";
}
void Display()

cout<<"\nValues :"<<a<<"\t"<<b;
}
};
int main()

Example Object(10,20);
Example Object2;
// Constructor invoked.
Object.Display();

Object2.Display();
// Wait For Output Screen
getch();
return 0;
}

Output :Im Constructor


Im Constructor
Values :10

20

Values :50

100

Aim: Program to reverse the string with customize string class and with the help of string
header file

#include<iostream.h>
#include<stdio.h>
#include<string.h>
#define MAX 50
class string
{
char str[Max];
public:
//Operator overloading fro the inputeding string from console
Friend void operator >>(istream& din,string&s1)
{
din>>s1.str;
}
//Operator overloading for the outputting string to console
friend void operator <<(ostream&dout,string&s1)
{
dout<s1.str;
}
//concatenated operation is done with operator
string reverse();
String()
{
strcpy(str,);
}string(char ss[])
{
strcpy(str,s);
}
};

string string::reverse()
{
char rev[Max];
strcpy(rev,str);
strrev(rev);
string s(rev);
return s;
}
void main()
{
string s1,s2,s3;
clrscr();
cout<<Enter the string;
cin>>s1;
s2=s1.reverse();
cout<<s2;
getch();
}

Output:Enter the string


Shri
Reverse String
irhS

Aim: Program to count words, lines & characters.

#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
#define MAX_ROW 5
#define MAX_COL 80
void main(){
char name[MAX_ROW][MAX_COL],c;
int lines=1; //bcoz. first line will be
left to count.int words=1; //bcoz. first word will be left to count.int
chars=1; //bcoz. first char will be left to count.
clrscr();
cout<<"===Input Status===\n";
cout<<"Enter string termanate by # : ";
cin.get(c);

//Finding no. of lineswhile(c != '#'){


cin.get(c);
chars++;
if(c==' ' || c=='\n')
words++;
if(c=='\n')
lines++;
}

cout<<"\n"<<setw(20)<<"Particulars"<<setw(20)<<"Details\n";
cout<<"-------------------------------------\n";

cout.setf(ios::left,ios::adjustfield);
cout<<"\n"<<setw(20)<<"No. of lines

";

cout.setf(ios::right,ios::adjustfield);
cout<<setw(15)<<lines;

cout.setf(ios::left,ios::adjustfield);
cout<<"\n"<<setw(20)<<"No. of Words

";

cout.setf(ios::right,ios::adjustfield);
cout<<setw(15)<<words;

cout.setf(ios::left,ios::adjustfield);
cout<<"\n"<<setw(20)<<"No. of Characters
cout.setf(ios::right,ios::adjustfield);
cout<<setw(15)<<chars;

getch();

Output:===Input Status ====


Enter string termanante by #: Hello World !!!
Abcd
Efgh C++ Programming
Particular

Details

No of line

No of words 9
NO of characters 52

";

Aim: Program to create bank account class which maintains info of account holder as
array of objects

.
#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<iomanip>
#include<conio.h>
using namespace std;
class Bank
{
char fname[20],sname[20];
long acc;
float amount;
public:
void getdata()
{
cout<<"Enter account no:\t" ;
cin>>acc;
cout<<"\nEnter first name of account holder ";
cin>>fname;
cout<<"\nEnter last name of the account holder ";
cin>>sname;
cout<<"\nEnter ledger balance of the account ";
cin>>amount;
}
void display()
{
cout<<"\nAccount number\t :"<<setw(10)<<acc;
cout<<"\nName \t:"<<fname<<" "<<sname;
cout<<"\nBalance \t:"<<amount;
}
};
int main()
{
int i,j=0,num=0;
Bank b[5];
cout<<"Enter totoal no of customer(maximum 5) :";
cin>>num;
for(i=0;i<num;i++)
{
j++;
cout<<"Enter for account "<<j<<"\n";
b[i].getdata();
}
j=0;
cout<<"----------------------------";

for(i=0;i<num;i++)
{
b[i].display();
}
}
/*
Output :Enter
Enter
Enter
Enter

account no
first name of account holder
last name of account holder
ledger balance of the account

:123456789
:Ram
:sanket
:1000

Enter
Enter
Enter
Enter

account no
first name of account holder
last name of account holder
ledger balance of the account

:98707137455
:Laksman
:sanket
:1500

---------------------------------------------Account number
:123456789
Name
:Ram sanket
Balance
:1000
Account number
:98707137455
Name
:Laksman sanket
Balance
:1500
Process returned 0 (0x0)
*/

execution time : 35.159 s

Aim: Program to implement operator overloading for string concatenation

#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<iomanip>
#include<string.h>
#include<conio.h>
using namespace std;
class string_concat
{
char name[20];
public:
void input()
{
gets(name);
}
void output()
{
cout<<name<<endl;
}
string_concat operator+(string_concat s2)
{
string_concat s;
strcpy(s.name," ");
strcat(s.name,strcat(name," "));
strcat(s.name,s2.name);
return(s);
}
};
int main()
{
string_concat s1,s2,s3;
cout<<"Enter string one: ";
s1.input();
cout<<"Enter string two: ";
s2.input();
cout<<"string one is: ";
s1.output();
cout<<"string two is: ";
s2.output();
s3=s1+s2;

cout<<"Concatenated string
s3.output();

is: ";

getch();
}
Output :Enter string one: shree
Enter string two: ram
string one is: shree
string two is: ram
Concatenated string is:

shree ram

Aim: Program for exception handling with try and multiple catch

#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<iomanip>
#include<string.h>
#include<conio.h>
using namespace std;
void test(int x)
{
try
{
if(x>0)
throw x;
else
throw 'x';
}
catch(int x)
{
cout<<"Catch a integer and that integer is:\n"<<x;
}
catch(char x)
{
cout<<"Catch a character and that character is:\n"<<x;
}
}
int main()
{
cout<<"Testing multiple catches\n:";
test(10);
test(0);
getch();
}
Output:Testing multiple catches
Catch a integer and that integer is: 10
Catch a character and that character is: x

Aim: Program for handling customize exception in c++


#include <iostream>
#include<stdio.h>
#include<iomanip>
#include<string.h>
#include<conio.h>
using namespace std;
class MyDivideByZeroException:public exception
{
public:
const char* what()
{
return "Divide By Zero Exception \n";
}
};
int main()
{
try
{
int a,b;
cout<<"Enter two number :";
cin>>a>>b;
if compute a/b
if(b==0)
{
MyDivideByZeroException d;
throw d;
}
else
{
cout<"a/b ="<<a/b<<endl
}
}
catch(exception& e)
{
cout<<e.what()<<endl;
}
getch();
}
Ouptut:$ a.out
Enter two number :10 2
a/b =5;
Enter tow number :10 0
Divide By Zero Exception

Aim: Program to Open file in binary mode


#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<iomanip>
#include<string.h>
#include<conio.h>
using namespace std;
class student
{
int admno;
char name[20];
public:
void getdata();
void showdata();
intreadadmno();
};
void student::getdata()
{
cout<<"\Enter the admission no :"
cin>>admno;
cout<<"\n Enter your name :";
gets(name);
}
void student::showdata()
{
cout<<"\n Admission no :="<<admno;
cout<<"\nNameL=";
puts(name);
}
int student::readadmno()
{
return admno;
}
void write_data()
{
student obj;
ofstream fp2;
fp2.open("student.dat",ios::binary|ios::app);
obj.getdata();
int objesixe =sizeof(obj);
fp2.write((char *)&obj,objsize);
fp2.close();
}
void display()
{

student obj;
ofstream fp1;
fp1.open("student.dat",ios::binary);
int objesize =sizeof(obj);
while(fp1.read(char*)&obj,objsize);
{
obj.shodata();
}
fp1.close();
}
void main()
{
clrscr();
write_datat();
display();
getch();
}

/*
Output:-

Enter the admission no 1


Enter your name Yash
admission no:=1
name:=Yash

*/

Вам также может понравиться