1st exam
1st exam
1st exam
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.
int main() {
int n, i = 1;
while (i <= n) {
cout << "Hello world "<<endl;
i++;
}
do while:
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;
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.
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
int main() {
int 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.
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;
}
int main() {
int num;
unsigned long long factorial = 1; // Using unsigned long long for larger
results
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++.
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;
}
#include <iostream>
using namespace std;
int main() {
int matrix1[2][2], matrix2[2][2], result[2][2] = {0};
// 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];
}
}
}
return 0;
}
class Vehicle {
protected:
string color;
int wheels;
string engine;
public:
// Common behaviors
void accelerate() {
cout << "The vehicle is accelerating." << endl;
}
void brake() {
cout << "The vehicle is braking." << endl;
}
void specificFeature() {
cout << "The car has a sunroof." << endl;
}
};
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");
return 0;
}
class Shape {
protected:
double area;
double perimeter;
public:
Shape() : area(0), perimeter(0) {}
void displayProperties() {
cout << "Area: " << area << ", Perimeter: " << perimeter << endl;
}
};
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();
}
};
public:
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:
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() {
myCircle.displayDetails();
cout << endl;
myRectangle.displayDetails();
cout << endl;
myTriangle.displayDetails();
return 0;
}
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;
}
};
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; }
};
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();
pt.displayInfo();
pt.calculateSalary();
return 0;
}
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;
}
};
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;
}
};
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.
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; }
};
int main() {
Mammal lion("Lion", 5, "Savanna");
Bird parrot("Parrot", 2, "Rainforest");
Reptile snake("Snake", 3, "Desert");
lion.eat();
lion.sleep();
lion.sound();
snake.eat();
snake.sleep();
snake.sound();
return 0;
}
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() ;
};
prof.teach();
prof.research();
prof.advise();
lect.teach();
lect.research();
lect.advise();
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.
class Student {
protected:
string name;
int rollNumber;
public:
Student(string n, int r) : name(n), rollNumber(r) {}
};
public:
Test(string n, int r, int m1, int m2) : Student(n, r), marks1(m1), marks2(m2)
{}
};
int main() {
Result res("John", 101, 85, 90);
res.displayResult();
return 0;
}
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;
}
};
public:
Book(string t, int i, string a) : LibraryItem(t, i), author(a) {}
void displayInfo() {
LibraryItem::displayInfo();
cout << "Author: " << author << endl;
}
};
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;
}
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;
}
};
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;
}
};
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;
}
};
void displayTeachingAssistantInfo() {
displayPersonInfo();
displayStudentInfo();
displayTeacherInfo();
}
};
int main() {
TeachingAssistant ta("John Doe", 25, 1001, "Computer Science", 2001,
"Programming");
ta.displayTeachingAssistantInfo();
return 0;
}
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;
}
};
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.
class Person {
protected:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
};
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;
}
};
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;
}
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;
}
};
int main() {
Car car("Red", "V8");
Truck truck("Blue", "Diesel");
Motorcycle motorcycle("Black", "Single-Cylinder");
car.displayInfo();
truck.displayInfo();
motorcycle.displayInfo();
return 0;
}
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;
}
};
void displaySmartphoneDetails() {
makeCall();
sendText();
showDeviceDetails();
}
};
int main() {
Smartphone mySmartphone(6.5, 10, 0.2, "15x7 cm");
mySmartphone.displaySmartphoneDetails();
return 0;
}
class Person {
protected:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {}
};
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;
}
};
public:
Athlete(string n, int a, string s) : Person(n, a), sport(s) {}
void playSport() {
cout << name << " is playing " << sport << "." << endl;
}
};
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.
class Rectangle {
private:
double length, width;
public:
// Constructor
Rectangle(double l, double w) {
length = l;
width = w;
}
// Destructor
~Rectangle() {
cout << "Rectangle object destroyed.\n";
}
int main() {
// Create a Rectangle object
Rectangle rect(7.0, 3.0);
return 0;
}
20. Write a program to demonstrate parameterized constructors to employees.
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;
}
int main() {
// Create Employee object using parameterized constructor
Employee emp1("John Doe", 101, 50000);
Employee emp2("Jane Smith", 102, 60000);
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.
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;
}
int main() {
Student student;
return 0;
}
class Complex {
private:
int real, imag;
public:
// Constructor to initialize complex number
Complex(int r = 0, int i = 0) : real(r), imag(i) {}
int main() {
Complex c1(3, 4), c2(1, 2), result;
return 0;
}
class Box {
private:
int length;
public:
Box(int l = 0) : length(l) {}
void display() {
cout << "Length: " << length << endl;
}
};
int main() {
Box box1(10), box2(15);
if (box1 == box2)
cout << "Both boxes are of equal length." << endl;
else
cout << "Boxes are not of equal length." << endl;
return 0;
}
class Student {
private:
string name;
int age;
public:
int main() {
Student 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.
class Shape {
public:
virtual double area() = 0;
virtual ~Shape() {}
};
public:
Circle(double r) : radius(r) {}
public:
Rectangle(double l, double w) : length(l), width(w) {}
int main() {
Shape* shape1 = new Circle(5.0);
Shape* shape2 = new Rectangle(4.0, 6.0);
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.
class Employee {
protected:
string name;
double baseSalary;
public:
void display() {
cout << "Employee Name: " << name << endl;
cout << "Base Salary: $" << baseSalary << endl;
}
virtual ~Employee() {}
};
public:
public:
int main() {
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.
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;
}
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.
class Person {
private:
string name;
int age;
public:
int main() {
try {
try {
return 0;
}