0% found this document useful (0 votes)
23 views34 pages

C++ Lab Manual for Object-Oriented Programming

This document is a lab manual for Object-Oriented Programming using C++ at Visvesvaraya Technological University. It includes various C++ programming assignments such as finding the largest of three numbers, sorting elements, displaying student details, and implementing bank employee functionalities. The manual also covers concepts like function overloading, operator overloading, multiple inheritance, and constructors in derived classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views34 pages

C++ Lab Manual for Object-Oriented Programming

This document is a lab manual for Object-Oriented Programming using C++ at Visvesvaraya Technological University. It includes various C++ programming assignments such as finding the largest of three numbers, sorting elements, displaying student details, and implementing bank employee functionalities. The manual also covers concepts like function overloading, operator overloading, multiple inheritance, and constructors in derived classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

BELAGAVI

LAB MANUAL

OBJECT ORIENTED PROGRAMMING USING C+


+
(BCS306B)

NAME: LAXMI B
MAGADUM

USN : 2VX22CBO23
SEM : III

PROGRAMME: COMPUTER SCIENCE AND


BUSSINESS SYSTEM
Certificate

This is certify that Mr./Mrs.

with USN has satisfactorily completed all the

Laboratory Assignment of Subject Object-Oriented Programming with

C++ having Subject Code BCS306B during the academic year 2023-24.

Faculty in-charge Programme co-ordinator

Signature of the Examiners


1. Develop a C++ program to find the largest of three numbers
 Aim: Finding the largest of three numbers
 Algorithm:
 Start.
 Read three numbers (num1, num2, num3) from the user.
 Assume the first number (num1) is the largest.
 Compare num2 with the current largest. If num2 is greater, update
the largest to num2.
 Compare num3 with the current largest. If num3 is greater, update
the largest to num3.
 Print the largest number.
 Stop.

 Source code:

#include<iostream>

using namespace std;

int main()

double x1,x2,x3;

cout<<"Enter any three numbers";

cin>>x1>>x2>>x3;

if(x1>=x2 && x1>=x3)

cout<<"Largest number is:"<<x1;

else if(x2>=x1 && x2>=x3)

cout<<"Largest number is:"<<x2;

else

cout<<"Largest number is:"<<x3;

return 0;
}

OUTPUT 1:

Enter any three numbers: 45

24

56

Largest number is: 56

OUTPUT 2:

Enter any three numbers: 67

99

78

Largest number is: 99


2. Develop a C++ program to sort the elements in ascending and
descending order.
 Aim: Sorting the elements in ascending and
descending order.
 Algorithm:
Here are the steps to find the largest of three
numbers:
 Start.
 Read three numbers (num1, num2, num3)
from the user.
 Assume the first number (num1) is the largest.
 Compare num2 with the current largest. If
num2 is greater, update the largest to num2.
 Compare num3 with the current largest. If
num3 is greater, update the largest to num3.
 Print the largest number.
 Stop.
Here are the steps to sort three numbers in
ascending order:
 Start.
 Read three numbers (num1, num2, num3)
from the user.
 Compare num1 with num2. If num1 is greater
than num2, swap them.
 Compare the new num1 (which could be the
original num1 or num2) with num3. If num1 is
greater than num3, swap them.
 Compare num2 with num3. If num2 is greater
than num3, swap them.
 Print the numbers in ascending order (num1,
num2, num3).
 Stop.
 Source code:
#include<iostream>

using namespace std;

int main()

int num[100],n;

int i,j,temp;

cout<<"Enter n for the numbers you want to sort:"<<endl<<endl;

cin>>n;

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

cout<<"Enter number"<<endl;

cin>>num[i];

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

