0% found this document useful (0 votes)
8 views

C++ BCA FINAL LAB MANUAL (1)

The document outlines the curriculum for a C++ Programming Lab course at JSPM University Pune, detailing the course code, credits, and practical examination scheme. It includes a list of laboratory experiments that cover fundamental C++ concepts such as control structures, classes, inheritance, and file handling, along with example programs for each topic. The total number of sessions for the lab course is specified as 15.
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)
8 views

C++ BCA FINAL LAB MANUAL (1)

The document outlines the curriculum for a C++ Programming Lab course at JSPM University Pune, detailing the course code, credits, and practical examination scheme. It includes a list of laboratory experiments that cover fundamental C++ concepts such as control structures, classes, inheritance, and file handling, along with example programs for each topic. The total number of sessions for the lab course is specified as 15.
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/ 26

JSPM University Pune

Bachelor of Computer Application(BCA)

“C++ Programming Lab”

Course Type: LC Lab Course Title: “ Programming in C++ Lab”

Course Code: Teaching Scheme: Examination Scheme:

230GCAB03_02

Credits: 2 Lecture (L): Practical: 50 Marks

Tutorial (T): Oral: Nil

Practical (P): 2

Experiential Learning (EL):

Assignment No Lab Course Contents No. Of Sessions

1 Basic, Control Structure and Looping,

2 Class , Object and methods implementation

3 Constructor: Copy Constructor, Default


Constructor, Parameterized Constructor

4 Inline function, friend function, default


argument, Function Overloading,

5 Inheritance: Single, multiple, multilevel,


hierarchy, Constructor and destructor in
derived class.
6 File Handling: Read, Write, Updating of files
using random access

Total Number of Sessions per batch 15

List of Laboratory Experiments


1. Create a program that performs addition, subtraction, multiplication, and division of two
numbers entered by the user.

2. Accept a score from the user and display the corresponding grade (A, B, C, D, F) using if-
else statements.

3. Print various number patterns (like pyramids or triangles) using nested loops.

4. Create a class Person with attributes like name and age. Create an object of the class and
display the details using a method.

5. Write a C++ program to implement a class called Employee that has private member
variables for name, employee ID, and salary. Include member functions to calculate and
set salary based on employee performance.

6 Write a program to create an overloaded function findSquare():

o One version should accept an integer and return its square.

o Another version should accept a floating-point number and return its


square.

7 Create a class BankAccount with attributes account_number, account_holder_name, and


balance. Use a parameterized constructor to initialize the attributes and methods for
depositing and withdrawing money.

8 C++ program to demonstrate the execution of constructor and destructor

9 Implement a class Employee that has private attributes like name, id, and salary. Provide
methods to set and get these attributes, ensuring proper encapsulation.

10 Define a class Circle with attributes radius and methods to calculate the area and
circumference of the circle within the class.(Function within the class)

11 Create a base class Vehicle with attributes like make and model. Derive a class Car that
adds attributes like number_of_seats. Implement a method in the derived class to display
the complete details of the car.

12 Design two base classes Student and Sports with respective attributes. Create a derived
class Result that inherits from both and calculates the total score.

13 Write a program to create a base class Shape with a virtual method calculateArea(). Derive
classes Circle and Rectangle that implement the calculateArea() method differently.
14 Create a class FileManager with methods to write data to a file and read data from the file.
Use objects to manage file operations.

15 Write a program to divide two numbers. Handle the case where the denominator is zero
using a try-catch block.

1.Create a program that performs addition, subtraction, multiplication,


and division of two numbers entered by the user.

Program:

#include <iostream>

using namespace std;

