0% found this document useful (0 votes)
54 views21 pages

Lab Manual

Uploaded by

sumukhchavan6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views21 pages

Lab Manual

Uploaded by

sumukhchavan6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Object Oriented Programming with C++ BCS306B

1. Develop a C++ program to find the largest of three numbers


#include <iostream>
using namespace std;

int main() {

double n1, n2, n3;

cout << "Enter three numbers: ";


cin >> n1 >> n2 >> n3;

// check if n1 is the largest number


if(n1 >= n2 && n1 >= n3)
cout << "Largest number: " << n1;

// check if n2 is the largest number


else if(n2 >= n1 && n2 >= n3)
cout << "Largest number: " << n2;

// if neither n1 nor n2 are the largest, n3 is the largest


else
cout << "Largest number: " << n3;

return 0;
}
Output
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 1


Object Oriented Programming with C++ BCS306B

2. Develop a C++ program to sort the elements in ascending and descending order.
#include <iostream>
using namespace std;

#define MAX 100

int main() {
// Array declaration
int arr[MAX];
int n, i, j;
int temp;

// Read total number of elements to read


cout << "Enter total number of elements to read: ";
cin >> n;

// Read n elements
for (i = 0; i < n; i++) {
cout << "Enter element [" << i + 1 << "]: ";
cin >> arr[i];
}

// Print input elements


cout << "Unsorted Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl;

// Sorting - Ascending ORDER


for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

// Print sorted array elements in Ascending Order


cout << "Sorted (Ascending Order) Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl;

// Sorting - Descending ORDER


for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 2
Object Oriented Programming with C++ BCS306B

}
// Print sorted array elements in Descending Order
cout << "Sorted (Descending Order) Array elements:" << endl;
for (i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl;

return 0;
}

Output

Enter total number of elements to read: 5


Enter element [1]: 13
Enter element [2]: 21
Enter element [3]: 6
Enter element [4]: 49
Enter element [5]: 33
Unsorted Array elements:
13 21 6 49 33
Sorted (Ascending Order) Array elements:
6 13 21 33 49
Sorted (Descending Order) Array elements:
49 33 21 13 6

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 3


Object Oriented Programming with C++ BCS306B

3. Develop a C++ program using classes to display student name, roll number, marks obtained in two
Subjects and total score of student.

#include <iostream>
#include <string>
using namespace std;

// Define a class to represent a student


class Student {
private:
string name;
int rollNumber;
float marks1;
float marks2;

public:
// Method to input student details
void inputDetails() {
cout << "Enter student name: ";
getline(cin, name);
cout << "Enter roll number: ";
cin >> rollNumber;
cout << "Enter marks for subject 1: ";
cin >> marks1;
cout << "Enter marks for subject 2: ";
cin >> marks2;
cin.ignore(); // To ignore the newline character left in the buffer
}

// Method to calculate total score


float calculateTotal() {
return marks1 + marks2;
}

// Method to display student details


void displayDetails() {
cout << "\nStudent Details:" << endl;
cout << "Name: " << name << endl;
cout << "Roll Number: " << rollNumber << endl;
cout << "Marks in Subject 1: " << marks1 << endl;
cout << "Marks in Subject 2: " << marks2 << endl;
cout << "Total Score: " << calculateTotal() << endl;
}
};

int main() {
Student student;
// Input student details
student.inputDetails();
// Display student details
student.displayDetails();
return 0;
}

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 4


Object Oriented Programming with C++ BCS306B

Output

Enter student name: John Doe


Enter roll number: 12345
Enter marks for subject 1: 85
Enter marks for subject 2: 90

Student Details:
Name: John Doe
Roll Number: 12345
Marks in Subject 1: 85
Marks in Subject 2: 90
Total Score: 175

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 5


Object Oriented Programming with C++ BCS306B

4. Develop a C++ program for a bank employee to print name of the employee, account_no. & balance.
Print invalid balance if amount<500, Display the same, also display the balance after withdraw and
deposit.

#include <iostream>
#include <string>
using namespace std;

