Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

OBJECT ORIENTED PROGRAMMING

(OOP)
SUBJECT CODE: SE 203

LAB FILE
Submitted by –
Yash Yadav(2K20/SE/164)
Batch – SE A2 (2 nd year)
Submitted to –
Mrs. Sonali Chawla

DEPARTMENT OF SOFTWARE ENGINEERING


DELHI TECHNOLOGICAL UNIVERSITY, SHAHBAD
DAULATPUR
(FORMERLY DELHI COLLEGE OF ENGINEERING)
MAIN BAWANA ROAD, Delhi 110042
INDEX

S. Experiment
No.
C++ Programs
Write a C++ program to print your personal details name, surname
1. (single character), total marks, gender(M/F), result(P/F) by taking
input from the user.
1) Create a class called Employee that has “Empnumber‟ and
“Empname‟ as data members and member functions getdata( ) to
input data display() to output data. Write a main function to create
2. an array of ‟Employee‟ objects. Accept and print the details of at
least 6 employees.
2) Write a program to implement a class called ComplexNumber
and write a function add() to add two complex numbers.
Write a C++ program to swap two number by both call by value
and call by reference mechanism, using two functions swap_value()
3.
and swap_reference respectively , by getting the choice from the
user and executing the user’s choice by switch-case.
Write a C++ program to create a simple banking system in which
the initial balance and the rate of interest are read from the
keyboard and these values are initialized using the constructor. The
destructor member function is defined in this program to destroy
the class object created using constructor member function. This
program consists of following member functions:
4. i. Constructor to initialize the balance and rate of interest
ii. Deposit - To make deposit
iii. Withdraw – To with draw an amount
iv. Compound – To find compound interest
v. getBalance – To know the balance amount
vi. Menu – To display menu options
vii. Destructor
Write a program to accept five different numbers by creating a class
called friendfunc1 and friendfunc2 taking 2 and 3 arguments
5.
respectively and calculate the average of these numbers by passing
object of the class to friend function.
Write a program to accept the student detail such as name and 3
different marks by get_data() method and display the name and
6.
average of marks using display() method. Define a friend class for
calculating the average of marks using the method mark_avg().

Write a C++ program to perform different arithmetic operation such


7. as addition, subtraction, division, modulus and multiplication using
inline function.

8. WAP to return absolute value of variable types integer and float


using function overloading.

WAP to perform string operations using operator overloading in


C++
9. i. = String Copy
ii. ==,>,< Equality
iii. + Concatenation
Consider a class network of figure given below. The class master
derives information from both account and admin classes which in
turn derive information from the class person. Define all the four
classes and write a program to create, update and display the
information contained in master objects. Also demonstrate the use
of different access specifiers by means of member variables and
member functions.

10.
Write a C++ program to create three objects for a class named
pntr_obj with data members such as roll_no and name. Create a
11. member function set_data() for setting the data values and print()
member function to print which object has invoked it using ‘this’
pointer
Write a C++ program to explain virtual function (polymorphism) by
creating a base class c_polygon which has virtual function area().
12. Two classes c_rectangle and c_triangle derived from c_polygon and
they have area() to calculate and return the area of rectangle and
triangle respectively.
Write a program to explain class template by creating a template T
for a class named pair having two data members of type T which
13. are inputted by a constructor and a member function get-max()
return the greatest of two numbers to main. Note: the value of T
depends upon the data type specified during object creation.
Write a C++ program to illustrate:
i. Division by zero
14. ii. Array index out of bounds exception
Also use multiple catch blocks.
Java Programs
Write a Java program that takes two numbers as input and display
1.
the addition and product of two numbers.

2. Write a Java program to print the area and perimeter of a circle.


Create a class with a main( ) that throws an object of class
Exception inside a try block. Give the constructor for Exception a
3. String argument. Catch the exception inside a catch clause and print
the String argument. Add a finally clause and print a message to
prove you were there.
Create a class with a main( ) that throws an object of class
Exception inside a try block. Give the constructor for Exception a
4. String argument. Catch the exception inside a catch clause and print
the String argument. Add a finally clause and print a message to
prove you were there.
Class Assignments
1. WAP showing the use of pointers to the derived class objects.
2. WAP that uses classes to allocate object's memory using dynamic
memory allocation.
3. A) Print Hello world
B) Addition of 2 numbers
C) Input 5 subject marks of a student and calculate their average
D) Find area of a circle
E) Input a number from a user and check whether it is positive,
negative or zero
4. Write a Program showing the use of pointers to the derived class
objects.

