CSC213 Object Oriented Programming-Lab Manual-Sol

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 83

Lab Manual

OBJECT ORIENTED
PROGRAMMING

CSC-213

SPRING 2020
OOPs Lab Manual

Lab Manual

OBJECT ORIENTED PROGRAMMING

Semester : Spring 2020


Program : BSCS
Course Title and Name : CSC 213
Credits : 0+1
Faculty : Mrs. Saadia Karim
Student Name :
Student ID :
Total Marks :
Obtained Marks :
Submitted Date :

2
OOPs Lab Manual

Table of Contents

Experiment
Experiment Title Date Signature
No.
The objective of this lab is to practice with input, 20/01/2021
1. output and variables and to familiarize students with
IDE interface.
The objective of this lab is to practice with variables
2. 27/01/2021
declaration, class components and compiling code.
To create a program with conditional IF-Statement
3. and IF-ELSE-IF Ladder and compare variables to
display the result.
To create a program with FOR loop for repeated
4.
processing of s statement.
To create a two dimensional array, insert values in
5.
the array and display the result.
To implement Switch statement and develop an
6.
arithmetic calculator.
To demonstrate the concept of class and declaration
7.
of objects with a class and display the output.
To develop a constructor, to initialize object and
8.
display output.
To implement inheritance concept using class and
9.
subclass and display the output.
To implement the concept of polymorphism
10. (dynamic Binding or Late Binding) and display the
output.
To implement exception handling using TRY-
11
CATCH statement and display the result.
To implement the concept of collection in java and
12.
run the program

13. To develop applet in java using HTML.

3
OOPs Lab Manual

LAB EXPERIMENT # 1

Objective: The objective of this lab is to practice with input, output and variables
and to familiarize students with IDE interface.

Example 1:
#include <iostream>  
using namespace std;  
int main( ) {  
   cout << " Welcome to C++ tutorial " << endl;  
}  
Output:

Example 2:
#include <iostream>  
using namespace std;  
int main( ) {  
  int age;  
   cout << "Enter your age: ";  
   cin >> age;  
   cout << "Your age is: " << age << endl;  
}  

Output:

4
OOPs Lab Manual

Task 1:
(Print a table) Write a program that displays the following table:

Source code:

#include<iostream>
using namespace std;
main()
{
int i;
cout << "a\ta^2\ta^3" <<endl;
for(i=1;i<=4;i++)
{
cout <<i <<"\t" <<i*i <<"\t" <<i*i*i <<endl;
}
}
Execution:

5
OOPs Lab Manual

Task 2:
(Average speed in miles) Assume a runner runs 14 kilometers in 45 minutes
and 30 seconds. Write a program that displays the average speed in miles per
hour. (Note that 1 mile is 1.6 kilometers.)

Source code:

#include <iostream>
using namespace std;
main()
{
float miles;
float milperhour;
float mins=45;
float totalsec;
float givensec=30;
int kilometer=14;
float hours;
mins=45;
totalsec=(mins*60)+givensec;
hours=totalsec/3600;
miles=kilometer/1.6;
milperhour=(miles/hours);

6
OOPs Lab Manual

cout << "The sprinter has covered 14 kilometers in 45 minutes and 30 seconds" <<endl
<<endl;
cout << "Converting given time into hours " <<endl <<endl;
cout << "After converting time and kilometers into miles the duration is: " <<endl
<<endl;
cout << "Miles per hour: " << milperhour;
}

Execution:

7
OOPs Lab Manual

Student Registration No: ______20201-27628_______

Teacher Signature: ________________________

LAB EXPERIMENT # 2

Objective: The objective of this lab is to practice with variables declaration, class
components and compiling code.

Example 1:
#include <iostream>  
using namespace std;  
int main( ) {  
   char ary[] = "Welcome to C++ tutorial";  
   cout << "Value of ary is: " << ary << endl;  
}  
Output:

8
OOPs Lab Manual

Example 2:
#include <iostream>  
using namespace std;  
int main( ) {  
int x=5,b=10;  //declaring 2 variable of integer type    
float f=30.8;    
char c='A';
   cout << "Sum = " << x+b << endl;  
   cout << "Float = " << f << endl;  
cout << "Character = " << c << endl;  
}  
Output:

9
OOPs Lab Manual

Task 1:
Write a program that displays the following equation:  
-7 – 4a = -a + 8

Source code:

#include<iostream> // header file declaration


// This program is an illustration of a left hand side equation which is equal to
the right hand side equation
// it uses only one variable which is "a"
main() // main function starts here
{
using namespace std; // It is used to combine similar classes under a single
standard
cout << "-7 - 4a = -a + 8";
} // main function ends here

10
OOPs Lab Manual

Execution:

Task 2:
Write a program that displays the following equation:
4c = 8 - 4c

Source code:

#include<iostream> // header file declaration


// This program is an illustration of a left hand side equation which is
equal to the right hand side equation
// it uses only one variable which is "a"
main() // main function starts here
{
using namespace std; // It is used to combine similar classes under a
single standard
cout << "4c = 8 - 4c";
} // main function ends here