// Define a class to represent a bank account


class BankAccount {
private:
string employeeName;
int accountNo;
float balance;

public:
// Constructor to initialize the bank account with details
BankAccount(string name, int accNo, float initialBalance) {
employeeName = name;
accountNo = accNo;
if (initialBalance < 500) {
cout << "Invalid initial balance. Setting balance to 500." << endl;
balance = 500;
} else {
balance = initialBalance;
}
}

// Method to deposit money


void deposit(float amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: $" << amount << endl;
} else {
cout << "Invalid deposit amount." << endl;
}
}

// Method to withdraw money


void withdraw(float amount) {
if (amount > 0) {
if (amount <= balance) {
balance -= amount;
cout << "Withdrawn: $" << amount << endl;
} else {
cout << "Insufficient balance." << endl;
}
} else {
cout << "Invalid withdrawal amount." << endl;
}
}

// Method to display account details


void displayDetails() {
Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 6
Object Oriented Programming with C++ BCS306B

cout << "\nEmployee Details:" << endl;


cout << "Name: " << employeeName << endl;
cout << "Account Number: " << accountNo << endl;
cout << "Balance: $" << balance << endl;
}
};

int main() {
string name;
int accNo;
float initialBalance;
float depositAmount, withdrawAmount;

// Input employee details


cout << "Enter employee name: ";
getline(cin, name);
cout << "Enter account number: ";
cin >> accNo;
cout << "Enter initial balance: ";
cin >> initialBalance;

// Create a BankAccount object with the given details


BankAccount account(name, accNo, initialBalance);

// Display initial details


account.displayDetails();

// Deposit money
cout << "\nEnter amount to deposit: ";
cin >> depositAmount;
account.deposit(depositAmount);
account.displayDetails();

// Withdraw money
cout << "\nEnter amount to withdraw: ";
cin >> withdrawAmount;
account.withdraw(withdrawAmount);
account.displayDetails();

return 0;
}

Output
Enter employee name: Alice Smith
Enter account number: 98765
Enter initial balance: 450
Invalid initial balance. Setting balance to 500.

Employee Details:
Name: Alice Smith
Account Number: 98765
Balance: $500

Enter amount to deposit: 200


Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 7
Object Oriented Programming with C++ BCS306B

Deposited: $200

Employee Details:
Name: Alice Smith
Account Number: 98765
Balance: $700

Enter amount to withdraw: 100


Withdrawn: $100

Employee Details:
Name: Alice Smith
Account Number: 98765
Balance: $600

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 8


Object Oriented Programming with C++ BCS306B

5. Develop a C++ program to demonstrate function overloading for the following prototypes.

add(int a, int b)
add(double a, double b)

#include <iostream>
using namespace std;

// Overloaded function for adding two integers


int add(int a, int b) {
return a + b;
}

// Overloaded function for adding two doubles


double add(double a, double b) {
return a + b;
}

int main() {
int int1, int2;
double double1, double2;

// Input integers
cout << "Enter the first integer: ";
cin >> int1;
cout << "Enter the second integer: ";
cin >> int2;

// Input doubles
cout << "Enter the first double: ";
cin >> double1;
cout << "Enter the second double: ";
cin >> double2;

// Display results
cout << "\nSum of integers: " << add(int1, int2) << endl;
cout << "Sum of doubles: " << add(double1, double2) << endl;

return 0;
}

Output
Enter the first integer: 5
Enter the second integer: 10
Enter the first double: 3.5
Enter the second double: 2.1

Sum of integers: 15
Sum of doubles: 5.6

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 9


Object Oriented Programming with C++ BCS306B

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

#include<iostream>
using namespace std;

class NUM
{
private:
int n;

public:
//function to get number
void getNum(int x)
{
n=x;
}
//function to display number
void dispNum(void)
{
cout << "value of n is: " << n;
}
//unary - operator overloading
void operator - (void)
{
n=-n;
}
};

