1st exam

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

1.

Write a program in c++ to print one statement for n times using while loop
and Write a program in c++ to print numbers from 1 to n using do while loop.

Ans:while: #include <iostream>


using namespace std;

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

cout << "Enter the value of n: ";


cin >> n;

while (i <= n) {
cout << "Hello world "<<endl;
i++;
}

cout << endl;


return 0;
}

do while:

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;

int i = 1; // Start from 1


do {
cout <<"Hello world "<<endl;
i++;
} while (i <= n); // Loop until i is greater than n

cout << endl;


return 0;
}

2. Write a program in c++ using if else like if age>=18 then he or she can drive
else cannot drive Write a program in c++ to check entered no is positive or
negative or zero using if else ladder.

Ans: 1st: #include <iostream>


using namespace std;

int main() {
int age;
cout << "Enter your age: ";
cin >> age;

if (age >= 18) {


cout << "You can drive." << endl;
} else {
cout << "You cannot drive." << endl;
}
return 0;
}

2nd: #include <iostream>


using namespace std;

int main() {
int num;

cout << "Enter a number: ";


cin >> num;

if (num > 0) {
cout << "The number is positive." << endl;
} else if (num < 0) {
cout << "The number is negative." << endl;
} else {
cout << "The number is zero." << endl;
}

return 0;
}

3.3. Using Switch case program to print months name in c++. And Write a program in
c++ to calculate factorial of given number.

Ans: 1st: #include <iostream>


using namespace std;

int main() {
int month;

cout << "Enter a number (1-12) to get the month name: ";
cin >> month;

switch (month) {
case 1:
cout << "January" << endl;
break;
case 2:
cout << "February" << endl;
break;
case 3:
cout << "March" << endl;
break;
case 4:
cout << "April" << endl;
break;
case 5:
cout << "May" << endl;
break;
case 6:
cout << "June" << endl;
break;
case 7:
cout << "July" << endl;
break;
case 8:
cout << "August" << endl;
break;
case 9:
cout << "September" << endl;
break;
case 10:
cout << "October" << endl;
break;
case 11:
cout << "November" << endl;
break;
case 12:
cout << "December" << endl;
break;
default:
cout << "Invalid input! Please enter a number between 1 and 12." <<
endl;
}

return 0;
}

2nd: #include <iostream>


using namespace std;

int main() {
int num;
unsigned long long factorial = 1; // Using unsigned long long for larger
results

cout << "Enter a non-negative integer: ";


cin >> num;

if (num < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
} else {
for (int i = 1; i <= num; ++i) {
factorial *= i; // Multiply current factorial by i
}
cout << "The factorial of " << num << " is: " << factorial << endl;
}

return 0;
}

4. Display value stored in array at even or odd index And .Fibbonaci series
program in c++.

Ans: 1st: #include <iostream>


using namespace std;

int main()
{ {
const int size = 10;
int arr[size] = {10, 21, 32, 43, 54, 65, 76, 87, 98, 109};
int choice;

cout << "Enter 1 to display values at even indices or 2 for odd indices: ";
cin >> choice;

if (choice == 1) {
cout << "Values at even indices: ";
for (int i = 0; i < size; i += 2) {
cout << arr[i] << " ";
}
cout << endl;
} else if (choice == 2) {
cout << "Values at odd indices: ";
for (int i = 1; i < size; i += 2)
cout << arr[i] << " ";
}
cout << endl;
} else {
cout << "Invalid choice! Please enter 1 or 2." << endl;
}

return 0;
}

2nd: #include <iostream>


using namespace std;

#include <iostream>
using namespace std;

int main() {
int matrix1[2][2], matrix2[2][2], result[2][2] = {0};

// Input for the first matrix


cout << "Enter elements of the first 2x2 matrix:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cin >> matrix1[i][j];
}
}

// Input for the second matrix


cout << "Enter elements of the second 2x2 matrix:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cin >> matrix2[i][j];
}
}

// Matrix multiplication
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}

// Output the result matrix


cout << "The resulting 2x2 matrix after multiplication is:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}

return 0;
}

6 Vehicle Hierarchy: Design a program to represent different types of vehicles


(Car, Truck, Motorcycle) that inherit common attributes (color, wheels, engine) and
behaviors (accelerate, brake) from a base Vehicle class.