for(j=0;j<n;j++){

if(num[i]<num[j]){

temp=num[i];

num[i]=num[j];

num[j]=temp;

}
cout<<"Ascending: "<<endl;

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

cout<<" "<<num[i]<<endl;;

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

for(j=0;j<n;j++){

if(num[i]>num[j]){

temp=num[i];

num[i]=num[j];

num[j]=temp;

cout<<" Descending:"<<endl;

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

cout<<" "<<num[i]<<endl;

return 0;

OUTPUT 1:

Enter number of values you want to sort: 4

Enter value

67
Enter value

19

Enter value

88

Enter value

98

Ascending:

19

67

88

98

Descending:

98

88

67

19

OUTPUT 2:

Enter number of values you want to sort: 3

Enter value

98
Enter value

Enter value

23
Ascending:

23

98

Descending:

98

23

5
3. Develop a C++ program using classes to display student name, roll
number, marks obtained in two subjects and total score of student
 Aim: Display student name, roll number, marks obtained
in two subject and total score of student using classes.
 Algorithm:
 Start
 Define a class Student
 Declare private member variables for name,
roll number, marks of two subjects, and total
score
 Define public member functions to set and get
values for name, roll number, marks, and
calculate total score
 Read student details (name, roll number,
marks of two subjects) from user input
 Create an object of the Student class
 Set the values for name, roll number, and
marks using the public member functions
 Calculate the total score
 Print student details (name, roll number,
marks, total score)
 Stop
 Source code:
#include<iostream>

using namespace std;

class Student
{
public:
string name;
int roll_no;
int marks1;
int marks2;
int total_score()
{
return marks1 + marks2;
};
int main()
{
Student s1;
cout<<"Enter the name of the student:";
cin>>[Link];
cout<<"Enter the roll number of student:";
cin>>[Link];
cout<<"Enter the marks of the student in subject 1:";
cin>>s1.marks1;
cout<<"Enter the marks of the student in subject 2:";
cin>>s1.marks2;
cout<<"The name of the student is:"<<[Link]<<endl;
cout<<"The roll number of the student is:"<<s1.roll_no<<endl;
cout<<"The marks of the student in subject 1
are:"<<s1.marks1<<endl;
cout<<"The marks of the student in subject 2
are:”<<s1.marks2<<endl;
cout<<"The total score of the student is:"<<s1.total_score()<<endl;
return 0;
}

OUTPUT 1:
Enter the name of the student :Abc

Enter the roll number of the student : 23

Enter the marks of the student in subject 1:87

Enter the marks of the student in subject 2: 89

The name of the student is :Abc


The roll number of the student is: 23

The marks of the student in subject 1 are:87

The marks of the student in subject 2 are: 89

The total score of the student is : 176

OUTPUT 2:

Enter the name of the student :Laxmi

Enter the roll number of the student : 76

Enter the marks of the student in subject 1:34

Enter the marks of the student in subject 2: 87

The name of the student is :Laxmi

The roll number of the student is: 76

The marks of the student in subject 1 are:34

The marks of the student in subject 2 are: 87

The total score of the student is : 121


4. Develop a C++ program for a bank empolyee to print name of the employee,
account_no. & [Link] invalid balance if amount<500, Display the same,
also display the balance after withdraw and deposit.
 Aim: Display the information about bank employee.
 Algorithm:
 Start
 Read employee's name, account number, and initial
balance from user input
 If initial balance is less than 500, print "Invalid balance"
and stop
 Print employee's name, account number, and initial
balance
 Read withdrawal amount from user input
 If withdrawal amount is less than or equal to balance,
subtract withdrawal amount from balance and print new
balance
 Else, print "Insufficient balance" and stop
 Read deposit amount from user input
 Add deposit amount to balance and print new balance
 Stop
 Source code:

#include <iostream>
#include <string>

using namespace std;

class BankEmployee {
private:
string name;
int accountNo;
double balance;

public:
BankEmployee() {}

void setDetails() {
cout << "Enter name: ";
cin>>name;
cout << "Enter account number: ";
cin >> accountNo;
cout << "Enter balance: ";
cin >> balance;
}

void printDetails() {
cout << "Name: " << name << endl;
cout << "Account No.: " << accountNo << endl;
cout << "Balance: " << balance << endl;
}

void withdraw(double amount) {


if (balance - amount < 500) {
cout << "Invalid balance!" << endl;
return;
}
balance -= amount;
cout << "Withdrawal successful. Balance after withdrawal: " << balance
<< endl;
}

void deposit(double amount) {


balance += amount;
cout << "Deposit successful. Balance after deposit: " << balance << endl;
}
};
int main() {
BankEmployee employee;
[Link]();
[Link]();

cout << "Enter withdrawal amount: ";


double withdrawAmount;
cin >> withdrawAmount;
[Link](withdrawAmount);

cout << "Enter deposit amount: ";


double depositAmount;
cin >> depositAmount;
[Link](depositAmount);

return 0;
}

OUTPUT 1:
Enter name: xyz
Enter account number: 666554
Enter balance: 7000
Name: xyz
Account No.: 666554
Balance: 7000
Enter withdrawal amount: 500
Withdrawal successful. Balance after withdrawal: 6500
Enter deposit amount: 600
Deposit successful. Balance after deposit: 7100

OUTPUT 2:
Enter name: ABC
Enter account number: 666754
Enter balance: 700
Name: ABC
Account No.: 666754
Balance: 700
Enter withdrawal amount: 500
Withdrawal successful. Balance after withdrawal: 200
Enter deposit amount: 600
Deposit successful. Balance after deposit: 1300
5. Develop a C++ program to demonstrate function overloading for the
following prototypes.

Add(int a, int b)
add(double a, double b)
 Aim: Demonstrate function overloading.
 Algorithm:
 Start. Define a function Add with parameters (int a,
int b) that returns the sum of a and b
 Define another function Double with parameters
(double a, double b) that returns the product of a
and b
 Call Add with integer arguments and store the
result
 Call Double with double arguments and store the
result
 Print the results and stop.
 Source code:
#include <iostream>
using namespace std;
void add(int a, int b)
{
cout << "sum = " << (a + b);
}
void add(double a, double b)
{
cout << endl << "sum = " << (a + b);
}
int main()
{
add(10, 2);
add(5.3, 6.2);
return 0;
}
Output :
sum = 12
sum = 11.5

6. Develop a C++ program using Operator Overloading for overloading Unary


minus operator.
 Aim: Overloading Unary minus operator
 Algorithm:
 Start
 Define a Class: Create a class named MyNumber with a
private member variable value.
 Unary Minus Overloading: Overload the unary minus
operator (operator-) to return a new MyNumber object with
the negated value.
 Display Method: Implement a method named display to
display the
value of the object.
 Main Function: In the main function, create instances of
MyNumber,
apply unary minus overloading, and display the original
and modified
numbers.
 Stop

 Source code:

#include<iostream>
class MyNumber
{
private:
int value;

public:
MyNumber(int val) : value(val) {}
MyNumber operator-() {
return MyNumber(-value);
}

void display() {
std::cout << "Value: " << value << std::endl;
}
};

int main() {
MyNumber num1(5);
MyNumber num2 = -num1;
std::cout << "Original Number:" << std::endl;
[Link]();
std::cout << "Number after Unary Minus Overloading:" << std::endl;
[Link]();

return 0;
}

OUTPUT 1:
Original Number:
Value: 5
Number after Unary Minus Overloading:
Value: -5

OUTPUT 2:
Original Number:
Value: 8
Number after Unary Minus Overloading:
Value: -8
7. Develop a C++ program to implement Multiple inheritance for
performing arithmetic operation of two numbers

 Aim : Multiple inheritance for arithmetic operation


 Algorithm :
 Start
 Numbers is the base class which contains two protected data members
num1 and num2.
 Addition is a derived class from Numbers which performs addition.
 Multiplication is another derived class from Numbers which performs
multiplication.
 Stop
 Source code:
#include <iostream>
class Addition
{
public:
int add(int a, int b)
{
return a + b;
}
};
class Subtraction
{
public:
int subtract(int a, int b)
{
return a - b;
}
};

class Arithmetic : public Addition, public Subtraction

{
public:
int multiply(int a, int b)
{
return a * b;
}

int divide(int a, int b)


{
if (b != 0)
{
return a / b;
}
else
{
cout << "Error: Division by zero" << endl;
return 0;
}
}
};

int main()
{
Arithmetic calculator;
int num1 = 9;
int num2 = 5;
int sum = [Link](num1, num2); s
cout << "Sum: " << sum << endl;
int difference = [Link](num1, num2);
cout << "Difference: " << difference << endl;
int product = [Link](num1, num2);
cout << "Product: " << product << endl;
int quotient = [Link](num1, num2);
cout << "Quotient: " << quotient << endl;
return 0;
}

OUTPUT:
Sum: 14
Difference: 4
Product: 45
Quotient: 1
8. Develop a C++ program using Constructor in Derived classes to
initialize alpha, beta and gamma and display corresponding values.

 Aim: Constructor in Derived classes to initialize alpha, beta and gamma and
display corresponding values.

 Algorithm:

 Start

 Base class has a member variable alpha and a constructor to initialize it.

 Derived A is derived from Base and has an additional member variable beta.
It initializes both alpha and beta using its constructor.

 Derived B is derived from Derived A and introduces one more member


variable gamma. It initializes alpha, beta, and gamma using its constructor.

 Each constructor prints a message to the console when called.

 display() function in both Derived A and Derived B classes is used to display


the values of alpha, beta, and gamma. Note that the function in Derived B
overrides the one in Derived A.

 Stop

 Source code:
#include <iostream>
class Alpha
{
protected:
int alpha;
public:
Alpha(int a) : alpha(a)
{
}
void displayAlpha()
{
cout << "Alpha: " << alpha << endl;
}
};
class Beta : public Alpha
{
private:
int beta;
public:
Beta(int a, int b) : Alpha(a), beta(b)
{
}
void displayBeta()
{
displayAlpha();
cout << "Beta: " << beta << endl;
}
};
class Gamma : public Alpha
{
private:
int gamma;
public:
Gamma(int a, int g) : Alpha(a), gamma(g)
{
}
void displayGamma()
{
displayAlpha();
cout << "Gamma: " << gamma << endl;
}
};
int main() {
Beta objBeta(11, 12);
[Link]();
Gamma objGamma(13, 14);
[Link]();
return 0;

OUTPUT:
Alpha: 11
Beta: 12
Alpha: 13
Gamma: 14
[Link] a C++ program to create a text file, check file created or not, if
created it will write some text into the file and then read the text from the file.

 Aim : creating a textfile check if it is created or not

 Algorithm:

 Include necessary header files like iostream, fstream.

 Define a function to create a text file and write some text into
it.

 Define another function to read the text from the file.

 In the main() function, call the function to create and write text
into the file.

 Then call the function to read text from the file.

 Print the text read from the file onto the console.

 Source code:
#include <iostream>

#include <fstream>

#include <string>

int main() {
ofstream outputFile("[Link]");

if (!outputFile.is_open())

cerr << "Error: File could not be created." << endl; return

1;

}
string textToWrite = "There is some text written in the file.";

outputFile << textToWrite << endl;

[Link]();

ifstream inputFile("[Link]");

if (!inputFile.is_open())

cerr << "Error: File could not be opened for reading." << endl;

return 1;

string textRead;

while (getline(inputFile, textRead))

cout << "Text from the file: " << textRead << endl;

[Link]();

return 0;

}
OUTPUT:

Text from the file: There is some text written in the file.
[Link] a C++ program to write and read time in/from binary file using
fstream
 Aim: to write and read time in/from binary file using fstream
 Algorithm:
 Start
 Include necessary header files like iostream, fstream, and
ctime for time-related functions.
 Define a structure to hold the time information. In this
case, we can use the tm structure from ctime.
 Define a function to write the current time to a binary file.
 Define another function to read the time from the binary
file.
 In the main() function, call the function to write the
current time to the file.
 Then call the function to read the time from the file.
 Print the time read from the file onto the console.
 End
 Source code:
#include <iostream>

#include <fstream>

#include <ctime>

int main()

time_t currentTime = time(0);

tm* timeInfo = localtime(&currentTime);

std::ofstream outFile("time_data.bin",

std::ios::binary); if (!outFile) {
std::cerr << "Failed to open the file for writing." << std::endl;
return 1;

[Link](reinterpret_cast<char*>(timeInfo), sizeof(tm));

[Link]();

std::ifstream inFile("time_data.bin", std::ios::binary);

if (!inFile) {

cerr << "Failed to open the file for reading." << endl; return 1;

tm readTimeInfo;

[Link](reinterpret_cast<char*>(&readTimeInfo), sizeof(tm));

[Link]();

cout << "Original Time: " << asctime(timeInfo);

cout << "Read Time: " << asctime(&readTimeInfo);

return 0;

OUPUT:

Original Time: Wed Nov 8 [Link] 2023

Read Time: Wed Nov 8 [Link] 2023


[Link] a function which throws a division by zero exception and catch
it in catch block. Write a C++ program to demonstrate usage of try, catch
and throw to handle exception.
 Aim: demonstrate usage of try, catch and throw to handle exception.
 Algorithm:
 Start
 The divide() function takes two double values as parameters,
performs division, and throws an exception if the divisor is
zero.
 In the main() function, the user is prompted to enter the
dividend and divisor.
 Inside the try block, the division operation is attempted by
calling the divide() function.
 If a division by zero occurs, the program throws an exception
of type const char* with the message "Division by zero error".
 The catch block catches this exception and handles it by
printing an error message to the standard error stream (cerr).
 Stop
 Source code:
#include <iostream>

int divide(int numerator, int denominator)

if (denominator == 0)

{
throw std::runtime_error("Division by zero is not allowed.");
}
return numerator / denominator;
}
int main() {
int numerator, denominator;

cout << "Enter numerator: ";


cin >> numerator;
cout << "Enter denominator: ";
cin >> denominator;
try {
int result = divide(numerator, denominator);
cout << "Result of division: " << result << endl;
} catch (const std::runtime_error &ex) {
cerr << "Exception caught: " << [Link]() << endl;
}
return 0;
}
OUTPUT 1:
Enter numerator: 88
Enter denominator: 2
Result of division: 44

OUTPUT 2:
Enter numerator: 77
Enter denominator: 11
Result of division: 7

12. Develop a C++ program that handles array out of bounds exception using
C++.

 Aim: program that handles array out of bounds exception using C++.
 Algorithm:
 Start
 Declare an array of size n
 Declare a variable index
 Read the value of index from user input
 If index is within the bounds of the array (0 <= index < n)
 Access arr[index]
 Print arr[index]
 Else
 Print "Array index out of bounds"
 Stop
 Source code:

#include<iostream>

#include <vector>

#include <stdexcept>

int main()

try {

vector<int> numbers = {1, 2, 3, 4, 5}; nt

index;

cout << "Enter an index to access an element in the array: ";

cin >> index;

if (index < 0 || index >= [Link]()) {


throw std::out_of_range("Index is out of bounds.");

int element = [Link](index);

cout << "Element at index " << index << " is: " << element << endl;

} catch (const std::out_of_range &ex) {

cerr << "Exception caught: " << [Link]() << endl;

return 0;

OUTPUT:

Enter an index to access an element in the array: 3

Element at index 3 is: 4

Enter an index to access an element in the array: 7


Exception caught: Index is out of bounds.

Common questions

Powered by AI

In the program, constructors are used in a three-level inheritance hierarchy. The base class 'Alpha' initializes the variable 'alpha'. In 'Beta', which derives from 'Alpha', its constructor initializes both 'alpha' (calling the base constructor) and 'beta'. The class 'Gamma', also deriving from 'Alpha', initializes 'alpha' and adds a new member 'gamma', showing how constructors in derived classes can call base class constructors to ensure proper initialization throughout the inheritance chain .

The C++ program ensures an employee's account balance is valid by checking it before allowing any transactions. If the initial balance is less than 500, the program outputs 'Invalid balance' and stops further operations. Additionally, during withdrawals, it verifies that the account balance minus the withdrawal amount isn't less than 500 to prevent invalid transactions .

Class encapsulation in the student information system is achieved by declaring member variables for name, roll number, and marks as private. This ensures that they cannot be accessed directly from outside the class. Public member functions are provided for setting and getting values, and for calculating the total score, ensuring control over how data is manipulated and maintaining data integrity by preventing unauthorized or erroneous modifications .

Function overloading in C++ allows functions to have the same name with different parameters, enabling operations on different data types or different numbers of parameters using a simplified naming convention. In the presented program, two "add" functions are used: one handles integer parameters, and the other handles double parameters, demonstrating the ability of function overloading to differentiate functions based on parameter types .

Memory-based file operations using iostream and fstream in the program are effective for simplifying file input and output operations in C++. However, the potential pitfalls include the possibility of file operation failures (such as files not opening correctly) and inadequate error handling for these scenarios. Additionally, using text-based operations for large files can be inefficient compared to binary file operations, and a failure to check stream states rigorously can lead to subtle bugs .

The program utilizes ofstream to write and ifstream to read binary data from a file. Data integrity is ensured by verifying that the file opens successfully for both operations. It writes a 'tm' structure representing the current time using binary data, then reads it back, confirming consistency by checking the read data matches the original time structure using asctime(). Error conditions for file operations are managed with appropriate error messages .

The program handles array out-of-bounds access by throwing an 'std::out_of_range' exception when the user enters an invalid index. This exception is caught and managed by printing a related error message, preventing program crashes and ensuring robust error handling. Implementing exceptions for such errors makes the code more secure and user-friendly, avoiding undefined behavior that could compromise program stability .

Encapsulation is preserved in the BankEmployee class by making the member variables name, accountNo, and balance private, thus preventing direct access from outside the class. However, the use of public methods for setting and manipulating these data points ensures control is maintained over how the variables can be changed, offering a proper encapsulation level while still allowing some flexibility in modifying the information .

The program uses a try-catch block for exception handling where the divide function throws a runtime exception when the denominator is zero, using the statement 'throw std::runtime_error("Division by zero is not allowed.")'. This exception is caught in the main function, where an error message is printed using the catch block to handle the exception gracefully .

The program sorts numbers using nested loops. For ascending order, it iteratively compares each element with all others, swapping them if the current element is greater than the compared one. Similarly, for descending order, it swaps elements if the current one is less than the compared one. This double-nested loop approach ensures all numbers are checked against each other, achieving the desired order .

You might also like