11
OOPs Lab Manual

Execution:

Student Registration No: ________________________

Teacher Signature: ________________________

LAB EXPERIMENT # 3

Objective: To create a program with conditional IF-Statement and IF-ELSE-IF


Ladder and compare variables to display the result.

Example 1: If Statement
// Program to print positive number entered by the user
// If user enters negative number, it is skipped

#include <iostream>
using namespace std;
int main()
{

12
OOPs Lab Manual

int number;
cout << "Enter an integer: ";
cin >> number;
// checks if the number is positive
if ( number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0;
}

Output:

Example 2: If-Else Statement


// Program to check whether an integer is positive or negative
// This program considers 0 as positive number
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter an integer: ";

13
OOPs Lab Manual

cin >> number;


if ( number >= 0)
{
cout << "You entered a positive integer: " << number << endl;
}

else
{
cout << "You entered a negative integer: " << number << endl;
}
cout << "This line is always printed.";
return 0;
}

Output:

Example 3: Nested if...else


// Program to check whether an integer is positive, negative or zero
#include <iostream>

14
OOPs Lab Manual

using namespace std;


int main()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if ( number > 0)
{
cout << "You entered a positive integer: " << number << endl;
}
else if (number < 0)
{
cout<<"You entered a negative integer: " << number << endl;
}
else
{
cout << "You entered 0." << endl;
}
cout << "This line is always printed.";
return 0;
}
Output:

15
OOPs Lab Manual

Task 1:
Write a program that a student will not be allowed to sit in exam if his/her
attendance is less than 75%.
 Take following input from user
o Number of classes held
o Number of classes attended.
 And print percentage of class attended
 In addition, print student is allowed to sit in exam or not.

Source code:

#include<iostream> // header file declaration


main() // main function starts here
{
using namespace std;
int hldcls; //integer declaration
int attcls; //integer declaration
float perattcls; //integer declaration
cout << "enter the number of classes you attended : " << endl;
cin >> attcls; //integer defination
cout << "enter the number of classes you held : " << endl;
cin >> hldcls; //integer defination
perattcls=(attcls*100)/hldcls;
cout << perattcls <<" % is your total class attandance percentage" << endl;
if(perattcls>75) // this block is executed if your attandance is greater than 75
{
cout << "you are eligible to appear in this exam !!";
}
else // this block executes if your attandance is less than 75
{
cout << "Sorry you are not eligible to appear in this exam !!!!!";
}
} // main function ends here

16
OOPs Lab Manual

Execution:

Task 2:
Write a program and display the answer of the expressions:
If
x=2
y=5
z=0
Then find values of the following expressions:
 x == 2
 x != 5
 x != 5 && y >= 5
 z != 0 || x == 2
 !(y < 10)

Source code:

#include<iostream> // header files


main() // main function starts here
{
using namespace std; // using namespace to create similar classes under a single
standard
int x=2; // declaring and defining (x)variable
int y=5; // declaring and defining (y)variable
int z=0; // declaring and defining (z)variable

17
OOPs Lab Manual

bool outcome; // declaring bool variable

// statement 1 : (x==2) will give 1 if x==2 else it will give 0 on console screen
outcome = (x==2) ? true:false;
cout << "The outcome of the statement (x==2) is : " << outcome <<endl
<<endl;

// statement 2 : (x!=5) will give 1 if x is not equal to 5 else it will give 0 on


console screen
outcome = (x!=5) ? true:false;
cout << "The outcome of the statement (x!=5) is : " << outcome <<endl
<<endl;

// statement 3 : (x==2) && (y>=5) will give 1 if x is equal to 2 and y is greater


than or equal to 5 else it will give 0 on console screen
outcome = (x!=5) && (y>=5) ? true:false;
cout << "The outcome of the statement (x!=5) || (y>=5) is : " << outcome
<<endl <<endl;

// statement 4 : (z!=0) || (x==2) will give 1 if z is not equal to 0 and x is equal to 2


else it will give 0 on console screen
outcome = (z!=0) || (x==2) ? true:false;
cout << "The outcome of the statement (z!=0) || (x==2) is : " << outcome
<<endl <<endl;

// statement 5 : !(y<10) will give 1 if y is not less than 10 else it will give 0 on
console screen
outcome = !(y<10) ? true:false;
cout << "The outcome of the statement !(y<10) is : " << outcome <<endl
<<endl;

} // main function ends here

18
OOPs Lab Manual

Execution:

Task 3:
Write a program to check whether a entered character is lowercase (a to z ) or
uppercase ( A to Z ).

Source code:

#include<iostream> // header file declaration


main() // main function starts here
{
using namespace std;
char c; // variable declaration
cout << " Enter a character to be distinguished as a lower case letter or a upper case
letter = ";
cin >> c; // variable defination
if(c>=65 && c<=90) // this block is executed if given character is uppercase
{
cout << "you have entered a uppercase letter !!";
}
else if(c>=97 && c<=122) // this block is executed if given character is lowercase
{
cout << "you have entered a lowercase letter !!";
}

19
OOPs Lab Manual

else if(c>=48 && c<=57) // this block is executed if given character is a number
{
cout << "you have entered a numerical digit !!";
}
else // this block is executed checks if given character is a special character
{
cout << "you have not entered a letter or a digit !!!!!!!!";
}
} // main function ends here