Ans: #include <iostream>


#include <string>
using namespace std;

class Vehicle {
protected:
string color;
int wheels;
string engine;

public:

Vehicle(string c, int w, string e) : color(c), wheels(w), engine(e) {}

// Common behaviors
void accelerate() {
cout << "The vehicle is accelerating." << endl;
}

void brake() {
cout << "The vehicle is braking." << endl;
}

// Display vehicle information


void displayInfo() {
cout << "Color: " << color << ", Wheels: " << wheels << ", Engine: " <<
engine << endl;
}
};

class Car : public Vehicle {


public:
Car(string c, string e) : Vehicle(c, 4, e) {} // Cars typically have 4 wheels

void specificFeature() {
cout << "The car has a sunroof." << endl;
}
};

class Truck : public Vehicle {


public:
Truck(string c, string e) : Vehicle(c, 6, e) {} // Trucks typically have 6
wheels
void specificFeature() {
cout << "The truck can carry heavy loads." << endl;
}
};

class Motorcycle : public Vehicle {


public:
Motorcycle(string c, string e) : Vehicle(c, 2, e) {} // Motorcycles typically
have 2 wheels

void specificFeature() {
cout << "The motorcycle has a sporty design." << endl;
}
};

int main() {
// Create objects for each vehicle type
Car myCar("Red", "V6");
Truck myTruck("Blue", "Diesel");
Motorcycle myMotorcycle("Black", "Parallel-Twin");

// Display information and features for each vehicle


cout << "Car Details:" << endl;
myCar.displayInfo();
myCar.accelerate();
myCar.specificFeature();

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


myTruck.displayInfo();
myTruck.brake();
myTruck.specificFeature();

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


myMotorcycle.displayInfo();
myMotorcycle.accelerate();
myMotorcycle.specificFeature();

return 0;
}

7. Shape Inheritance: Create a program to model various shapes (Circle,


Rectangle, Triangle) that inherit properties (area, perimeter) and methods
(calculateArea, calculatePerimeter) from a base Shape class.

Ans: #include <iostream>


#include <cmath> // For mathematical operations
using namespace std;

class Shape {
protected:
double area;
double perimeter;

public:
Shape() : area(0), perimeter(0) {}

void displayProperties() {
cout << "Area: " << area << ", Perimeter: " << perimeter << endl;
}
};

class Circle : public Shape {


private:
double radius;

public:

Circle(double r) : radius(r) {}

void calculateArea() {
area = M_PI * radius * radius;
}

void calculatePerimeter() {
perimeter = 2 * M_PI * radius;
}

void displayDetails() {
cout << "Circle:" << endl;
calculateArea();
calculatePerimeter();
displayProperties();
}
};