EXPERIMENT –1
AIM- Write a C++ program to print your personal details name,
surname (single character), total marks, gender(M/F), result(P/F) by
taking input from the user.
CODE
#include <iostream>
using namespace std;
class Student{
public:
string name,surname;
int marks=0;

char gender,result;

void input(){

cout << "enter your name\n";

cin >> name;

cout << "enter your surname\n";

cin>> surname;
int arr[5];

cout << "enter marks obtained in Physics ,Chemistry ,Maths ,Biology ,English out of 100 respectively\n ";
for (int i = 0; i < 5; i ++)

cin >> arr[i];

for (int i = 0; i < 5; i ++)

{
marks += arr[i];
}
cout << "enter your gender\n";
if(marks > 200 ){
result = 'P';
}

else

{
result = 'F';

cin >> gender;

}
void output(){
cout<<"Name: "<<name<<" "<<surname<<"\n";
cout<<"Total Marks: "<<marks<<"\n";
cout<<"Gender: "<<gender<<'\n';
cout<<"Result: "<<result;

};
int main(){

Student s;

s.input();

s.output();

return 0;
}

OUTPUT
EXPERIMENT -2
AIM- Create a class called 'Employee' that has “Empnumber‟ and
“Empname‟ as data members and member functions getdata( ) to
input data display() to output data. Write a main function to create an
array of ‟Employee‟ objects. Accept and print the details of at least 6
employees.
CODE
#include<iostream>

#include<stdio.h>

using namespace std;

class employee{

int empnumber;

char empname[20];
public:

void getdata();

void display();

};

void employee :: getdata(){

cout<<"Enter Employee Details\nEmployee Number:\t";

cin>>empnumber;

fflush(stdin);

cout<<"Employee Name:\t";

gets(empname);

}
void employee :: display(){

cout<<"\nEmployee Number:"<<empnumber<<endl;

cout<<"Employee Name:\t";

puts(empname);

int main(){

employee S[6];

for(int i = 0; i < 6; i++){

S[i].getdata();

}
for(int i = 0; i < 6; i++){

S[i].display();

return 0;

OUTPUT
EXPERIMNET-3
AIM - Write a C++ program to swap two number by both call by
value and call by reference mechanism, using two functions
swap_value() and swap_reference
respectively, by getting the choice from the user and executing the
user’s
choice by switch-case.
CODE
#include<iostream>
using namespace std;
void swap_value( int a , int b)
{
int temp;
temp = a;
a=b;
b= temp;
cout<<"After swapping a = "<<a<<" and b = "<<b;
return ;
}
void swap_reference( int *a , int *b)
{
int temp;
temp = *a;
*a= *b;
*b = temp;
cout<<"After swapping a = "<<*a<<" and b = "<<*b;
return ;

int main()

int a,b;

cout<<"Enter the value of a - ";

cin>>a;

cout<<"Enter the value of b - ";

cin>>b;
cout<<"Before swapping a = "<<a<<" and b = "<<b<<endl;

cout<<"1. Swap using call by value"<<endl;

cout<<"2. Swap using call by reference"<<endl;

cout<<"Enter your choice - ";

int n;

cin >>n;

switch(n)

{
case 1 :
swap_value(a , b);
break;
case 2 :
swap_reference( &a , &b);
break;
default :
cout<<"wrong input!";
}

return 0;
}

OUTPUT -
EXPERIMENT- 4
AIM- Write a C++ program to create a simple banking system in
which the initial balance and the rate of interest are read from the
keyboard and these values are initialized using the constructor. The
destructor member function is defined in this program to destroy the
class object created using constructor member function. This program
consists of following member functions-

1. Constructor to initialize the balance and rate of interest


2. Deposit - To make deposit
3. Withdraw – To with draw an amount
4. Compound – To find compound interest
5. getBalance – To know the balance amount
6. Menu – To display menu options
7. Destructor

CODE
#include <iostream>

using namespace std;

#include<cmath>

class Bank{

float amount ;

float roi;

public:

Bank(float a , float b){

amount = a;

roi = b;

}
void withdraw()

int money;

cout << "Enter amount to withdraw " << endl;

cin >> money;

if(money> amount)

cout << "Insufficient Balance" << endl;

else

amount -= money;

cout << "Your Balance is : " << amount;

void getBalance(){

cout << "Your Balance is : " << amount;

void deposit(){

int money;

cout << "Enter amount to deposit " << endl;

cin >> money;

amount += money;

cout << "Your Balance is : " << amount;

}
void compound(){

float time;

cout << "Enter time duration" << endl;

cin >> time;

int compountInterest = (amount) * (pow((1 + (roi/100)),


time));
cout << "Compount Interest is : " << compountInterest <<
endl;
}
void menu(){
cout << " \n\n1.Deposit Money\n2.WithdrawMoney\n3.Calculate Compound
Interest\n4.Balance\n5.Destructor\nEnter the Number : " << endl;
}
~Bank()
{
cout << "Destructor called" << endl;
}
};

int main()

float a=0, b = 2;

Bank s(a, b);

s.menu();

int number;

cin >> number;

while(number != 5){

switch (number)

case 1 :

s.deposit();

break;
case 2 :

s.withdraw();

break;

case 3:

s.compound();
break;

case 4:
s.getBalance();

break;
case 5:
cout << "You have quit the system succesfully";

return 0;
default:
cout << "Invalid operation!! Please try again" <<

endl;
break;
}
s.menu();
cin >> number;
}
cout << "You have quit the system succesfully" << endl;
return 0;
}

OUTPUT
EXPERIMENT -5
AIM- Write a program to accept five different numbers by creating a
class called friendfunc1 and friendfunc2 taking 2 and 3 arguments
respectively and calculate the average of these numbers by passing
object of the class to friend function

CODE
#include<iostream>

using namespace std;

class friendFunc2;

class friendFunc1

   {

  int a1,a2;
      public:
          friendFunc1(int x,int y)

     {

              a1=x;

              a2=y;

     }
          friend float average(friendFunc1 f1,friendFunc2 f2);
      };
class friendFunc2
   {
int a3,a4,a5;
      public:

          friendFunc2(int x,int y,int z)


     {

              a3=x;

              a4=y;

              a5=z;

     }
          friend float average(friendFunc1 f1,friendFunc2 f2);

      };
float average(friendFunc1 f1, friendFunc2 f2)

  return (f1.a1 + f1.a2 + f2.a3 + f2.a4 + f2.a5) / 5.0;

}
int main()

  friendFunc1 obj1(17, 10);

  friendFunc2 obj2(8, 7, 9);

  float ans = average(obj1, obj2);


  cout << "Average : " << ans << endl;

}
OUTPUT
EXPERIMENT – 6
AIM- Write a program to accept the student detail such as name and 3
different marks by get_data() method and display the name and
average of marks using display() method. Define a friend class for
calculating the average of marks using the method mark_avg().
CODE
#include<bits/stdc++.h>
#include<conio.h>
using namespace std;

class student
{
char name[20];
int mark1,mark2,mark3;
friend class friendclass;

public:
void get_data()
{
cout<<"\nEnter name:";
cin>>name;
cout<<"\nEnter 3 marks:";
cin>>mark1>>mark2>>mark3;
}
void display(int a)
{
cout<<"\nOutput\n ";
cout<<"=============\n";
cout<<"\nName ="<<name;
cout<<"\nAverage ="<<a;
}
};
class friendclass
{
public:
void mark_avg(student &stud)
{
int avg=(stud.mark1+stud.mark2+stud.mark3)/3;
stud.display(avg);
}
};
int main()
{
student s;
s.get_data();
friendclass obj;
obj.mark_avg(s);
getch();
return 0;
}
OUTPUT
EXPERIMENT – 7
AIM - Write a C++ program to perform different arithmetic operation
such as addition, subtraction, division, modulus and multiplication
using inline function.
CODE
#include<iostream>
using namespace std;
class operations
{
int i , j;
public :
void get_data(int a , int b)
{
i = a;
j = b;
return;
}
void put_data()
{
cout<<"a = "<<i<<endl;
cout<<"b = "<<j<<endl;
return;
}
inline int add()
{
return i+j;
}
inline int subtract()
{
return i-j;
}
inline int multiply()
{
return i*j;
}
inline int divide()
{
return i/j;
}
inline int modulus()
{
return i%j;
}
};
int main()
{
operations op;
cout<<"Enter the numbers - ";
int a , b;
cin>>a>>b;
op.get_data(a,b);
op.put_data();
cout<<"MENU - "<<endl;
fn1 :
int x;
cout<<"1. Add"<<endl;
cout<<"2. Subtract"<<endl;
cout<<"3. Multiply"<<endl;
cout<<"4. Divide"<<endl;
cout<<"5. Modulus"<<endl;
cout<<"6. Exit"<<endl;
cout<<"Enter your choice - ";
cin>>x;
switch (x)
{
case 1 :
{
cout<<"a + b = "<<op.add()<<endl;
goto fn1;
}
case 2 :
{
cout<<"a - b = "<<op.subtract()<<endl;
goto fn1;
}
case 3 :
{
cout<<"a * b = "<<op.multiply()<<endl;
goto fn1;
}
case 4 :
{
cout<<"a / b = "<<op.divide()<<endl;
goto fn1;
}
case 5 :
{
cout<<"a % b = "<<op.modulus()<<endl;
goto fn1;
}
case 6 :
{
return 0;
}
}
}
OUTPUT-
EXPERIMENT – 8
AIM - WAP to return absolute value of variable types integer and
float using function overloading.

CODE
#include<iostream>
using namespace std;
class Absol{
public:
void absolute(int& x);
void absolute(float& x);
};
void Absol::absolute(int& x){
cout<<"Inside void absolute(int& x)";
if(x < 0){
x = -x;
}
}
void Absol::absolute(float& x){
cout<<"Inside void absolute(float& x)";
if(x < 0.0){
x = -x;
}
}
int main(){
Absol S;
cout<<"\nEnter an integer : ";
int x;
cin>>x;
S.absolute(x);
cout<<"\nAbsolute = "<<x;
cout<<"\n\nEnter a floating point number : ";
float y;
cin>>y;
S.absolute(y);
cout<<"\nAbsolute = "<<y;
}
OUTPUT-
EXPERIMENT – 9
AIM - WAP to perform string operations using operator overloading
in C++

1. String Copy
2. ==,&lt;,&gt; Equality
3. + Concatenation
CODE
#include <iostream>
#include <stdio.h> //for gets() and puts()
#include <string.h>
using namespace std;

class String{
string str;

public:
String()
{
str = "";
}
String(string s)
{
str = s;
}
void operator=(String s);
String operator+(String s);
bool operator==(String s);
bool operator<(String s);
bool operator>(String s);
void show();
};

void String :: operator=(String s){


cout << "Operator Overloaded=\n";
str = s.str;
}

String String :: operator+(String s){


String temp;
cout << "Operator Overloaded+\n";
temp.str = str + s.str;
return temp;
}

bool String :: operator==(String s){


if (str == s.str)
return true;
return false;
}

bool String :: operator<(String s){


int x = min(str.size(), s.str.size());
for (int i = 0; i < x; i++)
{
if (str[i] < s.str[i])
return true;
else if(str[i] > s.str[i])
return false;
}
return false;
}

bool String :: operator>(String s){


int x = min(str.size(), s.str.size());
for (int i = 0; i < x; i++)
{
if (str[i] > s.str[i])
return true;
else if(str[i] < s.str[i])
return false;
}
return false;
}

void String :: show(){


cout << str << "\n";
}

int main(){
String s1("Sehnish"), s2("Dagar"), ch;
cout<<"String s1 - ";
s1.show();
cout<<"String s2 - ";
s2.show();
s1 = s1 + s2;
ch = s1;
cout<<"String s1 after concatenation - ";
s1.show();
ch.show();
if(s1 < s2)
cout <<"s2 is longer than s1!";
else
cout <<"s1 is longer than s2!";
return 0;
}
OUTPUT
EXPERIMENT – 10
AIM - Consider a class network of figure given below. The class
master derives information from both account and admin classes
which in turn derive information from the class person. Define all
the four classes and write a program to create, update and display
the information contained in master objects. Also demonstrate the
use of different access specifiers by means of member variables
and member functions.

CODE
#include<iostream>
using namespace std;
class person{
private:
string name;
int code;
public:
person(string s, int c){
name = s;
code = c;
cout<<"\nPerson constructor called";
}
void display();
void updateName(string);
void updateCode(int);
};
class account: virtual public person{
private:
int pay;
public:
account(string s, int c, int p):person(s, c){
pay = p;
cout<<"\nAccount constructor called";
}
void display();
void updatePay(int);
};
class admin: virtual public person{
private:
int experience;

public:
admin(string s, int c, int exp):person(s, c){
experience = exp;
cout<<"\nAdmin constructor called";
}
void display();
void updateExp(int);
};
class master: public account, public admin{
public:
master(string s, int c, int p, int exp):account(s,c,p),admin(s,c,exp),person(s, c){
cout<<"\nMaster constructor called";
}
void update();
void display();
};
void person :: display(){
cout<<"\nName = "<<name;
cout<<"\nCode = "<<code;
}
void person :: updateName(string s){
name = s;
}
void person :: updateCode(int n){
code = n;
}
void account :: display(){
cout<<"\nPay = "<<pay;
}
void account :: updatePay(int n){
pay = n;
}
void admin :: display(){
cout<<"\nExperience = "<<experience;
}
void admin :: updateExp(int n){
experience = n;
}
void master :: update(){
//this->display();
cout<<"\n\nUPDATE DETAILS";
string n;
int c, p, exp;
cout<<"\nName = ";
cin>>n;
cout<<"\nCode = ";
cin>>c;
cout<<"\nPay = ";
cin>>p;
cout<<"\nExperience = ";
cin>>exp;
updateName(n);
updateCode(c);
updatePay(p);
updateExp(exp);
}
void master :: display(){
cout<<"\n\nMASTER DETAILS";
person::display();
account::display();
admin::display();
}
int main(){
//master M;
string n;
int c, p, exp;
cout<<"\nName = ";
cin>>n;
cout<<"\nCode = ";
cin>>c;
cout<<"\nPay = ";
cin>>p;
cout<<"\nExperience = ";
cin>>exp;
master M(n,c,p,exp);
M.display();
M.update();
M.display();
return 0;
}

OUTPUT
EXPERIMENT – 11
AIM- Write a C++ program to create three objects for a class named
pntr_obj with data members such as roll_no and name . Create a
member function set_data() for setting the data values and print()
member function to print which object has invoked it using ‘this’
pointer.
CODE
#include<bits/stdc++.h>

using namespace std;

class prn_obj
{
int rno;
string name;
public:
void set_data(string n, int r)
{ name=n;
rno=r;
}
void print() {
cout<<this->name<<" has invoked print() function"<<endl;
cout<<"The roll number is "<<this->rno<<endl;
}
};
int main()
{
prn_obj ob1,ob2,ob3;
ob1.set_data("Saket",1);
ob2.set_data("kuldeep",2);
ob3.set_data("garry",3);

ob1.print();
ob2.print();
ob3.print();
return 0;

}
OUTPUT
EXPERIMENT -12
AIM - Write a C++ program to explain virtual function
(polymorphism) by creating a base class c_polygon which has virtual
function area(). Two classes c_rectangle and c_triangle derived from
c_polygon and they have area() to calculate and return the area of
rectangle and triangle respectively.
CODE
#include<bits/stdc++.h>

using namespace std;

class c_polygon

public :

virtual float area() = 0;

};

class c_triangle : public c_polygon

float a,b,c;

public :

c_triangle(){}

void setSides(float x , float y , float z)

a=x;

b=y;

c=z;

float area()

float s = (a+b+c)/2;
float ans = sqrt(s*(s-a)*(s-b)*(s-c));

return ans;

};