int main()
{
NUM num;
num.getNum(10);
-num;
num.dispNum();
cout << endl;
return 0;

}
Output:
value of n is: -10

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 10


Object Oriented Programming with C++ BCS306B

7. Develop a C++ program to implement Multiple inheritance for performing arithmetic operation of
two numbers.

#include <iostream>
using namespace std;

// Base class for addition


class Addition {
public:
// Method to perform addition
int add(int a, int b) {
return a + b;
}
};

// Base class for subtraction


class Subtraction {
public:
// Method to perform subtraction
int subtract(int a, int b) {
return a - b;
}
};

// Derived class for arithmetic operations


class ArithmeticOperations : public Addition, public Subtraction {
public:
// Method to perform multiplication
int multiply(int a, int b) {
return a * b;
}

// Method to perform division


double divide(double a, double b) {
if (b != 0) {
return a / b;
} else {
cout << "Error: Division by zero is not allowed." << endl;
return 0;
}
}
};

int main() {
ArithmeticOperations ops;
int num1, num2;
double num1D, num2D;

// Input integers
cout << "Enter the first integer: ";
cin >> num1;
cout << "Enter the second integer: ";
cin >> num2;

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 11


Object Oriented Programming with C++ BCS306B

// Perform and display operations


cout << "\nAddition: " << ops.add(num1, num2) << endl;
cout << "Subtraction: " << ops.subtract(num1, num2) << endl;
cout << "Multiplication: " << ops.multiply(num1, num2) << endl;

// Input doubles for division


cout << "\nEnter the first double: ";
cin >> num1D;
cout << "Enter the second double: ";
cin >> num2D;

cout << "\nDivision: " << ops.divide(num1D, num2D) << endl;

return 0;
}

Output
Enter the first integer: 10
Enter the second integer: 5

Addition: 15
Subtraction: 5
Multiplication: 50

Enter the first double: 10.5


Enter the second double: 2.0

Division: 5.25

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 12


Object Oriented Programming with C++ BCS306B

8. Develop a C++ program using Constructor in Derived classes to initialize alpha, beta and gamma and
display corresponding values.

#include <iostream>
using namespace std;

// Base class
class Base {
protected:
int alpha;
public:
// Constructor for Base class
Base(int a) : alpha(a) {
// Initialization of alpha
}
};

// Derived class
class Derived : public Base {
private:
int beta;
int gamma;
public:
// Constructor for Derived class
Derived(int a, int b, int c) : Base(a), beta(b), gamma(c) {
// Initialization of alpha (from Base class), beta, and gamma
}

// Method to display values


void displayValues() {
cout << "Alpha: " << alpha << endl;
cout << "Beta: " << beta << endl;
cout << "Gamma: " << gamma << endl;
}
};

int main() {
int alpha, beta, gamma;

// Input values
cout << "Enter value for alpha: ";
cin >> alpha;
cout << "Enter value for beta: ";
cin >> beta;
cout << "Enter value for gamma: ";
cin >> gamma;

// Create an instance of Derived class


Derived obj(alpha, beta, gamma);

// Display the values


cout << "\nValues:" << endl;
obj.displayValues();

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 13


Object Oriented Programming with C++ BCS306B

return 0;
}

Enter value for alpha: 10


Enter value for beta: 20
Enter value for gamma: 30

Values:
Alpha: 10
Beta: 20
Gamma: 30

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 14


Object Oriented Programming with C++ BCS306B

9. Develop 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.

#include <iostream>
#include <fstream> // For file handling
#include <string>
using namespace std;

int main() {
string filename = "example.txt";
string textToWrite;
string line;

// Create and open a text file


ofstream outFile(filename);

// Check if the file is created


if (!outFile) {
cerr << "Error: File could not be created." << endl;
return 1; // Exit with an error code
}

cout << "File created successfully!" << endl;

// Get text input from the user


cout << "Enter the text to write into the file: ";
cin.ignore(); // Ignore any leftover newline character in the input buffer
getline(cin, textToWrite);

// Write the text to the file


outFile << textToWrite;
outFile.close(); // Close the file after writing

// Open the file for reading


ifstream inFile(filename);

// Check if the file was successfully opened


if (!inFile) {
cerr << "Error: File could not be opened for reading." << endl;
return 1; // Exit with an error code
}

cout << "Reading from the file..." << endl;

// Read and display the text from the file


while (getline(inFile, line)) {
cout << line << endl;
}

inFile.close(); // Close the file after reading

return 0;
}

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 15