Execution:

Task 4:
Write a program to create grade book using IF Statement.

Source code:

#include<iostream> // Header file


main() // main function starts here
{
using namespace std; // using namespace to create similar classes under a single
standard

// declaring integer variables


//**********

20
OOPs Lab Manual

int sci;
int eng;
int math;
int avg;
int obtained;
//**********
cout << "***** Grade sheet *****" << endl << endl ;
cout << "Enter your science marks : " ;
cin >> sci ;
cout << endl << "Enter your english marks : " ;
cin >> eng ;
cout << endl << "Enter your maths marks : " ;
cin >> math ;
obtained=sci+eng+math; // This line is calculating total obtained marks of all subjects
combined
avg=(obtained*100)/300; // This line is calculating average % of your session
cout << endl << "your obtained average percenatage is : " << avg << "%" ;
if(avg>=90) // This block will be executed if a student has secured 90% and above
{
cout <<endl << "You secured 'A+' grade sucessfully " ;
cout << endl << endl << "***Excellent***" ;
}
else if(avg>=80) // This block will be executed if a student has secured 80% and above
{
cout <<endl << "You secured 'A' grade sucessfully " ;
cout << endl << endl << "***Very Good***" ;
}
else if(avg>=70) // This block will be executed if a student has secured 70% and above
{
cout <<endl << "You secured 'B' grade sucessfully " ;
cout << endl << endl << "***Good job***" ;
}
else if(avg>=60) // This block will be executed if a student has secured 60% and above
{
cout <<endl << "You secured 'C' grade sucessfully " ;
cout << endl << endl << "***Need some improvement***" ;
}
else if(avg>=50) // This block will be executed if a student has secured 50% and above
{
cout <<endl << "You secured 'D' grade sucessfully " ;
cout << endl << endl << "***Work Hard next time***" ;
}

21
OOPs Lab Manual

else // This block will be executed if a student has failed session obtaining less than
50%
{
cout << endl << "You have failed this examination with an 'F' grade ";
cout << endl << endl << "***Repeat this exam with great enthusiasm and progressive
approach***" ;
}
} // main function ends here

Execution phase 1:

Execution phase 2:

22
OOPs Lab Manual

Student Registration No: ________________________

Teacher Signature: ________________________

LAB EXPERIMENT # 4

Objective: To create a program with FOR loop for repeated processing of s


statement.

Example: For Loop


// C++ Program to find factorial of a number
// Factorial on n = 1*2*3*...*n

#include <iostream>
using namespace std;

int main()
{
int i, n, factorial = 1;

cout << "Enter a positive integer: ";

23
OOPs Lab Manual

cin >> n;

for (i = 1; i <= n; ++i) {


factorial *= i; // factorial = factorial * i;
}

cout<< "Factorial of "<<n<<" = "<<factorial;


return 0;
}

Output:

Task 1:
Write a C++ program to print all odd number between 1 to 100.

Source code:

#include<iostream> // header file


main() // main function starts here
{

24
OOPs Lab Manual

using namespace std; // creates similar classes under a single standard


int i; // ineteger declaration

for(i=1;i<=100;i=i+2) // This loop displays odd numbers from 1 to 100


{
cout << i ;
cout << "\t" ;
}

} // main function ends here

Execution:

Task 2:
Write a C++ program to enter any number and check whether it is Prime
number or not.

Source code:

#include<iostream> // header file


main() // main function starts here

25
OOPs Lab Manual

using namespace std; // creates similar classes under a single


standard

// integer declarations
//*****
int no,i;
int c=0;
//*****

cout << "Enter any positive integer : " ;


cin >> no;

if(no>0) // this block is executed when number entered is 1 or


greater
{

for(i=1;i<=no;i++) // This loop checks whether a number is prime


or not
{
if(no%i==0)
{
c=c+1;
}
}

if(c==2) // This block is executed for a prime number


{
cout << endl << "The number " << no << " is a prime number " ;
}
else // This block is executed for a non prime number
{
cout << "The number you entered " << no << " is not a prime
number !!!!" ;
}

26
OOPs Lab Manual

else if(no==0) // this block is executed when entered number is (0)


{
cout << "0 is not a prime number ";
}

else if(no==1) // this block is executed when entered number is (1)


{
cout << "1 is neither a prime nor a composite number !!";
}

else // this block is executed when all above conditions are not met
{
cout << endl << "Negative numbers are non-prime
numbers !!!!";
}

} // main function ends here

Execution phase 1:

27
OOPs Lab Manual

Execution phase 2:

Task 3:
Write a C++ program to enter any number and calculate sum of all natural
numbers between 1 to n.

28
OOPs Lab Manual

Source code:

#include<iostream> // header file