class c_rectangle : public c_polygon

float l,b;

public :

c_rectangle(){}

void setSides(float x , float y )

l=x;

b=y;

float area()

return l*b;

};

int main()

cout<<"Enter the sides of the triangle : ";

c_triangle tri;

float a,b,c;

cin>>a>>b>>c;

tri.setSides(a,b,c);

cout<<"Area of the triangle with sides "<<a<<" , "<<b<<" , "<<c<<" = "<<tri.area()<<endl;


cout<<"Enter the sides of the rectangle : ";

c_rectangle rect;

float l,w;

cin>>l>>w;

rect.setSides(l,w);

cout<<"Area of the rectangle with sides "<<l<<" , "<<w<<" = "<<rect.area()<<endl;

OUTPUT
EXPERIMENT -13
AIM- Write a program to explain class template by creating a
template T for a class named pair having two data members of type T
which are inputted by a constructor and a member function get-max()
return the greatest of two numbers to main. Note: the value of T
depends upon the data type specified during object creation.
CODE
#include <iostream>
using namespace std;
template<class t>
class Pair
{
t a, b;
public:
Pair(t x, t y)
{
a = x;
b = y;
}
t get_max()
{
if(a>b)
return a;
else
return b;
}
};
int main(){ int a,b;
cout<<"Enter the value of two integers : ";
cin>>a>>b;
Pair <int> m(a,b);
cout<<"The max value out of "<<a<<" and "<<b<<" = "<<m.get_max()<<endl;
float c, d;
cout<<"Enter the value of two floats : ";
cin>>c>>d;
Pair <float> n(c ,d);
cout<<"The max value out of "<<c<<" and "<<d<<" = "<<n.get_max()<<endl;
return 0;
}
OUTPUT