class Rectangle : public Shape {


private:
double length, width;

public:

Rectangle(double l, double w) : length(l), width(w) {}

void calculateArea() {
area = length * width;
}

void calculatePerimeter() {
perimeter = 2 * (length + width);
}

void displayDetails() {
cout << "Rectangle:" << endl;
calculateArea();
calculatePerimeter();
displayProperties();
}
};
class Triangle : public Shape {
private:
double side1, side2, side3;

public:

Triangle(double a, double b, double c) : side1(a), side2(b), side3(c) {}

void calculateArea() {
double s = (side1 + side2 + side3) / 2;
area = sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

void calculatePerimeter() {
perimeter = side1 + side2 + side3;
}

void displayDetails() {
cout << "Triangle:" << endl;
calculateArea();
calculatePerimeter();
displayProperties();
}
};

int main() {

Circle myCircle(5); // Radius = 5


Rectangle myRectangle(4, 6); // Length = 4, Width = 6
Triangle myTriangle(3, 4, 5); // Sides = 3, 4, 5

myCircle.displayDetails();
cout << endl;

myRectangle.displayDetails();
cout << endl;

myTriangle.displayDetails();

return 0;
}

8. Employee Management: Develop a system to manage different types of employees


(Full-time, Part-time, Contractor) who inherit common attributes (name, ID,
department) and methods (calculateSalary, displayInfo) from a base Employee class.

Ans: #include <iostream>


#include <string>
using namespace std;

class Employee {
protected:
string name;
int id;
string department;
public:
Employee(string n, int i, string d) : name(n), id(i), department(d) {}
void calculateSalary() ;
void displayInfo() {
cout << "Name: " << name << "\nID: " << id << "\nDepartment: " <<
department << endl;
}
};

class FullTimeEmployee : public Employee {


private:
double salary;

public:
FullTimeEmployee(string n, int i, string d, double s) : Employee(n, i, d),
salary(s) {}
void calculateSalary() { cout << "Full-Time Employee Salary: $" << salary <<
endl; }
};

class PartTimeEmployee : public Employee {


private:
double hourlyRate;
int hoursWorked;

public:
PartTimeEmployee(string n, int i, string d, double hr, int hw) : Employee(n, i,
d), hourlyRate(hr), hoursWorked(hw) {}
void calculateSalary() { cout << "Part-Time Employee Salary: $" << hourlyRate
* hoursWorked << endl; }
};

int main() {
FullTimeEmployee ft("Alice", 101, "HR", 5000);
PartTimeEmployee pt("Bob", 102, "IT", 20, 80);

ft.displayInfo();
ft.calculateSalary();

cout << endl;

pt.displayInfo();
pt.calculateSalary();

return 0;
}

9. Bank Account Hierarchy: Design a program to represent various types of bank


accounts (Savings, Checking, Credit) that inherit common attributes (accountNumber,
balance) and behaviors (deposit, withdraw) from a base BankAccount class.

Ans: #include <iostream>


#include <string>
using namespace std;

class BankAccount {
protected:
string accountNumber;
double balance;

public:
BankAccount(string acc, double bal) : accountNumber(acc), balance(bal) {}
virtual void deposit(double amount) {
balance += amount;
cout << "Deposited $" << amount << ", New Balance: $" << balance << endl;
}
virtual void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
cout << "Withdrawn $" << amount << ", Remaining Balance: $" << balance
<< endl;
} else {
cout << "Insufficient funds!" << endl;
}
}
virtual void displayInfo() {
cout << "Account Number: " << accountNumber << "\nBalance: $" << balance <<
endl;
}
};

class SavingsAccount : public BankAccount {


private:
double interestRate;

public:
SavingsAccount(string acc, double bal, double rate) : BankAccount(acc, bal),
interestRate(rate) {}
void applyInterest() {
double interest = balance * (interestRate / 100);
balance += interest;
cout << "Interest Applied: $" << interest << ", New Balance: $" << balance
<< endl;
}
};

class CheckingAccount : public BankAccount {


public:
CheckingAccount(string acc, double bal) : BankAccount(acc, bal) {}
void withdraw(double amount) override {
if (amount <= balance) {
balance -= amount;
cout << "Withdrawn $" << amount << ", Remaining Balance: $" << balance
<< endl;
} else {
cout << "Overdraft not allowed!" << endl;
}
}
};

int main() {
SavingsAccount sa("12345", 1000, 5);
CheckingAccount ca("67890", 500);

sa.displayInfo();
sa.deposit(200);
sa.applyInterest();
cout << endl;

ca.displayInfo();
ca.withdraw(600);

return 0;
}

10.. Animal Kingdom: Create a program to simulate the animal kingdom, where
different species (Mammal, Bird, Reptile) inherit characteristics (name, age,
habitat) and behaviors (eat, sleep, sound) from a base Animal class.

Ans: #include <iostream>


#include <string>
using namespace std;

class Animal {
protected:
string name;
int age;
string habitat;

public:
Animal(string n, int a, string h) : name(n), age(a), habitat(h) {}
void eat() { cout << name << " is eating." << endl; }
void sleep() { cout << name << " is sleeping." << endl; }

};

class Mammal : public Animal {


public:
Mammal(string n, int a, string h) : Animal(n, a, h) {}
void sound() { cout << name << " says: Roar!" << endl; }
};

class Bird : public Animal {


public:
Bird(string n, int a, string h) : Animal(n, a, h) {}
void sound() { cout << name << " says: Chirp!" << endl; }
};

class Reptile : public Animal {


public:
Reptile(string n, int a, string h) : Animal(n, a, h) {}
void sound() { cout << name << " says: Hiss!" << endl; }
};

int main() {
Mammal lion("Lion", 5, "Savanna");
Bird parrot("Parrot", 2, "Rainforest");
Reptile snake("Snake", 3, "Desert");

lion.eat();
lion.sleep();
lion.sound();

cout << endl;


parrot.eat();
parrot.sleep();
parrot.sound();

cout << endl;

snake.eat();
snake.sleep();
snake.sound();

return 0;
}