main() // main function starts here
{

using namespace std; // creates similar classes under a single standard

// integer declarations
// ******
int no,i;
int sum=0;
// ******

cout << "Enter any positive integer : " ;


cin >> no;

for(i=1;i<=no;i++) // This loop sums up number from 1 to the provided


number
{
sum=sum+i;
}

cout << endl << "The sum calculated uptil the no " << no << " is : " << sum;

} // main function ends here

29
OOPs Lab Manual

Execution:

Student Registration No: ________________________

Teacher Signature: ________________________

30
OOPs Lab Manual

LAB EXPERIMENT # 5

Objective: To create a two dimensional array, insert values in the array and
display the result.

Example: two-dimensional array


#include <iostream>
using namespace std;

int main()
{
int test[3][2] =
{
{2, -5},
{4, 0},
{9, 1}
};

// Accessing two dimensional array using


// nested for loops
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 2; ++j)
{
cout<< "test[" << i << "][" << j << "] = " << test[i][j] << endl;
}
}

return 0;
}
Output:

31
OOPs Lab Manual

Task 1:
Write a C++ Program to Store value entered by user in three-dimensional
array and display it

Source code:

#include<iostream> // header file


using namespace std; // creates similar classes under a single standard
main() // main function starts here
{

int i,j,k; // variable declarations


int darray[2][2][2]; // array declaration

for(i=0;i<2;i++) // nested loop for getting all elements of array


{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
cout << endl << "Enter element [" << i << "][" << j << "][" << k << "]" << "=
";

32
OOPs Lab Manual

cin >> darray[i][j][k];


}
}
}
for(i=0;i<2;i++) // nested loop for displaying all elements of array
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
cout << endl << "Element[" << i << "][" << j << "][" << k << "]" <<
darray[i][j][k];
}
}
}
} // main functions ends here

Execution:

Task 2:
Write a C++ Program to store temperature of two different cities for a week
and display it.

Source code:

33
OOPs Lab Manual

#include<iostream> // header file


using namespace std; // creates similar classes under a single
standard
main()
{ // main function starts here
int i,j; // variable declarations

/**********/ // 2 dimensional array constants


int week=7;
int city=2;
/**********/

float temp[city][week]; // 2d array declaration

/************/ // string variables declaration for two cities


string city1;
string city2;
/************/

cout << "enter your first city name : ";


cin >> city1 ;

cout << "enter your second city name : ";


cin >> city2;

for(i=0;i<city;i++) // This nested loop block is used to input all


temperature elements of city 1 and city 2
{
for(j=0;j<week;j++)
{
cout << "city: " << i+1 << " day: " << j+1 << " = ";
cin >> temp[i][j];
}
}

34
OOPs Lab Manual

for(i=0;i<city;i++) // This block displays result containing record


of city's 1 temperatue and city's 2 temperature
{
for(j=0;j<week;j++)
{
if(i==0) // this block is executed for user's first city
temperature record of a week
{
cout <<endl << "city: " << city1 << " day: " << j+1 << " = ";
cout << temp[i][j];
}

else // this block is executed for user's second city


temperature record of a week
{
cout <<endl << "city: " << city2 << " day: " << j+1 << " = ";
cout << temp[i][j];
}
}
}

} // main function ends here

Execution phase 1:

35
OOPs Lab Manual

Execution phase 2:

Execution phase 3:

36
OOPs Lab Manual

Task 3:
Write a C++ program to find the largest element of a given array of integers.

Source code:

#include<iostream> // header file


using namespace std; // creates similar classes under a single standard
main() // main function starts here
{
/**************/ // variables declarations and definations
int i;

37
OOPs Lab Manual

int highest=0;
int size;
/**************/

cout << "Enter the quantity of numbers in your array : ";


cin >> size;

int numcollection[size]; // daclaration of integer type array

for(i=0;i<size;i++) // loop for getting all elements of array


{
cout << "Element [" << i+1 << "]" << " = ";
cin >> numcollection[i];
}

for(i=0;i<size;i++) // this loop checks highest element in this array


{
if(numcollection[i]>highest)
{
highest=numcollection[i];
}
}
cout <<endl << "Higest number in this array is : " << highest; // displaying
highest element of the array
} // main function ends here

Execution:

38
OOPs Lab Manual

Student Registration No: ________________________

Teacher Signature: ________________________

39
OOPs Lab Manual

LAB EXPERIMENT # 6

Objective: To implement Switch statement and develop an arithmetic calculator.

Example : Switch Statement


// Program to built a simple calculator using switch Statement

#include <iostream>
using namespace std;

int main()
{
char o;
float num1, num2;

cout << "Enter an operator (+, -, *, /): ";


cin >> o;

cout << "Enter two operands: ";


cin >> num1 >> num2;

switch (o)
{
case '+':
cout << num1 << " + " << num2 << " = " << num1+num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1-num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1*num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1/num2;
break;

40
OOPs Lab Manual

default:
// operator is doesn't match any case constant (+, -, *, /)
cout << "Error! operator is not correct";
break;
}

return 0;
}

Output:

Task 1:
Write a C++ program that have some grades of students and you need to
display, like following,
Grade A = YOU VERY GOOD
Grade B = EXCELLENT
Grade C = EXCELLENT