EXPERIMENT -14
AIM- Write a C++ program to illustrate
i. Division by zero
ii. Array index out of bounds exception
Also use multiple catch blocks.
1. CODE
Division by zero
i. #include <bits/stdc++.h>
using namespace std;
float CheckDenominator(float den)
{
if (den == 0)
throw "Error";
else
return den;
}
int main()
{
float numerator, denominator, result;
cout<<"Enter the numerator and denominator : ";
cin>>numerator;
cin>>denominator;
try {
if (CheckDenominator(denominator)) {
result = (numerator / denominator);
cout << "The quotient is "
<< result << endl;
}
}
catch (...)
cout << "Exception occurred" << endl;
}
}
Array index out of bounds exception
#include <bits/stdc++.h>
using namespace std;
int main () {
try
{
char * mystring;
mystring = new char [10];
if (mystring == NULL) throw "Allocation failure";
for (int n=0; n<=100; n++)
{
if (n>9) throw n;
mystring[n]='z';
}
}
catch (int i)
{
cout << "Exception: ";
cout << "index " << i << " is out of range" << endl;
}
catch (char * str)
{
cout << "Exception: " << str << endl;
}
return 0;
}

OUTPUT
i. Division by zero

ii. Array index out of bounds exception


JAVA EXPERIMENTS