int main() {

double num1, num2;

cout << "Enter two numbers: ";

cin >> num1 >> num2;

cout << "Addition: " << num1 + num2 << endl;

cout << "Subtraction: " << num1 - num2 << endl;

cout << "Multiplication: " << num1 * num2 << endl;

cout << "Division: " << num1 / num2 << endl;

return 0;

Expected Output:

Enter two numbers: 10 5

Addition: 15
Subtraction: 5

Multiplication: 50

Division: 2

2.Accept a score from the user and display the corresponding grade (A, B, C,
D, F) using if-else statements

Program:

#include <iostream>

using namespace std;

int main() {

int score;

cout << "Enter your score: ";

cin >> score;

if (score >= 90) cout << "Grade: A" << endl;

else if (score >= 80) cout << "Grade: B" << endl;

else if (score >= 70) cout << "Grade: C" << endl;

else if (score >= 60) cout << "Grade: D" << endl;

else cout << "Grade: F" << endl;

return 0;

Expected Output:

Enter your score: 85

Grade: B

3. Print various number patterns (like pyramids or triangles) using nested


loops.
Program:

#include <iostream>

using namespace std;

int main() {

int rows = 5;

for (int i = 1; i <= rows; i++) {

for (int j = 1; j <= i; j++) {

cout << "*";

cout << endl;

return 0;

Expected Output:

**

***

****

*****

4. Create a class Person with attributes like name and age. Create an object
of the class and display the details using a method.

Program:

#include <iostream>

#include <string>

using namespace std;


class Person {

public:

string name;

int age;

void display() {

cout << "Name: " << name << endl;

cout << "Age: " << age << endl;

};

int main() {

Person person1;

person1.name = "John";

person1.age = 30;

person1.display();

return 0;

Expected Output:

Name: ABC

Age: 30

5.Write a C++ program to implement a class called Employee that has


private member variables for name, employee ID, and salary. Include
member functions to calculate and set salary based on employee
performance.

Program:

#include <iostream>

#include <string>
using namespace std;

class Employee {

private:

string name;

int id;

double salary;

public:

void setDetails(string empName, int empID, double empSalary) {

name = empName;

id = empID;

salary = empSalary;

void display() {

cout << "Name: " << name << endl;

cout << "ID: " << id << endl;

cout << "Salary: " << salary << endl;

};

int main() {

Employee emp1;

emp1.setDetails("Alice", 101, 5000);

emp1.display();

return 0;

Expected Output:
Name: Alice

ID: 101

Salary: 5000

7.Write an overloaded function findSquare() to calculate the square of a


number. One version should accept an integer, and another should accept
a floating-point number.

Code:

#include <iostream>

using namespace std;

double findSquare(int num) {

return num * num;

double findSquare(double num) {

return num * num;

int main() {

int intNum = 5;

double doubleNum = 4.5;

cout << "Square of " << intNum << " is " << findSquare(intNum) << endl;

cout << "Square of " << doubleNum << " is " << findSquare(doubleNum) <<
endl;

return 0;

Output:
Square of 5 is 25

Square of 4.5 is 20.25

8.Create a class BankAccount with attributes account_number,


account_holder_name, and balance. Use a parameterized constructor to
initialize the attributes and methods for depositing and withdrawing
money.

#include <iostream>

using namespace std;

class BankAccount {

public:

double balance;

BankAccount(double initBalance) {

balance = initBalance;

void deposit(double amount) {

balance += amount;

cout << "Deposited " << amount << ", Balance: " << balance << endl;

void withdraw(double amount) {

if (balance >= amount) {

balance -= amount;

cout << "Withdrew " << amount << ", Balance: " << balance << endl;

} else {

cout << "Insufficient funds" << endl;

}
}

};

int main() {

BankAccount account(1000);

account.deposit(200);

account.withdraw(500);

account.withdraw(1000); // Should show insufficient funds

return 0;

Output:

Deposited 200, Balance: 1200

Withdrew 500, Balance: 700

Insufficient funds

8.C++ program to demonstrate the execution of constructor and destructor

#include <iostream>

using namespace std;

class Demo {

public:

// Constructor

Demo() {

cout << "Constructor executed: Object created!" << endl;

// Destructor

~Demo() {

cout << "Destructor executed: Object destroyed!" << endl;


}

};

int main() {

cout << "Entering main function..." << endl;

// Creating an object of the Demo class

Demo obj;

cout << "Inside main function..." << endl;

// The destructor is automatically called when obj goes out of scope

cout << "Exiting main function..." << endl;

return 0;

OUTPUT

Entering main function...

Constructor executed: Object created!

Inside main function...

Exiting main function...

Destructor executed: Object destroyed!

9. Implement a class Employee that has private attributes like name, id,
and salary. Provide methods to set and get these attributes, ensuring
proper encapsulation.

#include <iostream>

using namespace std;

class Employee {

private:

string name;
int id;

double salary;

public:

// Setter methods (Encapsulation)

void setName(string empName) {

name = empName;

void setId(int empId) {

id = empId;

void setSalary(double empSalary) {

if (empSalary >= 0) { // Ensuring salary is non-negative

salary = empSalary;

} else {

cout << "Invalid salary! Setting salary to 0." << endl;

salary = 0;

// Getter methods

string getName() {

return name;

int getId() {

return id;

}
double getSalary() {

return salary;

// Display employee details

void displayEmployee() {

cout << "Employee Details:" << endl;

cout << "Name: " << name << endl;

cout << "ID: " << id << endl;

cout << "Salary: $" << salary << endl;

};

int main() {

Employee emp;

// Setting employee details

emp.setName("John Doe");

emp.setId(101);

emp.setSalary(50000);

// Displaying employee details

emp.displayEmployee();

return 0;

OUTPUT:

Employee Details:

Name: John Doe

ID: 101
Salary: $50000

10. Define a class Circle with attributes radius and methods to calculate
the area and circumference of the circle within the class.(Function within
the class)

#include <iostream>

using namespace std;

class Circle {

private:

double radius;

public:

// Constructor to initialize the radius

Circle(double r) {

radius = r;

// Method to calculate area (π * r^2)

double area() {

return 3.14159 * radius * radius;

// Method to calculate circumference (2 * π * r)

double circumference() {

return 2 * 3.14159 * radius;

// Method to display details

void display() {

cout << "Radius: " << radius << endl;


cout << "Area: " << area() << endl;

cout << "Circumference: " << circumference() << endl;

};

int main() {

// Creating a Circle object with radius 5

Circle c(5);

// Displaying details of the circle

c.display();

return 0;

OUTPUT:

Radius: 5

Area: 78.5397

Circumference: 31.4159

11. Create a base class Vehicle with attributes like make and model.
Derive a class Car that adds attributes like number_of_seats. Implement a
method in the derived class to display the complete details of the car.

#include <iostream>

using namespace std;

// Base class

class Vehicle {

protected:

string make;
string model

public:

// Constructor to initialize make and model

Vehicle(string mk, string mdl) {

make = mk;

model = mdl;

// Method to display vehicle details

void displayVehicleDetails() {

cout << "Make: " << make << endl;

cout << "Model: " << model << endl;

};

// Derived class

class Car : public Vehicle {

private:

int number_of_seats;

public:

// Constructor to initialize make, model, and number_of_seats

Car(string mk, string mdl, int seats) : Vehicle(mk, mdl) {

number_of_seats = seats;

// Method to display complete car details

void displayCarDetails() {

displayVehicleDetails(); // Call base class method


cout << "Number of Seats: " << number_of_seats << endl;

};

int main() {

// Creating a Car object

Car myCar("Toyota", "Camry", 5);

// Displaying car details

cout << "Car Details:\n";

myCar.displayCarDetails();

return 0;

OUTPUT:

Car Details:

Make: Toyota

Model: Camry

Number of Seats: 5

12. Design two base classes Student and Sports with respective
attributes. Create a derived class Result that inherits from both and
calculates the total score.

#include <iostream>

using namespace std;

// Base class 1: Student

class Student {

protected:
string name;

int rollNo;

int marks;

public:

// Constructor to initialize student details

Student(string n, int r, int m) {

name = n;

rollNo = r;

marks = m;

// Method to display student details

void displayStudentDetails() {

cout << "Name: " << name << endl;

cout << "Roll No: " << rollNo << endl;

cout << "Marks (Academic): " << marks << endl;

};

// Base class 2: Sports

class Sports {

protected:

int sportsScore;

public:

// Constructor to initialize sports score

Sports(int s) {

sportsScore = s;
}

// Method to display sports score

void displaySportsScore() {

cout << "Sports Score: " << sportsScore << endl;

};

// Derived class: Result (Inheriting from Student and Sports)

class Result : public Student, public Sports {

public:

// Constructor to initialize all attributes using base class constructors

Result(string n, int r, int m, int s) : Student(n, r, m), Sports(s) {}

// Method to display total score

void displayTotalScore() {

cout << "Total Score (Academic + Sports): " << (marks + sportsScore) <<
endl;

};

int main() {

// Creating a Result object

Result student1("John Doe", 101, 85, 15);

// Displaying details

cout << "Student Result Details:\n";

student1.displayStudentDetails();

student1.displaySportsScore();

student1.displayTotalScore();
return 0;

OUTPUT:

Student Result Details:

Name: John Doe

Roll No: 101

Marks (Academic): 85

Sports Score: 15

Total Score (Academic + Sports): 100

13.Write a program to create a base class Shape with a virtual method


calculateArea(). Derive classes Circle and Rectangle that implement the
calculateArea() method differently.

#include <iostream>

#include <cmath> // For M_PI (value of Pi)

using namespace std;

// Base class: Shape

class Shape {

public:

// Virtual method to calculate area

virtual void calculateArea() = 0; // Pure virtual function (Abstract Class)

};

// Derived class: Circle

class Circle : public Shape {

private:

double radius;
public:

// Constructor to initialize radius

Circle(double r) {

radius = r;

// Overriding calculateArea method

void calculateArea() override {

double area = M_PI * radius * radius;

cout << "Circle Area: " << area << endl;

};

// Derived class: Rectangle

class Rectangle : public Shape {

private:

double length, width;

public:

// Constructor to initialize length and width

Rectangle(double l, double w) {

length = l;

width = w;

// Overriding calculateArea method

void calculateArea() override {

double area = length * width;


cout << "Rectangle Area: " << area << endl;

};

int main() {

// Creating objects using pointers to the base class

Shape* shape1 = new Circle(5.0);

Shape* shape2 = new Rectangle(4.0, 6.0);

// Calling overridden methods dynamically

shape1->calculateArea();

shape2->calculateArea();

// Free memory

delete shape1;

delete shape2;

return 0;

OUTPUT:

Circle Area: 78.5398

Rectangle Area: 24

14.Create a class FileManager with methods to write data to a file and read
data from the file. Use objects to manage file operations.

#include <iostream>

#include <fstream> // For file handling

using namespace std;

class FileManager {
private:

string filename; // Stores file name

public:

// Constructor to initialize filename

FileManager(string fname) {

filename = fname;

// Method to write data to the file

void writeToFile(string data) {

ofstream outFile(filename, ios::app); // Open file in append mode

if (outFile.is_open()) {

outFile << data << endl;

cout << "Data written to file successfully!" << endl;

outFile.close(); // Close file

} else {

cout << "Error opening file for writing!" << endl;

// Method to read data from the file

void readFromFile() {

ifstream inFile(filename); // Open file for reading

string line;

if (inFile.is_open()) {

cout << "File Contents:" << endl;

while (getline(inFile, line)) { // Read file line by line


cout << line << endl;

inFile.close(); // Close file

} else {

cout << "Error opening file for reading!" << endl;

};

int main() {

// Creating FileManager object for "data.txt"

FileManager file("data.txt");

// Writing data to file

file.writeToFile("Hello, this is a test file.");

file.writeToFile("File handling in C++ is simple!");

// Reading data from file

file.readFromFile();

return 0;

OUTPUT:

Hello, this is a test file.

File handling in C++ is simple!

15. Write a program to divide two numbers. Handle the case where the
denominator is zero using a try-catch block.

#include <iostream>
using namespace std;

class Division {

public:

// Method to divide two numbers with exception handling

void divideNumbers(double numerator, double denominator) {

try {

if (denominator == 0) {

throw "Error: Division by zero is not allowed!";

double result = numerator / denominator;

cout << "Result: " << result << endl;

catch (const char* errorMsg) {

cout << errorMsg << endl;

};

int main() {

double num, denom;

// Taking user input

cout << "Enter numerator: ";

cin >> num;

cout << "Enter denominator: ";

cin >> denom;


// Creating object of Division class

Division div;

div.divideNumbers(num, denom); // Calling method to divide numbers

return 0;

OUTPUT:

Enter numerator: 10

Enter denominator: 2

Result: 5

You might also like