41
OOPs Lab Manual

Grade F = WORST
(**if user enter any other letter programme should display “ERROR” message!**)

Source code:

#include<iostream> //header file declaration


using namespace std; // used to create similar classes under a single standard
class grade // defination of class
{

public: // it can be
acessed from main function
char a; // switch
variable
string name;

/***********************************************/
// methods for grades according to equivalent letters
Agrade()
{
cout<< endl <<"Excedding Expection";
}
Bgrade(){
cout << endl <<"Good performance";
}
Cgrade(){
cout<< endl <<"Not bad";
}
Fgrade(){
cout<< endl <<"Try your max potential next time";
}
/*************************************************/
};
main()
{ // main function starts here
grade g1;

cout << "------------------------------------------------";


cout << endl << "Enter your name : ";

42
OOPs Lab Manual

cin >> g1.name;

cout << endl << "------------------------------------------------";


cout <<endl << "------------------------------------------------";
cout <<endl << "Enter a grade: "; // entering grade

cin >> g1.a;

switch(g1.a){ // switch case


starts
case 'A':
case'a': // this block executes if (a) grade is
obtained

{
cout << endl << "------------------------------------------------";
cout <<endl << "------------------------------------------------";
cout <<endl << g1.name << " have met " ;
g1.Agrade();

break;
}
case 'B':
case'b': // this block executes if (b) grade is
obtained
{
cout << endl << "------------------------------------------------";
cout <<endl << "------------------------------------------------";
cout <<endl << g1.name << " have shown" ;
g1.Bgrade();
break;
}
case 'C': // this block executes if (c) grade is
obtained
case'c':
{
cout << endl << "------------------------------------------------";
cout <<endl << "------------------------------------------------";
cout <<endl << g1.name << " performance is " ;
g1.Cgrade();

43
OOPs Lab Manual

break;
}
case 'F': // this block executes if (f) grade is
obtained
case'f':
{
cout << endl << "------------------------------------------------";
cout <<endl << "------------------------------------------------";
cout << endl << g1.name << " you should " ;
g1.Fgrade();
break;
}
default: // this block executes if none of
above grades are obtained
{

cout << endl <<"--------------ERROR-----------------";


break;
}
} // swicth case ends

} // main function ends here

Execution:

44
OOPs Lab Manual

Task 2:
Write a C++ program to develop an arithmetic calculator.

Source code:

/*************************/ // header files declaration