EXPERIMENT-1
AIM-Write a Java program to print the area and perimeter of a circle
CODE
public class Main

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.print("Input 1st number: ");

int number1 = in.nextInt();

System.out.print("Input 2nd number: ");

int number2 = in.nextInt();

int number3=number1+number2;
System.out.println("Product of two numbers: "+ number1 + " x " + number2 + " = " + number1 *
number2);

System.out.println("addition of two numbers: "+ number1 + " + " + number2 + " = " + number3);

OUTPUT

EXPERIMENT-2
AIM-Write a Java program that takes two numbers as input and
display the addition and product of two numbers.

CODE
import java.util.Scanner;

class Main

static Scanner sc = new Scanner(System.in);

public static void main(String args[])

System.out.print("Enter the radius: ");

double radius = sc.nextDouble();

double area = Math.PI * (radius * radius);


System.out.println("The area of circle is: " + area);

double circumference= Math.PI * 2*radius;

System.out.println( "The circumference of the circle is:"+circumference) ;

OUTPUT

EXPERIMENT – 3
AIM- Create a class with a main( ) that throws an object of class
Exception inside a try block. Give the constructor for Exception a
String argument. Catch the exception inside a catch clause and print
the String argument. Add a finally clause and print a message to prove
you were there.
CODE
package com.company;