Object Oriented Programming with C++ BCS306B

Output:

File created successfully!


Enter the text to write into the file: Hello, this is a test file.

Reading from the file...


Hello, this is a test file.

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 16


Object Oriented Programming with C++ BCS306B

10. Develop a C++ program to write and read time in/from binary file using fstream

#include <iostream>
#include <fstream> // For file handling
using namespace std;

// Structure to store time


struct Time {
int hours;
int minutes;
int seconds;
};

// Function to write time to a binary file


void writeTimeToFile(const string& filename, const Time& time) {
ofstream outFile(filename, ios::binary);
if (!outFile) {
cerr << "Error: File could not be opened for writing." << endl;
return;
}
outFile.write(reinterpret_cast<const char*>(&time), sizeof(Time));
outFile.close();
}

// Function to read time from a binary file


void readTimeFromFile(const string& filename, Time& time) {
ifstream inFile(filename, ios::binary);
if (!inFile) {
cerr << "Error: File could not be opened for reading." << endl;
return;
}
inFile.read(reinterpret_cast<char*>(&time), sizeof(Time));
inFile.close();
}

int main() {
string filename = "time.bin";
Time time;

// Input time from user


cout << "Enter hours (0-23): ";
cin >> time.hours;
cout << "Enter minutes (0-59): ";
cin >> time.minutes;
cout << "Enter seconds (0-59): ";
cin >> time.seconds;

// Write time to binary file


writeTimeToFile(filename, time);
cout << "Time written to file successfully!" << endl;

// Read time from binary file


Time readTime;
readTimeFromFile(filename, readTime);
Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 17
Object Oriented Programming with C++ BCS306B

// Display the read time


cout << "\nTime read from file:" << endl;
cout << "Hours: " << readTime.hours << endl;
cout << "Minutes: " << readTime.minutes << endl;
cout << "Seconds: " << readTime.seconds << endl;

return 0;
}

Output:

Enter hours (0-23): 14


Enter minutes (30-59): 45
Enter seconds (0-59): 50
Time written to file successfully!

Time read from file:


Hours: 14
Minutes: 45
Seconds: 50

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 18


Object Oriented Programming with C++ BCS306B

11. Develop 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

#include <iostream>
using namespace std;
int divide(int a, int b) {
if (b == 0) {
throw "Division by zero error!"; // Throw an exception
}
return a / b;
}
int main() {
int num1, num2, result;
try {
cout << "Enter two numbers: ";
cin >> num1 >> num2;
result = divide(num1, num2);
cout << "Result: " << result << endl;
} catch (const char* msg) {
cout << "Exception caught: " << msg << endl;
}
return 0;
}

Enter two numbers: 10 0


Exception caught: Division by zero error!

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 19


Object Oriented Programming with C++ BCS306B

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

#include <iostream>
using namespace std;
int main() {
int arr[5];
int index;
cout << "Enter 5 elements for the array: ";
for (int i = 0; i < 5; i++) {
cin >> arr[i];
}
cout << "Enter an index to access: ";
cin >> index;
try {
if (index < 0 || index >= 5) {
throw "Array index out of bounds!";
}
cout << "Element at index " << index << ": " << arr[index] << endl;
} catch (const char* msg) {
cout << "Exception caught: " << msg << endl;
}
return 0;
}

Output
Enter 5 elements for the array: 1 2 3 4 5
Enter an index to access: 6
Exception caught: Array index out of bounds!

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 20


Object Oriented Programming with C++ BCS306B

Dept. Computer Science and Engineering, KLS’s VDIT, Haliyal 21

You might also like