#include<iostream>
#include<cmath>
#include<stdlib.h>
#include<time.h>
/*************************/
using namespace std; // used to create similar classes
under a single standard
class calculator // defining class
{
private: // these variables can only be acessed in
this class
int i,k,res,diff;
float sinres,cosres,tanres;
public: // these methods can be acessed
anywhere inside this program
int add (int no1,int no2) // method for addition operation
{
return no1+no2;
}
int sub (int no1,int no2) // method for subtraction operation
{
return no1-no2;
}
int mult (int no1,int no2) // method for multiplication
operation
{
return no1*no2;
}

45
OOPs Lab Manual

float div (int no1,int no2) // method for division operation


{
return no1/no2;
}
int fact (int no) // method for factorial operation
{
int fact=1;
for(i=1;i<=no;i++)
{
fact = fact *i;
}
return fact;
}

int result(int no1,int no2) // method for addition operation


{
res=pow(no1,no2);
return res;
}

float sine(int no) // method for sin operation


{
sinres=sin(no);
return sinres;
}

float cosine(int no) // method for cos operation


{
cosres=cos(no);
return cosres;
}

float tangent(int no) // method for tan operation


{
tanres=tan(no);
return tanres;

46
OOPs Lab Manual

int random(int no1,int no2) // method for generating a random


number between two given numbers
{
if(no1>no2)
{
diff=no1-no2;
return rand()%diff+no2;
}
else
{
diff=no2-no1;
return rand()%diff+no1;
}

}
};

main() // main function starts here


{
srand(time(0)); // inputs current time of system in seconds to
generate a unique number every time
calculator c1; // instance of class (calculator)
int n1,n2;
int sel;
cout <<endl << "Enter first number :" ;
cin >> n1; // getting first number from user
cout <<endl << "Enter second number :" ;
cin >> n2; // getting second number from user

// options provided to user for switch statement selection


/
**********************************************************

47
OOPs Lab Manual

**********************************************************
***************************************/
cout << endl << endl << "1. add" << endl << "2. multiply" << endl
<< "3. divide" << endl << "4. subtract" << endl << "5. factorial" <<
endl << "6. x^y" ;
cout << endl <<"7. sin,cos,tan " << endl << "8. random numbers
between no " << n1 << " and " << n2 ;
cout << endl << endl;
/
**********************************************************
**********************************************************
***************************************/
cin >> sel; // getting switch case selection variable from the user to
perform the equivalent airthmetic operation
switch(sel)
{ // switch case starts
case 1: // this block executes when user provides 1 as input
cout <<endl << "The result of addition between these two
numbers is : " << c1.add(n1,n2) ;
break;
case 2: // this block executes when user provides 2 as input
cout <<endl << "The result of mutiplication between these two
numbers is : " << c1.mult(n1,n2) ;
break;
case 3: // this block executes when user provides 3 as input
cout <<endl << "The result of division between these two
numbers is : " << c1.div(n1,n2) ;
break;
case 4: // this block executes when user provides 4 as input
cout <<endl << "The result of subtraction between these two
numbers is : " << c1.sub(n1,n2) ;
break;
case 5: // this block executes when user provides 5 as input

48
OOPs Lab Manual

cout <<endl << "The factorial of first number : " << n1 << "
is : " << c1.fact(n1) << " and second number : " << n2 << " is : "
<<c1.fact(n2) ;
break;
case 6: // this block executes when user provides 6 as input
cout <<endl << "The result of no2 : " << n2 << " as a power of
no1 " << n1 << " is : " << c1.result(n1,n2) ;
break;
case 7: // this block executes when user provides 7 as input
cout <<endl << "The sin,cos,tan of no1: " << n1 << " is : " <<
c1.sine(n1) << "\t";
cout << c1.cosine(n1) << "\t";
cout << c1.tangent(n1);
cout <<endl << "The sin,cos,tan of no2: " << n2 << " is : " <<
c1.sine(n2) << "\t";
cout << c1.cosine(n2) << "\t";
cout << c1.tangent(n2);
break;
case 8: // this block executes when user provides 8 as input
cout <<endl << "A random number between no " << n1 << "
and no " << n2 << " is : " << c1.random(n1,n2);
break;
default: // this block executes when user provides any other
input other than (1-8)
cout <<"invalid choice !!!!";
} // switch case ends
} // main functions ends here

Execution:

49
OOPs Lab Manual

Student Registration No: ________________________

Teacher Signature: ________________________

50
OOPs Lab Manual

LAB EXPERIMENT # 7

Objective: To demonstrate the concept of class and declaration of objects with a


class and display the output.

Example:
#include <iostream>
using namespace std;
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

Output:

51
OOPs Lab Manual

First part

Second part

52
OOPs Lab Manual

Task 1:
Write a C++ program to print the area and perimeter of a triangle having
sides of 3, 4 and 5 units by creating a class named 'Triangle' with a function to
print the area and perimeter.

Source code:

#include <iostream> // header file declaration


using namespace std; // used to create similar classes under a single standard
class Box { // defining class (box)
public: // these variables can be acessed anuwhere inside the program

/***************************************/
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
/***************************************/
};
int main() // main functions starts here
{
Box Box1; // first object of class(Box)
Box Box2; // second object of class(Box)
double volume = 0.0; // initializing volume with zero to filter out any
garbage value
// box 1 specification inside class(Box)
///-----------------///
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
///----------------///
///----------------///
// box 2 specification inside class(Box)
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
///----------------///
// calculation for volume of box 1
///------------------------------------------------///
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

53
OOPs Lab Manual

///------------------------------------------------///
///------------------------------------------------///
// calculation for volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
///------------------------------------------------///
return 0;
} // main function ends here

Execution phase:

Task 2:
Create a class named 'Student' with a string variable 'name' and an integer
variable 'roll_no'. Assign the value of roll_no as '2' and that of name as
"John" by creating an object of the class Student.

Source code:

#include<iostream> // header file


using namespace std; // used to create similar classes under a single standard
class student{ // class (student) is created

54
OOPs Lab Manual

public: // acess specifier is (Public) (it can be acesses anywhere inside the
program)

/***********/
string name;
int roll_no;
/***********/ // variable declaration

};
main()
{ // main function starts
student s1; // object is created with instance (s1)
s1.roll_no=2; // roll_no variable is assigned with (2)
s1.name="John"; // name variable is assigned with ("john")
cout << "Name of the student is : " << s1.name; // name variable is displayed
on console screen
cout <<endl << "Roll number assigned to the student is : " << s1.roll_no; //
roll_no is displayed on the screen
} // main function ends

55
OOPs Lab Manual

Execution phase:

Task 3:
Write a C++ program to print the average of three numbers entered by the
user by creating a class named 'Average' having a function to calculate and
print the average without creating any object of the Average class.

Source code:

#include<iostream> // header file


using namespace std; // used to create similar classes under a single
standard
class Average{ // class (average) is created

56
OOPs Lab Manual

private: // acess specifier is (private) (it can only be acessed


inside the class)

/*****************/
int a;
int b;
int c;
int sum;
/****************/ // variable declaration

public: // acess specifier is (public) (it can only be acessed


anywhere inside the program)

void avg() // method for average calculation


{
cout << "Enter three positive integers seperated by space : ";
cin >> a >> b >> c;
sum=a+b+c;
cout << "The average calculated for these three integers is : " <<
sum/3;
}
};

main()
{ // main function starts
Average a1; // object created with instance (a1)
a1.avg(); // average method called
} // main function ends

Execution phase:

57
OOPs Lab Manual

Student Registration No: ________________________

Teacher Signature: ________________________