11. University Hierarchy: Develop a system to manage different types of university


staff (Professor, Lecturer, TeachingAssistant) who inherit common attributes (name,
ID, department) and methods (teach, research, advise) from a base UniversityStaff
class.

Ans: #include <iostream>


#include <string>
using namespace std;

class UniversityStaff {
protected:
string name;
int id;
string department;

public:
UniversityStaff(string n, int i, string d) : name(n), id(i), department(d) {}
void teach() ;
void research() ;
void advise() ;
};

class Professor : public UniversityStaff {


public:
Professor(string n, int i, string d) : UniversityStaff(n, i, d) {}
void teach() { cout << name << " is teaching a lecture." << endl; }
void research() { cout << name << " is conducting research." << endl; }
void advise() { cout << name << " is advising students." << endl; }
};

class Lecturer : public UniversityStaff {


public:
Lecturer(string n, int i, string d) : UniversityStaff(n, i, d) {}
void teach() { cout << name << " is teaching a class." << endl; }
void research() { cout << name << " is preparing course material." << endl; }
void advise() { cout << name << " is helping students with assignments." <<
endl; }
};

class TeachingAssistant : public UniversityStaff {


public:
TeachingAssistant(string n, int i, string d) : UniversityStaff(n, i, d) {}
void teach() { cout << name << " is assisting in teaching." << endl; }
void research() { cout << name << " is assisting in research." << endl; }
void advise() { cout << name << " is mentoring students." << endl; }
};
int main() {
Professor prof("Dr. Smith", 101, "Physics");
Lecturer lect("Ms. Johnson", 102, "Mathematics");
TeachingAssistant ta("Mr. Brown", 103, "Computer Science");

prof.teach();
prof.research();
prof.advise();

cout << endl;

lect.teach();
lect.research();
lect.advise();

cout << endl;

ta.teach();
ta.research();
ta.advise();

return 0;
}

12. 12. Implement a program to create a student class from which derive test
class and from test class derive result class.Implement a class hierarchy for a
simple library system with a base class LibraryItem and derived classes Book and
Magazine.

Ans: 1st: #include <iostream>


#include <string>
using namespace std;

class Student {
protected:
string name;
int rollNumber;

public:
Student(string n, int r) : name(n), rollNumber(r) {}
};

class Test : public Student {


protected:
int marks1, marks2;

public:
Test(string n, int r, int m1, int m2) : Student(n, r), marks1(m1), marks2(m2)
{}
};

class Result : public Test {


public:
Result(string n, int r, int m1, int m2) : Test(n, r, m1, m2) {}
void displayResult() {
cout << "Name: " << name << "\nRoll Number: " << rollNumber << "\nTotal
Marks: " << marks1 + marks2 << endl;
}
};

int main() {
Result res("John", 101, 85, 90);
res.displayResult();

return 0;
}

2nd: #include <iostream>


#include <string>
using namespace std;

class LibraryItem {
protected:
string title;
int id;

public:
LibraryItem(string t, int i) : title(t), id(i) {}
void displayInfo() {
cout << "Title: " << title << "\nID: " << id << endl;
}
};

class Book : public LibraryItem {


private:
string author;

public:
Book(string t, int i, string a) : LibraryItem(t, i), author(a) {}
void displayInfo() {
LibraryItem::displayInfo();
cout << "Author: " << author << endl;
}
};

class Magazine : public LibraryItem {


private:
int issueNumber;

public:
Magazine(string t, int i, int issue) : LibraryItem(t, i), issueNumber(issue) {}
void displayInfo() {
LibraryItem::displayInfo();
cout << "Issue Number: " << issueNumber << endl;
}
};

int main() {
Book book("The Great Gatsby", 101, "F. Scott Fitzgerald");
Magazine magazine("National Geographic", 202, 45);

book.displayInfo();
cout << endl;
magazine.displayInfo();

return 0;
}

13. Implement a program to perform multiple inheritance for Educational Institute


database

Ans: #include <iostream>


#include <string>
using namespace std;

class Person {
protected:
string name;
int age;

public:
Person(string n, int a) : name(n), age(a) {}

void displayPersonInfo() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};

