KEMBAR78
AnshumanLab File C | PDF | Pointer (Computer Programming) | Namespace
0% found this document useful (0 votes)
51 views44 pages

AnshumanLab File C

The document outlines a series of programming exercises and algorithms in C++ over six weeks, covering basic concepts such as 'Hello World', swapping numbers, creating a calculator, and checking number equality. It progresses to more complex topics including pattern printing, recursive functions, class definitions for student and employee management systems, and static member functions. Each section includes code snippets, algorithms, and expected outputs for the exercises.

Uploaded by

anusingh2252
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)
51 views44 pages

AnshumanLab File C

The document outlines a series of programming exercises and algorithms in C++ over six weeks, covering basic concepts such as 'Hello World', swapping numbers, creating a calculator, and checking number equality. It progresses to more complex topics including pattern printing, recursive functions, class definitions for student and employee management systems, and static member functions. Each section includes code snippets, algorithms, and expected outputs for the exercises.

Uploaded by

anusingh2252
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/ 44

WEEK:1

PROGRAM 1:- Write a simple “hello world” program.

CODE:- #include <iostream> Using

namespace std; int main() { std::cout<<

"Hello, World!" << std:endl; return 0;

Algorithm: Print Hello, World!

1. Start

2. Display "Hello, World!"

3. End OUTPUT:-

PROGRAM:-2 Write a program to swap two number without using third value.
CODE:- #include <iostream>

int main() {

int a, b;
// Input two numbers std::cout <<

"Enter two numbers: "; std::cin >> a >> b;

// Swapping without a third variable a=a

+ b; b = a - b; a = a - b;

// Output the swapped values std::cout << "After swapping: a = " << a << ", b =

" << b << std::endl;

return 0;

Algorithm:-

1. Input two numbers a and b

2. Perform swapping using arithmetic operations:

o a=a+b

o b=a-bo

a=a-b

3. Output the swapped values of a and b

4. End

OUTPUT:-
WEEK 2:LAB
Problem:-1
Create a basic calculator using arithmetic and logical operators.
Algorithm:

1. Start

2. Input two numbers num1 and num2

3. Input an operator (+, -, *, /)

4. Check the operator using logical conditions: o If operator is +, compute num1 + num2 o
If operator is -, compute num1 - num2 o If operator is *, compute num1 * num2 o If
operator is /, check if num2 is not zero:
▪ If num2 ≠ 0, compute num1 / num2

▪ Otherwise, print "Error: Division by zero" o If the operator is invalid,


print "Invalid operator"

5. Display the result

6. Stop

C++ program:

#include <iostream>

int main() { double num1,


num2; char op;

std::cout << "Enter first number: "; std::cin >> num1;

std::cout << "Enter an operator (+, -, *, /): "; std::cin >> op;
std::cout << "Enter second number: "; std::cin >> num2;

if (op == '+')

std::cout << "Result: " << num1 + num2 << std::endl; else if (op == '-')
std::cout << "Result: " << num1 - num2 << std::endl; else if (op == '*')
std::cout << "Result: " << num1 * num2 << std::endl; else if (op == '/')
{ if (num2 != 0)
std::cout << "Result: " << num1 / num2 << std::endl; else

std::cout << "Error: Division by zero is not allowed!" << std::endl;

} else {

std::cout << "Invalid operator!" << std::endl;

return 0;

}
OUTPUT:-

PROBLEM:2
Write a C++ program that checks whether the two numbers entered by
the user are equal or not.
Algorithm:

1. Start
2. Input two numbers num1 and num2

3. Compare the two numbers using the == operator: o If num1 == num2, print "Both
numbers are equal" o Otherwise, print "Numbers are not equal"

4. Stop

C++ program:
#include <iostream>

int main() { int


num1, num2;

std::cout << "Enter first number: "; std::cin >>


num1;

std::cout << "Enter second number: "; std::cin >>


num2;

if (num1 == num2) std::cout << "Both numbers are equal."


<< std::endl;
else

std::cout << "Numbers are not equal." << std::endl;

return 0;

}
OUTPUT:-

PROBLEM:3
Write a C++ program to find the reverse of a number.
Algorithm:
Algorithm:

1. Start

2. Input an integer num.

3. Initialize reversed = 0

4. Repeat the following steps until num becomes 0:

o Extract the last digit using remainder = num % 10 o Append the digit to
reversed using reversed = reversed *
10 + remainder o Remove the last digit from num using num = num /
10

5. Print the reversed number

6. Stop

C++ PROGRAM:-
#include <iostream> int main() {
int num, reversed = 0, remainder; std::cout
<< "Enter a number: "; std::cin >> num;
while (num != 0) { remainder = num % 10;
reversed = reversed * 10 + remainder; num /= 10;
}

std::cout << "Reversed Number: " << reversed << std::endl; return 0;
}

WEEK:-3

PROBLEM:-1
Pattern Printing Using Loops (e.g., pyramid, diamond patterns).
ALGORITHM:-
1. Start

2. Input the number of rows (rows)

3. Loop from i = 1 to rows (for each row):


o Print (rows - i) spaces o Print (2 * i -
1) asterisks (*)

o Move to the next line

4. Stop

C++ PROGRAM:-
PYRAMID PATTERN:-
#include <iostream>
int main() { int
rows;
std::cout << "Enter number of rows: "; std::cin >>
rows;
for (int i = 1; i <= rows; i++) { for
(int j = 1; j <= rows - i; j++)
std::cout << " "; for (int k = 1; k <=
2 * i - 1; k++) std::cout << "*";
std::cout << std::endl;
}

return 0;

OUTPUT:-

DIAMOND PATTERN:-

#include <iostream>

int main() {

int n;
std::cout << "Enter number of rows for half diamond: ";

std::cin >> n;

// Upper part for (int i = 1; i <=

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

j++) std::cout << " "; for

(int k = 1; k <= 2 * i - 1; k++)

std::cout << "*"; std::cout <<

std::endl;

// Lower part for (int i = n - 1; i

>= 1; i--) { for (int j = 1; j <= n -

i; j++) std::cout << " ";

for (int k = 1; k <= 2 * i - 1; k++)

std::cout << "*"; std::cout <<

std::endl;

return 0;

OUTPUT:-
WEEK-4
Algorithm: Recursive Factorial Calculator
Step 1: Start

Step 2: Input a number

• Prompt the user to enter an integer n.

Step 3: Check if the number is valid

• If n < 0, display an error message: "Factorial is not defined for negative


numbers."

• Else, proceed to the next step.

Step 4: Call the recursive factorial function

• Define a function factorial(n):

o If n == 0 or n == 1, return 1 (base case).

o Otherwise, return n * factorial(n - 1) (recursive step).

Step 5: Display the result


• Output the result of factorial(n).
Step 6: End

PROGRAM CODE-#include<iostream>
using namespace std;
class factorialcalculator{
public:
//recusive function to calculate factorial
int factorial(int n){
if(n==0||n==1)
return 1; return n*
factorial(n-1);

}
void displayfactorial(int number){ cout<<"factorial

of"<<number<<"is:"<<factorial(number)<<endl;

}
};
int main(){
factorialcalculator fc; int
num;
cout<<"enter a number:";
cin>>num;
fc.displayfactorial(num);
return 0;
}

WEEK:-5

1.Define a class Student with attributes like name, ID, and grades.
PROGRAM CODE:-
#include <iostream>
#include <string>
#include <vector>

class Student {
private:
std::string name;
int ID;
std::vector<float> grades;

public:
// Constructor
Student(std::string studentName, int studentID, std::vector<float>
studentGrades) { name = studentName; ID = studentID;
grades = studentGrades;
}

// Setters
void setName(std::string studentName) {
name = studentName;
}

void setID(int studentID) {


ID = studentID;
}

void setGrades(std::vector<float>
ALGORITHM:-

1. Start

2. Define a class named Student.

3. Inside the class:


o Declare a string variable name for the student’s name.
o Declare an integer variable ID for the student’s ID.
o Declare a vector of floats grades to store the student's grades.

4. Define a constructor to initialize the above attributes.

5. Define setter methods to update name, ID, and grades.

6. Define getter methods to retrieve name, ID, and grades.

7. (Optional) Define a method to calculate and return the average grade.

8. End

2. Employee Management System Using Classes and


Objects.
PROGRAM CODE:-
#include <iostream>
#include <string> using
namespace std;

class Employee { private:


int id;
string name;
string designation;
float salary;
public:
// Function to input employee details
void getData() { cout << "Enter
Employee ID: ";
cin >> id;
cin.ignore(); // to avoid input buffer issues
cout << "Enter Name: "; getline(cin,
name); cout << "Enter Designation: ";
getline(cin, designation); cout << "Enter
Monthly Salary: ";
cin >> salary;
}

// Function to display employee details void displayData() {


cout << "\n--- Employee Details ---\n"; cout << "ID: " << id <<
endl; cout << "Name: " << name << endl; cout <<
"Designation: " << designation << endl; cout << "Monthly
Salary: $" << salary << endl; cout << "Annual Salary: $" <<
calculateAnnualSalary() << endl;
}

// Function to calculate annual salary


float calculateAnnualSalary() {
return salary * 12;
}
};

int main() {
int n;
cout << "Enter number of employees: ";
cin >> n;

Employee emp[n]; // Array of employee objects

// Input data for all employees


for (int i = 0; i < n; i++) {
cout << "\nEnter details for Employee " << i + 1 << ":\n";
emp[i].getData();
}

// Display data for all employees


for (int i = 0; i < n; i++) {
emp[i].displayData();
}

return 0;
}
ALGORITHM:-
1 .Start.
2.Define class Employee with private data members: id, name, designation, salary.
3.Define public methods:
• getData() – to input employee details.
• displayData() – to show employee details.
• calculateAnnualSalary() – to calculate and return annual salary.
4.In main(), create objects of Employee class.
5.Call functions to accept and display employee data.
6.End.

WEEK:-6 LAB

1. Implement a class with static member functions and


data members.
ALOGRITHM:-
1. Start
2. Define a class Employee
• Declare a private data member id to store individual employee
ID.
• Declare a static data member count to track the number of
employees.
3. Define a Constructor • Accept an empId as a parameter.
• Assign empId to id.
• Increment the static member count by 1.
4. Define a Static Member Function getCount()
• Return the value of count.
• This function can be called without creating an object.
5. Define a Regular Member Function display()
• Display the id of the employee.
6. In the main() Function
• Create multiple Employee objects using the constructor.
• Call display() on each object to show the employee ID.
• Call the static function Employee::getCount() to display the total
number of employees.
7. End
PROGRAM CODE:-
#include <iostream> using
namespace std; class
Employee { private: int
id;
static int count; // Static data member

public:
// Constructor to initialize employee and increment count
Employee(int empId) { id = empId; count++;
}

// Static member function


static int getCount() {
return count;
}

// Display employee ID void display()


{ cout << "Employee ID: " << id <<
endl;
}
};

// Initialize static member


int Employee::count = 0;

int main() {
Employee e1(101);
Employee e2(102);
Employee e3(103);
e1.display();
e2.display();
e3.display(); // Call
static function cout <<
"Total Employees: " <<
Employee::getCount() <<
endl;

return 0;
}
OUTPUT:-

2. Library Management System Using Static Data


Members.
ALGORITHM:-
1. Start
2. Declare a class Library with:
a. Data members: bookName, bookID,
bookEdition, bookAuthor
b. Static data member: totalBooks
c. Member functions: addBook(), displayBook(),
showTotalBooks()
3. In main():
a. Ask user to enter the number of books n
b. Create an array of Library objects of size n
4. For each book:
a. Call addBook() to input book details
b. Increment totalBooks
5. For each book:
a. Call displayBook() to show entered details 6.
Call showTotalBooks() to display total number of
books
7. End
PROGRAM CODE:-
#include <iostream>
#include <sstream> // For stringstream to
convert strings to int using namespace std;

class Library { private:


string bookName; int bookID; string
bookEdition; string bookAuthor; static int
totalBooks; // Static member to track total
number of books public:
// Function to input book details
void addBook() { string input;
cout << "\nEnter Complete Book Name: ";
getline(cin, bookName); cout << "Enter Book ID:
"; getline(cin, input); stringstream(input) >>
bookID; // Convert string to int safely.
cout << "Enter Book Edition: ";
getline(cin, bookEdition); cout
<< "Enter Book Author: ";
getline(cin, bookAuthor);
totalBooks++;
}
// Function to display book details void
displayBook() const { cout << "\n--- Book Details -
--" << endl; cout << "Book Name : " <<
bookName << endl; cout << "Book ID : " <<
bookID << endl; cout << "Book Edition : " <<
bookEdition << endl; cout << "Book Author : " <<
bookAuthor << endl;
}
// Static function to display total number of
books.
static void showTotalBooks() {
cout << "\nTotal Books in Library: " << totalBooks
<< endl;
}
};
// Definition of static member int
Library::totalBooks = 0; int main() { int n; string
input; cout << "Enter the number of books to
add: "; getline(cin, input); stringstream(input)
>> n; Library* books = new Library[n]; for (int i
= 0; i < n; ++i) { cout << "\n--- Entering details for
Book " << i + 1
<< " ---" << endl; books[i].addBook();
} for (int i = 0; i < n; ++i)
{

books[i].displayBook();
}
Library::showTotalBooks(); delete[]
books;
return 0;
}
OUTPUT:-

WEEK:-7
1.Create a class for handling bank accounts with
constructors and destructors.
ANSWER:-
Step 1: Start
Step 2: Define the BankAccount class
• Declare private data members: o accountHolder (string) o
accountNumber (int)

o balance (double)
Step 3: Create a Constructor
• Accept parameters: name, account number, and initial balance
• Initialize the data members with provided values
• Print message indicating account creation
Step 4: Create a Destructor
• Display a message indicating the account is closed
Step 5: Define deposit(amount) method
• If amount > 0, add it to balance
• Print updated balance
• Else, print an error message
Step 6: Define withdraw(amount) method
• If amount > 0 and amount <= balance, subtract it from balance
• Print updated balance
• Else, print an error message
Step 7: Define display() method
• Print account holder name, account number, and current balance
Step 8: In main() function
• Create an object of BankAccount using constructor with sample data
• Call display() to show initial details
• Call deposit() to add funds
• Call withdraw() to remove funds
• Call display() again to show updated details
Step 9: End
PROGAM CODE:-
#include <iostream>
#include <string> using
namespace std;

class BankAccount { private:


string accountHolder;
int accountNumber;
double balance;

public:
// Constructor
BankAccount(string name, int accNum, double initialBalance) {
accountHolder = name;

accountNumber = accNum;
balance = initialBalance;
cout << "Account created for " << accountHolder << " with balance $" <<
balance << endl;
}

// Destructor ~BankAccount() { cout << "Account of " <<


accountHolder << " is now closed." << endl;
}
// Method to deposit money
void deposit(double amount) {
if (amount > 0) { balance += amount; cout << "Deposited $"
<< amount << ". New balance: $" << balance << endl;
} else {
cout << "Invalid deposit amount!" << endl;
}
}

// Method to withdraw money void


withdraw(double amount) { if (amount
> 0 && amount <= balance) { balance
-= amount;

cout << "Withdrew $" << amount << ". Remaining balance: $" << balance
<< endl;
} else {
cout << "Invalid or insufficient funds!" << endl;
}
}

// Display account details


void display() {
cout << "Account Holder: " << accountHolder << endl;
cout << "Account Number: " << accountNumber << endl;
cout << "Balance: $" << balance << endl;
}
};

// Main function to test the class int


main() {
BankAccount myAccount("John Doe", 123456, 1000.0);

myAccount.display();
myAccount.deposit(500);
myAccount.withdraw(200);
myAccount.display();

return 0;
}
OUTPUT:-

2. Constructor Overloading Example.


ALGORITHM:-
Step 1: Start
Step 2: Define the Student class
• Declare private data members:
o name (string)
o age (int)

Step 3: Define constructors

➤ Default Constructor
• Set name = "Unknown"
• Set age = 0
• Print message: "Default constructor called."

➤ Constructor with one parameter (name)


• Set name = passed value
• Set age = 0
• Print message: "Constructor with name only called."

➤ Constructor with two parameters (name, age)


• Set name = passed name
• Set age = passed age
• Print message: "Constructor with name and age called."

Step 4: Define display() method


• Print name and age

Step 5: In the main() function


• Create object s1 using default constructor
• Create object s2 using constructor with 1 parameter
• Create object s3 using constructor with 2 parameters
• Call display() on all objects to show their data

Step 6: End

PROGRAM CODE:-

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

class Student { private:

string name;
int age;

public:
// Default constructor
Student() {
name = "Unknown";
age = 0;
cout << "Default constructor called." << endl;
}
// Constructor with one parameter
Student(string n) { name = n;
age = 0;
cout << "Constructor with name only called." << endl;
}

// Constructor with two parameters


Student(string n, int a) { name =
n; age = a;
cout << "Constructor with name and age called." << endl;
}

// Method to display student details


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

// Main function to test constructor overloading int


main() {
Student s1; // Calls default constructor
Student s2("Alice"); // Calls constructor with 1 argument
Student s3("Bob", 20); // Calls constructor with 2 arguments

s1.display();
s2.display(); s3.display();
return 0;
}
OUTPUT:-

WEEK:-8
1.Matrix Operations Using Classes (Addition, Subtraction,
Multiplication)
ANSWER:-
#include <iostream> using

namespace std;

class Matrix { private:

int mat[10][10]; int

rows, cols;

public:

// Constructor

Matrix(int r = 0, int c = 0) {

rows = r; cols = c;

}
// Function to input matrix elements void input() { cout << "Enter

elements of matrix (" << rows << "x" << cols << "):\n"; for (int

i = 0; i < rows; ++i) for (int j = 0; j < cols; ++j) cin >>

mat[i][j];

// Function to display matrix void display() const {

cout << "Matrix (" << rows << "x" << cols << "):\n";

for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols;

++j) cout << mat[i][j] << " "; cout << endl;

// Overload + operator for matrix addition

Matrix operator+(const Matrix& m) { Matrix result(rows, cols);

if (rows != m.rows || cols != m.cols) { cout << "Addition not

possible (dimension mismatch)!" << endl;

return result;

for (int i = 0; i < rows; ++i) for (int j =

0; j < cols; ++j) result.mat[i][j] =

mat[i][j] + m.mat[i][j]; return result;

// Overload - operator for matrix subtraction

Matrix operator-(const Matrix& m) { Matrix result(rows, cols);

if (rows != m.rows || cols != m.cols) { cout << "Subtraction not

possible (dimension mismatch)!" << endl;

return result;
}

for (int i = 0; i < rows; ++i) for (int j =

0; j < cols; ++j) result.mat[i][j] =

mat[i][j] - m.mat[i][j]; return result;

// Overload * operator for matrix multiplication

Matrix operator*(const Matrix& m) { Matrix result(rows, m.cols);

if (cols != m.rows) { cout << "Multiplication not possible

(dimension mismatch)!" << endl;

return result;

for (int i = 0; i < rows; ++i) for (int j = 0; j <

m.cols; ++j) { result.mat[i][j] = 0; for

(int k = 0; k < cols; ++k) result.mat[i][j]

+= mat[i][k] * m.mat[k][j];

return result;

// Set dimensions void

setDimensions(int r, int c) {

rows = r; cols = c;

};
int main() { int r1,

c1, r2, c2; cout <<

"Enter rows and

columns for Matrix

1: "; cin >> r1 >>

c1; cout <<

"Enter rows and

columns for Matrix

2: "; cin >> r2 >>

c2;

Matrix m1(r1, c1), m2(r2, c2);

cout << "\nMatrix 1:\n"; m1.input();

cout << "\nMatrix 2:\n"; m2.input();

cout << "\nMatrix 1:\n"; m1.display();

cout << "\nMatrix 2:\n"; m2.display();

cout << "\n--- Matrix Addition ---\n";

if (r1 == r2 && c1 == c2) { Matrix

add = m1 + m2; add.display(); }

else { cout << "Addition not

possible.\n";

}
cout << "\n--- Matrix Subtraction ---\n"; if

(r1 == r2 && c1 == c2) { Matrix sub

= m1 - m2; sub.display();

} else { cout << "Subtraction not possible.\n";

cout << "\n--- Matrix Multiplication ---\n"; if

(c1 == r2) {

Matrix mul = m1 * m2;

mul.display();

} else { cout << "Multiplication not

possible.\n";

return 0;

ALGORITHM:-
Step 1: Start

Step 2: Define a Class Matrix

• Declare a 2D array mat[10][10] to hold matrix elements.

• Declare two integer variables rows and cols to store matrix


dimensions.

• Include methods for:

o input() – to read matrix elements from the user. o display() – to print the

matrix.

o Overloaded operators for:

▪ + – Matrix addition

▪ - – Matrix subtraction
▪ * – Matrix multiplication

Step 3: In the main() function

• Prompt the user to enter the number of rows and columns.

• Create two Matrix objects: m1 and m2.

• Use input() to read elements of both matrices.

Step 4: Perform Operations

• Use the overloaded + operator to compute the sum matrix and


display it.

• Use the overloaded - operator to compute the difference


matrix and display it.
• Check if matrix multiplication is possible (cols of m1 ==
rows of m2):
o If yes, use the overloaded * operator to compute the product and
display it. o If not, display an error message.
Step 5: End
OUTPUT:-

2. Create a base class Shape and derive classes like Circle, Square.
Algorithm:-
Step 1: Start

Step 2: Define a Base Class Shape

• Declare pure virtual functions:

o void input() — to input dimensions

o float area() — to compute


area o void display() — to

display the result

Step 3: Define Derived Class Circle

• Inherit from Shape.

• Add data member radius.

• Implement:

o input() — Read radius o area()

— Return π * radius² o

display() — Show the

computed area Step

4: Define Derived Class Square

• Inherit from Shape.

• Add data member side.

• Implement:

o input() — Read side o area()

— Return side * side o

display() — Show the

computed area

Step 5: In main() Function

• Create a Shape* pointer.

• Create objects c (Circle) and s (Square).

• Point shape to &c, call input() and display().

• Point shape to &s, call input() and display().

Step 6: End

Program code:-
#include <iostream> #include <cmath> // for M_PI using namespace std;
// Base class class Shape { public:
virtual void input() = 0; // pure virtual function virtual

float area() = 0; // pure virtual function virtual void

display() = 0; // pure virtual function

};

// Derived class: Circle class

Circle : public Shape { private:

float radius;

public:

void input() override { cout << "Enter

radius of the circle: "; cin >> radius;

float area() override { return

M_PI * radius * radius;

void display() override { cout <<

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

};

// Derived class: Square class

Square : public Shape { private:

float side;

public:
void input() override { cout <<

"Enter side of the square: "; cin >>

side;

float area() override { return

side * side;

void display() override { cout <<

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

};

// Main function int main()

Shape* shape;

cout << "--- Circle ---\n"; Circle

c; shape = &c; shape->input();

shape-

>display();

cout << "\n--- Square ---\n"; Square

s; shape = &s; shape->input();

shape-

>display();
return 0;

}
Output:-

3.Vehicle Management System Using Inheritance.


Algorithm:- Step
1: Start
Step 2: Define a Base Class Vehicle
• Declare common attributes:

o string brand o int

year
• Declare member functions: o input() — to take input

o display() — to show details o Use virtual functions

if using polymorphism

Step 3: Define Derived Class Car


• Inherit from Vehicle

• Add specific attributes like:

o int doors o string fuelType

• Override:
o input() — get car-specific details o display() —
show car-specific info

Step 4: Define Derived Class Bike


• Inherit from Vehicle

• Add specific attributes like: o int engineCC o bool

hasKickStart
• Override:

o input() — get bike-specific details o display() —

show bike-specific info

Step 5: In main() Function


1. Declare a pointer to Vehicle (e.g., Vehicle* v)
2. Create objects for Car and Bike
3. Set the pointer v to the object of Car o Call v-
>input() and v->display()
4. Set the pointer v to the object of Bike o Call v-
>input() and v->display()

Step 6: End
Program code:-

#include <iostream> using namespace

std;

// Base Class class

Vehicle { protected:
string brand; int

year;

public:

virtual void input() {

cout << "Enter brand: ";

cin >> brand; cout <<

"Enter year: "; cin >>

year;

virtual void display() { cout << "Brand: " <<

brand << " | Year: " << year;

virtual ~Vehicle() {} // Virtual destructor for proper cleanup

};

// Derived Class: Car class

Car : public Vehicle {

private: int doors;

string fuelType;

public:

void input() override { Vehicle::input(); cout

<< "Enter number of doors: "; cin >> doors; cout

<< "Enter fuel type (Petrol/Diesel/Electric): "; cin >>

fuelType;

}
void display() override { Vehicle::display(); cout << " |

Doors: " << doors << " | Fuel: " << fuelType << endl;

};

// Derived Class: Bike class

Bike : public Vehicle { private:

int engineCC; bool

hasKickStart;

public:
void input() override { Vehicle::input(); cout <<

"Enter engine CC: "; cin >> engineCC; cout <<

"Does it have kick start? (1 for Yes, 0 for No): "; cin >>

hasKickStart;

void display() override { Vehicle::display(); cout

<< " | Engine: " << engineCC << "cc | Kick Start: "

<< (hasKickStart ? "Yes" : "No") << endl;

};

// Main Function int main()

Vehicle* vehicle;
cout << "--- Car Details ---\n";

Car myCar; vehicle = &myCar;

vehicle->input(); vehicle-

>display();

cout << "\n--- Bike Details ---\n";

Bike myBike; vehicle =

&myBike; vehicle-

>input(); vehicle->display();

return 0;

Output:-

You might also like