LAB EXPERIMENT # 8

Objective: To develop a constructor, to initialize object and display output.

Example:

58
OOPs Lab Manual

#include <iostream>
using namespace std;

class Line {
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
private:
double length;
};

// Member functions definitions including constructor


Line::Line(void) {
cout << "Object is being created" << endl;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}

// Main function for the program


int main() {
Line line;

// set line length


line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;

return 0;
}
Output:

Phase 1:

59
OOPs Lab Manual

Phase 2:

To develop a constructor, to initialize the object and display output.


Watch this video: https://www.coursera.org/lecture/cs-fundamentals-1/3-1-class-constructors-
lYErY

60
OOPs Lab Manual

Book link for Task 2 & 3, read and solve them.


Solution: https://github.com/djkovrik/EckelCpp/tree/master/Volume%202
Constructors in C++
Constructor is a special member function of a class that initializes the object of the class. Constructor
name is same as class name and it doesn’t have a return type. Lets take a simple example to understand
the working of constructor.

Simple Example: How to use constructor in C++


Read the comments in the following program to understand each part of the program.

#include <iostream>

using namespace std;

class constructorDemo{

public:

int num;

char ch;

/* This is a default constructor of the

* class, do note that it's name is same as

* class name and it doesn't have return type.

*/

constructorDemo() {

num = 100; ch = 'A';

};

int main(){

/* This is how we create the object of class,

* I have given the object name as obj, you can

* give any name, just remember the syntax:

* class_name object_name;

*/

constructorDemo obj;

61
OOPs Lab Manual

/* This is how we access data members using object

* we are just checking that the value we have

* initialized in constructor are reflecting or not.

*/

cout<<"num: "<<obj.num<<endl;

cout<<"ch: "<<obj.ch;

return 0;

}
Output:

num: 100

ch: A
Program TASK 1: Solution - You have to do up to n = 15
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    for(int i = 1; i<10; i++)
  {
        int N, zeroth=3, first=2, second;
        cout << "Enter in an integer N: " << flush;
        cin >> N;
        if(N==0)
            cout << "u(" << N << ") = " << zeroth << endl << endl;
        else if (N==1)
            cout << "u(" << N << ") = " << first << endl << endl;
        else if (N>1)
    {
            for(int x = 2; x<=N; x++)
      {
                second = x*first + (x+1)*zeroth + x;
                zeroth = first;

62
OOPs Lab Manual

                first = second;
      }
            cout << "u(" << N << ") = " << second <<  endl << endl;
    }
  }
  cin.get();
}
    Output:
 Enter in an integer N: 1 
 u(1) = 2 
 Enter in an integer N: 2
 u(2) = 15
 Enter in an integer N: 3
 u(3) = 56
 Enter in an integer N: 4
 u(4) = 303

For n=15

63
OOPs Lab Manual

Output part1:

64
OOPs Lab Manual

Output part 2:

65
OOPs Lab Manual

Task 2: 

Source code:

#include<iostream>

using namespace std;

class Car{

66
OOPs Lab Manual

public:

string brand;

string model;

int year;

Car(string x,string y,int z)

brand=x;

model=y;

year=z;

cout <<endl << x << "\t" << y << "\t "<< z <<"\t";

};

main()

Car("BMW","X5",1999);

Car("FORD","Mustang",1969);
}

67
OOPs Lab Manual

Execution:

 Task 3: 

Source code:

#include<iostream>

using namespace std;

class Car {

public:

string brand;

string model;

68
OOPs Lab Manual

int year;

Car(string x,string y,int z);

};

Car::Car(string x,string y,int z)

brand=x;

model=y;

year=z;

main()

Car carObj1("BMW","X5",1999);

Car carObj2("FORD","Mustang",1969);

cout << carObj1.brand << " " << carObj1.model << carObj1.year <<"\n" ;

cout << carObj2.brand << " " << carObj2.model << carObj2.year <<"\n" ;

69
OOPs Lab Manual

Execution:

Student Registration No: ________________________

Teacher Signature: ________________________

70
OOPs Lab Manual

LAB EXPERIMENT # 9

Objective: To implement inheritance concept using class and subclass and display
the output.

Example 1:
#include <iostream>
using namespace std;

class stud {
protected:
int roll, m1, m2;

public:
void get()
{
cout << "Enter the Roll No.: "; cin >> roll;
cout << "Enter the two highest marks: "; cin >> m1 >> m2;
}
};
class extracurriculam {
protected:
int xm;

public:
void getsm()
{
cout << "\nEnter the mark for Extra Curriculam Activities: "; cin >> xm;
}
};
class output : public stud, public extracurriculam {
int tot, avg;

public:
void display()
{
tot = (m1 + m2 + xm);
avg = tot / 3;
cout << "\n\n\tRoll No : " << roll << "\n\tTotal : " << tot;
cout << "\n\tAverage : " << avg;
}
};
int main()
{

71
OOPs Lab Manual

output O;
O.get();
O.getsm();
O.display();
}
Output:
First part:

Second part:

72
OOPs Lab Manual