class Student : public Person {


protected:
int studentID;
string course;

public:
Student(string n, int a, int id, string c) : Person(n, a), studentID(id),
course(c) {}

void displayStudentInfo() {
cout << "Student ID: " << studentID << ", Course: " << course << endl;
}
};

class Teacher : public Person {


protected:
int employeeID;
string subject;

public:
Teacher(string n, int a, int empID, string subj) : Person(n, a),
employeeID(empID), subject(subj) {}

void displayTeacherInfo() {
cout << "Employee ID: " << employeeID << ", Subject: " << subject << endl;
}
};

class TeachingAssistant : public Student, public Teacher {


public:
TeachingAssistant(string n, int a, int id, string c, int empID, string subj)
: Person(n, a), Student(n, a, id, c), Teacher(n, a, empID, subj) {}

void displayTeachingAssistantInfo() {
displayPersonInfo();
displayStudentInfo();
displayTeacherInfo();
}
};

int main() {
TeachingAssistant ta("John Doe", 25, 1001, "Computer Science", 2001,
"Programming");
ta.displayTeachingAssistantInfo();
return 0;
}

14. Multiple Inheritance -> - Problem Statement: Create a program to model a


"FlyingCar" class that inherits attributes (wingspan, fuelCapacity) and methods
(fly, drive) from both "Car" and "Airplane" base classes.

Ans: #include <iostream>


using namespace std;

class Car {
protected:
double fuelCapacity;

public:
Car(double fuel) : fuelCapacity(fuel) {}

void drive() {
cout << "The car is driving. Fuel capacity: " << fuelCapacity << " liters."
<< endl;
}
};

class Airplane {
protected:
double wingspan;

public:
Airplane(double wing) : wingspan(wing) {}

void fly() {
cout << "The airplane is flying. Wingspan: " << wingspan << " meters." <<
endl;
}
};

class FlyingCar : public Car, public Airplane {


public:
FlyingCar(double fuel, double wing) : Car(fuel), Airplane(wing) {}

void showCapabilities() {
drive();
fly();
}
};

int main() {
FlyingCar myFlyingCar(50, 20);
myFlyingCar.showCapabilities();
return 0;
}
15. Multilevel Inheritance -> Problem Statement: Develop a system to
represent a "Professor" class that inherits properties (name, ID, department) and
behaviors (teach, research) from a base "Employee" class, which in turn inherits
attributes (name, age) from a base "Person" class.

Ans: #include <iostream>


#include <string>
using namespace std;

class Person {
protected:
string name;
int age;

public:
Person(string n, int a) : name(n), age(a) {}
};

class Employee : public Person {


protected:
int ID;
string department;

public:
Employee(string n, int a, int id, string dept) : Person(n, a), ID(id),
department(dept) {}

void work() {
cout << name << " is working in the " << department << " department." <<
endl;
}
};

class Professor : public Employee {


public:
Professor(string n, int a, int id, string dept) : Employee(n, a, id, dept) {}

void teach() {
cout << name << " is teaching." << endl;
}

void research() {
cout << name << " is conducting research." << endl;
}
};

int main() {
Professor prof("John Doe", 45, 101, "Computer Science");
prof.work();
prof.teach();
prof.research();
return 0;
}

16. Hierarchical Inheritance -> - Problem Statement: Design a program to


represent different types of "Vehicles" (Car, Truck, Motorcycle) that inherit
common attributes (color, wheels, engine) and behaviors (accelerate, brake) from a
base "Vehicle" class.

Ans: #include <iostream>


using namespace std;

class Vehicle {
protected:
string color;
int wheels;
string engine;

public:
Vehicle(string c, int w, string e) : color(c), wheels(w), engine(e) {}

void accelerate() {
cout << "The vehicle is accelerating." << endl;
}

void brake() {
cout << "The vehicle is braking." << endl;
}

void displayInfo() {
cout << "Color: " << color << ", Wheels: " << wheels << ", Engine: " <<
engine << endl;
}
};

class Car : public Vehicle {


public:
Car(string c, string e) : Vehicle(c, 4, e) {}
};

class Truck : public Vehicle {


public:
Truck(string c, string e) : Vehicle(c, 6, e) {}
};

class Motorcycle : public Vehicle {


public:
Motorcycle(string c, string e) : Vehicle(c, 2, e) {}
};