import java.io.FileNotFoundException;
public class Main {
Main(String msg) {
msg = "this is bound to execute";
System.out.println(msg);
}
public static void main(String[] args) throws Exception {
try {
throw new FileNotFoundException();
} catch (FileNotFoundException e) {
throw new Exception("File not found");
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
System.out.println("i will get printed");
}
}
}
OUTPUT

EXPERIMENT – 4
AIM- Create your own exception class using the extends keyword.
Write a constructor for this class that takes a String argument and
stores it inside the object with a String reference. Write a method that
prints out the stored String. Create a try-catch clause to exercise your
new exception.
CODE
package com.company;

class MyException extends Exception{


String str1;
MyException(String str2) {
str1=str2;
}
public String toString(){
return ("MyException Occurred: "+str1) ;
}
}
class Main{
public static void main(String args[]){
try{
System.out.println("Starting of try block");
throw new MyException("This is My error Message");
}
catch(MyException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}

OUTPUT

CLASS EXERCISE
EXPERIMENT-1
AIM- WAP showing the use of pointers to the derived class
objects.

CODE
#include<iostream>
using namespace std;
class Base{
int a;
public:
Base()
{
// Default Constructor
a = 0;
}
Base(int r)
{
// Parameterised Constructor
a = r;
}
virtual void show(){
cout << "Value of A is: " << a << endl;
}
};
class Derived1: public Base{
int b;
public:
Derived1()
{
// Default Constructor
b = 0;
}
Derived1(int r)
{
// Parameterised Constructor
b = r;
}
virtual void show(){
cout << "Value of B is: " << b << endl;
}
};
class Derived2 : public Derived1
{
int c;
public:
Derived2(int r)
{
// Parameterised Contructor
c=r;
}
void show(){
cout << "Value of C is: " << c << endl;
}
};
void display()
{
Base *ptr = new Derived2(6);
ptr->show();
ptr = new Derived1(2);
ptr->show();
ptr = new Base(5);
ptr->show();
}
int main()
{
display();
return 0;
}

OUTPUT
EXPERIMENT-2
AIM- WAP that uses classes to allocate object's memory using
dynamic memory allocation.

CODE
#include<iostream>
using namespace std;
class Cuboid
{
int Length, Breadth, Width;
public:
Cuboid(int l,int b,int w){
cout << "The Parameterised contructor is called" << endl;
Length = l;
Breadth = b;
Width = w;
}
void Display(){
cout << "The dimensions of the object pointed to by the pointer are "
<<
endl;
cout << "Len is: " << Length << endl;
cout << "Brdth is: " << Breadth << endl;
cout << "Wid is: " << Width << endl;
}
};
void display(){
Cuboid *ptr2 = new Cuboid(5 , 6, 7);
ptr2->Display();
}
int main()
{
display();
return 0;
}

OUTPUT

EXPERIMENT-3
Aim-A) Print Hello world
B) Addition of 2 numbers
C) Input 5 subject marks of a student and calculate their average
D) Find area of a circle
E) Input a number from a user and check whether it is positive, negative or zero
Input code:

#include<iostream>

using namespace std;


void hello(){

cout<<"hello world";

void add(){

int a=2,b=3;

cout<<"sum:"<<a+b;

void input(){

int a,b;

cout<<"input two no."<<endl;

cin>>a>>b;

cout<<"ans:"<<a+b;

void avg(){

int a,b,c;

float avg;

cout<<"input 3 no.s of whose avg is required"<<endl;

cin>>a>>b>>c;

avg=(a+b+c)/3.0;

cout<<"average of the 3 no.s is:"<<avg;

void area(){
int r;

cout<<"enter the radius of circle"<<endl;

cin>>r;

float area=3.14*r*r;

cout<<"area:"<<area;

void positivenegativenos(){

cout<<"enter a no."<<endl;

int x;

cin>>x;

if(x<0)

cout<<"no. entered is negative";

else if(x>0)

cout<<"no. entered is positive";

else

cout<<"no. entered is zero";

int main(){

cout<<"enter the value corresponding the function"<<endl;

cout<<"1.add two no.s"<<endl<<"2.input no.s"<<endl<<"3.average of 3


no.s"<<endl<<"4.area of circle"<<endl<<"5.hello world"<<endl<<"6.+ve&-ve no.s"<<endl;

int x;

cin>>x;

if(x==1){
add();

else if(x==2){

input();

else if(x==3){

avg();

else if(x==4){

area();

else if(x==5){

hello();

else if(x==6)

positivenegativenos();

return 0;

}
Output:
EXPERIMENT-4
Aim-Write a Program showing the use of pointers to the derived class objects.
Code-
#include <iostream>
using namespace std;

class overload{
private:
int x,y,z;
public:
overload(){
x=5;
y=10;
z=1;
};
void operator++();
void operator--();
void operator-();
void operator+();
void display();
};
overload o;
void overload::operator++() {
x++;
y++;
z++;
}
void overload::operator--() {
x--;
y--;
z--;
}
void overload::operator+() {
++x;
++y;
++z;
}
void overload::operator-() {
--x;
--y;
--z;
}
void overload::display() {
cout<<x<<endl;
cout<<y<<endl;
cout<<z<<endl;
}
int main()
{
cout << "Post Inc:" << endl;
++o;
o.display();
cout << "Post Dec :" << endl;
--o;
o.display();

cout << "Pre Inc" << endl;


+o;
o.display();
cout << "Pre Dec" << endl;
-o;
o.display();

return 0;
}

OUTPUT:

You might also like