Example 2:
#include <iostream>
using namespace std;

class Person
{
public:
string profession;
int age;

Person(): profession("unemployed"), age(16) { }


void display()
{
cout << "My profession is: " << profession << endl;
cout << "My age is: " << age << endl;
walk();
talk();
}
void walk() { cout << "I can walk." << endl; }
void talk() { cout << "I can talk." << endl; }
};

// MathsTeacher class is derived from base class Person.


class MathsTeacher : public Person
{
public:
void teachMaths() { cout << "I can teach Maths." << endl; }
};

// Footballer class is derived from base class Person.


class Footballer : public Person
{
public:
void playFootball() { cout << "I can play Football." << endl; }
};

int main()
{
MathsTeacher teacher;

73
OOPs Lab Manual

teacher.profession = "Teacher";
teacher.age = 23;
teacher.display();
teacher.teachMaths();

Footballer footballer;
footballer.profession = "Footballer";
footballer.age = 19;
footballer.display();
footballer.playFootball();

return 0;
}
Output:
First part:

Second part:

74
OOPs Lab Manual

Task 1:
Write a C++ program to make a class named Fruit with a data member to calculate
the number of fruits in a basket. Create two other class named Apples and Mangoes
to calculate the number of apples and mangoes in the basket. Print the number of
fruits of each type and the total number of fruits in the basket.

Task 2:
Write a C++ program to calculate the total marks of each student of a class in
Physics, Chemistry and Mathematics and the average marks of the class. The user
enters the number of students in the class. Create a class named Marks with data
members for roll number, name and marks. Create three other classes inheriting
the Marks class, namely Physics, Chemistry and Mathematics, which are used to
define marks in individual subject of each student. Roll number of each student will
be generated automatically.

Task 3:

75
OOPs Lab Manual

Write a program with a mother class and an inherited daughter class. Both of them
should have a method void display() that prints a message (different for mother and
daughter).In the main define a daughter and call the display() method on it.

Student Registration No: ________________________

Teacher Signature: ________________________

LAB EXPERIMENT # 10

Objective: To implement the concept of polymorphism (dynamic Binding or Late


Binding) and display the output

76
OOPs Lab Manual

Example 1:
#include<iostream>
using namespace std;
   
class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0)  {real = r;   imag = i;}
       
    // This is automatically called when '+' is used with
    // between two Complex objects
    Complex operator + (Complex const &obj) {
         Complex res;
         res.real = real + obj.real;
         res.imag = imag + obj.imag;
         return res;
    }
    void print() { cout << real << " + i" << imag << endl; }
};
   
int main()
{
    Complex c1(10, 5), c2(2, 4);
    Complex c3 = c1 + c2; // An example call to "operator+"
    c3.print();
}

Output:

Example 2:
// pointers to base class
#include <iostream>
using namespace std;

class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }

77
OOPs Lab Manual

};

class Rectangle: public Polygon {


public:
int area()
{ return width*height; }
};

class Triangle: public Polygon {


public:
int area()
{ return width*height/2; }
};

int main () {
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = &rect;
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << rect.area() << '\n';
cout << trgl.area() << '\n';
return 0;
}

Output:

Task 1:
Create one example of your own.

Student Registration No: ________________________

Teacher Signature: ________________________

LAB EXPERIMENT # 11

78
OOPs Lab Manual

Objective: To implement exception handling using TRY-CATCH statement and


display the result.

Example 1:
// exceptions
#include <iostream>
using namespace std;

int main () {
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
}
return 0;
}

Output:

Task 1:
Write a C++ program to create a class with its own operator new. This
operator should allocate ten objects, and on the eleventh object run out of
memory and throw an exception. Also add a static member function that
reclaims this memory. Now create a main( ) with a try block and
a catch clause that calls the memory-restoration routine. Put these inside
a while loop, to demonstrate recovering from an exception and continuing
execution.

Student Registration No: ________________________

Teacher Signature: ________________________

LAB EXPERIMENT # 12

79
OOPs Lab Manual

Objective: To implement the concept of collection in java and run the program

Example:
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}

Call this file AccountBalance.java and put it in a directory called MyPack.


Next, compile the file. Make sure that the resulting .class file is also in the MyPack
directory. Then, try executing the AccountBalance class, using the following command
line:
java MyPack.AccountBalance

Output:

Student Registration No: ________________________

Teacher Signature: ________________________

80
OOPs Lab Manual

LAB EXPERIMENT # 13

81
OOPs Lab Manual

Objective: To develop applet in java using HTML

The "Hello World" Applet

Create a Java Source File:

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {


public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}

Create an HTML File that Includes the Applet:

Using a text editor, create a file named Hello.html in the same directory that
contains HelloWorld.class. This HTML file should contain the following text:

<HTML>
<HEAD>
<TITLE> A Simple Program </TITLE>
</HEAD>
<BODY>

Here is the output of my program:


<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>

Once you've successfully completed these steps, you should see


something like this in the browser window:

Output:

82
OOPs Lab Manual

Student Registration No: ________________________

Teacher Signature: ________________________

83

You might also like