int main() {
Car car("Red", "V8");
Truck truck("Blue", "Diesel");
Motorcycle motorcycle("Black", "Single-Cylinder");

car.displayInfo();
truck.displayInfo();
motorcycle.displayInfo();

return 0;
}

17. Hybrid Inheritance -> - Problem Statement: Create a program to model a


"Smartphone" class that inherits attributes (screenSize, batteryLife) and methods
(makeCall, sendText) from both "Phone" and "Computer" base classes, using multiple
inheritance, and also inherits attributes (weight, dimensions) from a base "Device"
class, using single inheritance.

Ans: #include <iostream>


using namespace std;

class Device {
protected:
double weight;
string dimensions;

public:
Device(double w, string d) : weight(w), dimensions(d) {}

void showDeviceDetails() {
cout << "Weight: " << weight << " kg, Dimensions: " << dimensions << endl;
}
};

class Phone {
protected:
double screenSize;

public:
Phone(double screen) : screenSize(screen) {}

void makeCall() {
cout << "Making a call from the phone." << endl;
}
};

class Computer {
protected:
double batteryLife;

public:
Computer(double battery) : batteryLife(battery) {}

void sendText() {
cout << "Sending a text using the computer's software." << endl;
}
};

class Smartphone : public Phone, public Computer, public Device {


public:
Smartphone(double screen, double battery, double weight, string dimensions)
: Phone(screen), Computer(battery), Device(weight, dimensions) {}

void displaySmartphoneDetails() {
makeCall();
sendText();
showDeviceDetails();
}
};

int main() {
Smartphone mySmartphone(6.5, 10, 0.2, "15x7 cm");
mySmartphone.displaySmartphoneDetails();
return 0;
}

18. 18. Multipath Inheritance -> - Problem Statement: Develop a system to


represent a "StudentAthlete" class that inherits properties (name, ID, GPA) and
behaviors (study, playSport) from both "Student" and "Athlete" base classes, which
both inherit attributes (name, age) from a base "Person" class.

Ans: #include <iostream>


#include <string>
using namespace std;

class Person {
protected:
string name;
int age;

public:
Person(string n, int a) : name(n), age(a) {}
};

class Student : public Person {


protected:
int ID;
double GPA;

public:
Student(string n, int a, int id, double gpa) : Person(n, a), ID(id), GPA(gpa)
{}

void study() {
cout << name << " is studying. GPA: " << GPA << endl;
}
};

class Athlete : public Person {


protected:
string sport;

public:
Athlete(string n, int a, string s) : Person(n, a), sport(s) {}

void playSport() {
cout << name << " is playing " << sport << "." << endl;
}
};

class StudentAthlete : public Student, public Athlete {


public:
StudentAthlete(string n, int a, int id, double gpa, string s)
: Student(n, a, id, gpa), Athlete(n, a, s) {}

void showDetails() {
study();
playSport();
}
};
int main() {
StudentAthlete sa("Alice", 20, 1001, 3.8, "Soccer");
sa.showDetails();
return 0;
}

19. Implement a Rectangle class with attributes for length and width. Include
constructors, a destructor, and member functions to calculate the area and
perimeter.

Ans: #include <iostream>


using namespace std;

class Rectangle {
private:
double length, width;

public:
// Constructor
Rectangle(double l, double w) {
length = l;
width = w;
}

// Destructor
~Rectangle() {
cout << "Rectangle object destroyed.\n";
}

// Member function to calculate area


double calculateArea() {
return length * width;
}

// Member function to calculate perimeter


double calculatePerimeter() {
return 2 * (length + width);
}

// Member function to display rectangle details


void display() {
cout << "Length: " << length << ", Width: " << width << endl;
cout << "Area: " << calculateArea() << endl;
cout << "Perimeter: " << calculatePerimeter() << endl;
}
};

int main() {
// Create a Rectangle object
Rectangle rect(7.0, 3.0);

// Display rectangle details


rect.display();

return 0;
}
20. Write a program to demonstrate parameterized constructors to employees.

Ans: #include <iostream>


#include <string>
using namespace std;

class Employee {
private:
string name;
int id;
double salary;

public:
// Parameterized Constructor
Employee(string n, int i, double s) {
name = n;
id = i;
salary = s;
}

// Function to display employee details


void display() {
cout << "Employee ID: " << id << endl;
cout << "Name: " << name << endl;
cout << "Salary: $" << salary << endl;
}
};

int main() {
// Create Employee object using parameterized constructor
Employee emp1("John Doe", 101, 50000);
Employee emp2("Jane Smith", 102, 60000);

// Display employee details


cout << "Employee 1 details:\n";
emp1.display();
cout << "\nEmployee 2 details:\n";
emp2.display();

return 0;
}
21. 21. Implement a Program to find out areas of different shapes using
function overloading.
ans:

#include <iostream>
using namespace std;

class Area {
public:
double calculate_area(double radius) {
return 3.14 * radius * radius;
}
double calculate_area(double length, double width) {
return length * width;
}
};

int main() {
Area shape;
double radius = 5.0;
cout << "Area of circle with radius " << radius << ": " <<
shape.calculate_area(radius) << endl;
double length = 5.0, width = 10.0;
cout << "Area of rectangle with length " << length << " and width " << width <<
": " << shape.calculate_area(length, width) << endl;

return 0;
}

25.

26.

27.Implement a program to define a Student class with attributes like name, roll
number, and marks. Implement member functions to input and display student details.

ANs: #include <iostream>


#include <string>
using namespace std;

class Student {
private:
string name;
int rollNumber;
float marks;

public:
// Member function to input student details
void inputDetails() {
cout << "Enter student name: ";
getline(cin, name);
cout << "Enter roll number: ";
cin >> rollNumber;
cout << "Enter marks: ";
cin >> marks;
}

// Member function to display student details


void displayDetails() {
cout << "Student Name: " << name << endl;
cout << "Roll Number: " << rollNumber << endl;
cout << "Marks: " << marks << endl;
}
};

int main() {
Student student;

student.inputDetails(); // Input student details


student.displayDetails(); // Display student details

return 0;
}

28. Implement a program to overload unary and binary operators.


Ans: #include <iostream>
using namespace std;

class Complex {
private:
int real, imag;

public:
// Constructor to initialize complex number
Complex(int r = 0, int i = 0) : real(r), imag(i) {}

// Overloading unary operator (negation)


Complex operator-() {
return Complex(-real, -imag);
}

// Overloading binary operator (+)


Complex operator+(const Complex& c) {
return Complex(real + c.real, imag + c.imag);
}

// Function to display complex number


void display() {
cout << real << " + " << imag << "i" << endl;
}
};

int main() {
Complex c1(3, 4), c2(1, 2), result;

cout << "Complex number 1: ";


c1.display();

cout << "Complex number 2: ";


c2.display();

// Using overloaded binary operator


result = c1 + c2;
cout << "Result of addition: ";
result.display();

// Using overloaded unary operator


result = -c1;
cout << "Result of negation: ";
result.display();

return 0;
}

29. Implement a program to overload relational operators.

Ans: #include <iostream>


using namespace std;

class Box {
private:
int length;
public:
Box(int l = 0) : length(l) {}

bool operator==(const Box& b) {


return length == b.length;
}

bool operator>(const Box& b) {


return length > b.length;
}

void display() {
cout << "Length: " << length << endl;
}
};

int main() {
Box box1(10), box2(15);

cout << "Box 1: ";


box1.display();

cout << "Box 2: ";


box2.display();

if (box1 == box2)
cout << "Both boxes are of equal length." << endl;
else
cout << "Boxes are not of equal length." << endl;

if (box1 > box2)


cout << "Box 1 is larger than Box 2." << endl;
else
cout << "Box 1 is smaller than Box 2." << endl;

return 0;
}

30. Program to overload insertion and extraction operators using C++.

Ans: #include <iostream>


using namespace std;

class Student {
private:
string name;
int age;

public:

friend istream& operator>>(istream& in, Student& s) {


cout << "Enter name: ";
in >> s.name;
cout << "Enter age: ";
in >> s.age;
return in;
}

friend ostream& operator<<(ostream& out, const Student& s) {


out << "Name: " << s.name << ", Age: " << s.age << endl;
return out;
}
};

int main() {
Student student;

cin >> student;

cout << student;

return 0;
}

31.. Implement a program to create a base class Shape with a virtual function
area(). Derive two classes Circle and Rectangle from Shape and implement the area()
function in each derived class.

Ans: #include <iostream>


#include <cmath>
using namespace std;

class Shape {
public:
virtual double area() = 0;
virtual ~Shape() {}
};

class Circle : public Shape {


private:
double radius;

public:
Circle(double r) : radius(r) {}

double area() override {


return M_PI * radius * radius;
}
};

class Rectangle : public Shape {


private:
double length, width;

public:
Rectangle(double l, double w) : length(l), width(w) {}

double area() override {


return length * width;
}
};

int main() {
Shape* shape1 = new Circle(5.0);
Shape* shape2 = new Rectangle(4.0, 6.0);

cout << "Area of Circle: " << shape1->area() << endl;


cout << "Area of Rectangle: " << shape2->area() << endl;

delete shape1;
delete shape2;

return 0;
}

32. Implement a program to creat a base class Employee with a virtual function
calculateSalary(). Derive two classes FullTimeEmployee and PartTimeEmployee and
implement the calculateSalary() function in each derived class.

Ans: #include <iostream>


#include <string>
using namespace std;

class Employee {
protected:
string name;
double baseSalary;

public:

Employee(string n, double b) : name(n), baseSalary(b) {}

virtual double calculateSalary() = 0;

void display() {
cout << "Employee Name: " << name << endl;
cout << "Base Salary: $" << baseSalary << endl;
}

virtual ~Employee() {}
};

class FullTimeEmployee : public Employee {


private:
double annualBonus;

public:

FullTimeEmployee(string n, double b, double bonus) : Employee(n, b),


annualBonus(bonus) {}

double calculateSalary() override {


return baseSalary + annualBonus;
}
};

class PartTimeEmployee : public Employee {


private:
double hourlyRate;
int hoursWorked;

public:

PartTimeEmployee(string n, double b, double rate, int hours) : Employee(n, b),


hourlyRate(rate), hoursWorked(hours) {}

double calculateSalary() override {


return baseSalary + (hourlyRate * hoursWorked);
}
};

int main() {

FullTimeEmployee fullTimeEmp("John Doe", 50000, 5000);

PartTimeEmployee partTimeEmp("Jane Smith", 20000, 25, 120);

cout << "Full-Time Employee Details:" << endl;


fullTimeEmp.display();
cout << "Total Salary: $" << fullTimeEmp.calculateSalary() << endl;

cout << endl;

cout << "Part-Time Employee Details:" << endl;


partTimeEmp.display();
cout << "Total Salary: $" << partTimeEmp.calculateSalary() << endl;

return 0;
}

33. Implement a program to write user input data to a file name (abc.txt) and then
read it back from the file.

Ans: #include <iostream>


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

int main() {
string userInput;

ofstream outFile("abc.txt");

if (!outFile) {
cout << "Error opening file for writing." << endl;
return 1;
}

cout << "Enter data to write to the file (type 'exit' to stop):" << endl;
while (true) {
getline(cin, userInput);
if (userInput == "exit") break;
outFile << userInput << endl;
}

outFile.close();

ifstream inFile("abc.txt");

if (!inFile) {
cout << "Error opening file for reading." << endl;
return 1;
}

cout << "\nData read from the file:" << endl;


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

inFile.close();

return 0;
}

34. Implement a program that uses try, catch, and throw to handle division by zero
exceptions. Create a custom exception class InvalidAgeException and use it to
validate the age input for a Person class.

Ans: #include <iostream>


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

class InvalidAgeException : public exception {


public:
const char* what() const noexcept override {
return "Invalid age input! Age cannot be negative or zero.";
}
};

class Person {
private:
string name;
int age;

public:

Person(string n, int a) : name(n), age(a) {


if (age <= 0) {
throw InvalidAgeException();
}
}
void displayDetails() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};

double divide(int numerator, int denominator) {


if (denominator == 0) {
throw runtime_error("Division by zero error!");
}
return static_cast<double>(numerator) / denominator;
}

int main() {
try {

Person person1("John", 30);


person1.displayDetails();

Person person2("Alice", -5);

} catch (const InvalidAgeException& e) {


cout << "Error: " << e.what() << endl;
}

try {

cout << "Result of division: " << divide(10, 2) << endl;


cout << "Result of division: " << divide(10, 0) << endl;
} catch (const runtime_error& e) {
cout << "Error: " << e.what() << endl;
}

return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy