0% ont trouvé ce document utile (0 vote)
45 vues41 pages

C++ Program Examples: Classes and Functions

c++ codes

Transféré par

jerryholand41
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats DOCX, PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
45 vues41 pages

C++ Program Examples: Classes and Functions

c++ codes

Transféré par

jerryholand41
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats DOCX, PDF, TXT ou lisez en ligne sur Scribd

#include <iostream>

#include <string> // for using string

using namespace std;

class REPORT {

int adno; // 4 digit admission number

char name[20]; // name (20 characters)

float marks[5]; // array of 5 floating point marks

float average; // average marks

// Function to calculate average marks

void GETAVG() {

float sum = 0;

for (int i = 0; i < 5; ++i) {

sum += marks[i];

average = sum / 5;
}

public:

// Function to read admission number, name, and marks

void READINFO() {

cout << "Enter admission number (4 digits): ";

cin >> adno;

cout << "Enter name (max 20 characters): ";

[Link](); // To clear the newline character left by cin

[Link](name, 20); // Get the full name input

cout << "Enter marks in 5 subjects: ";

for (int i = 0; i < 5; ++i) {

cin >> marks[i];

GETAVG(); // Calculate the average after entering the marks

// Function to display information

void DISPLAYINFO() {

cout << "Admission Number: " << adno << endl;

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

cout << "Marks: ";

for (int i = 0; i < 5; ++i) {

cout << marks[i] << " ";

}
cout << endl;

cout << "Average Marks: " << average << endl;

};

int main() {

REPORT r;

[Link](); // Read the information from the user

[Link](); // Display the entered information

return 0;

#include <iostream>

using namespace std;

// Class to keep track of the total fruits

class Fruit {

int apples;
int mangoes;

public:

// Function to input the number of apples and mangoes

void inputFruits() {

cout << "Enter the number of apples: ";

cin >> apples;

cout << "Enter the number of mangoes: ";

cin >> mangoes;

// Function to display the count of each fruit and total fruits

void displayFruits() {

cout << "Number of apples: " << apples << endl;

cout << "Number of mangoes: " << mangoes << endl;

cout << "Total number of fruits: " << apples + mangoes << endl;

};

int main() {

Fruit basket;

[Link](); // Input the number of apples and mangoes

[Link](); // Display the number of apples, mangoes, and total fruits

return 0;

Or
#include <iostream>

using namespace std;

// Base class Fruit

class Fruit {

protected:

int totalFruits;

public:

Fruit() : totalFruits(0) {} // Constructor initializes totalFruits to 0

void addFruits(int num) {

totalFruits += num; // Add fruits to the total

int getTotalFruits() {

return totalFruits; // Return total fruits

};

// Derived class for Apples

class Apples : public Fruit {

int applesCount;
public:

Apples(int count) {

applesCount = count;

addFruits(count); // Add apples to the total fruit count

int getApplesCount() {

return applesCount; // Return number of apples

};

// Derived class for Mangoes

class Mangoes : public Fruit {

int mangoesCount;

public:

Mangoes(int count) {

mangoesCount = count;

addFruits(count); // Add mangoes to the total fruit count

int getMangoesCount() {

return mangoesCount; // Return number of mangoes


}

};

int main() {

Apples apples(10); // Create an Apples object with 10 apples

Mangoes mangoes(5); // Create a Mangoes object with 5 mangoes

cout << "Number of apples: " << [Link]() << endl;

cout << "Number of mangoes: " << [Link]() << endl;

cout << "Total number of fruits: " << [Link]() << endl; // Apples
and Mangoes share the same total count

return 0;

Q1. Define a class Distance with the following details:

 Data members: feet (integer) and inches (float).


 Member functions:
1. void set(int, float) – to assign values to the object.
2. void disp() – to display the distance in feet and inches.
3. Distance add(Distance) – to add two Distance objects and return the sum as
a new Distance.

#include <iostream>

using namespace std;

class Distance {
private:

int feet;

float inches;

public:

// Member function to set the values of feet and inches

void set(int f, float in) {

feet = f;

inches = in;

// Member function to display the distance in feet and inches

void disp() const {

cout << "Distance: " << feet << " feet " << inches << " inches" << endl;

// Member function to add two Distance objects

Distance add(Distance d) {

Distance result;

[Link] = inches + [Link];

[Link] = feet + [Link];


// If inches exceed 12, convert it to feet

if ([Link] >= 12.0) {

[Link] -= 12.0;

[Link]++;

return result;

};

// Main function

int main() {

Distance d1, d2, d3;

// Setting values for d1 and d2

[Link](5, 8.5);

[Link](3, 11.2);

// Displaying the values of d1 and d2

cout << "First Distance: ";

[Link]();

cout << "Second Distance: ";


[Link]();

// Adding d1 and d2 and storing result in d3

d3 = [Link](d2);

// Displaying the result

cout << "Sum of Distances: ";

[Link]();

return 0;

Q2. Write a C++ program that uses a copy constructor to copy the data of one class into another.

#include <iostream>

using namespace std;

class Distance {

private:

int feet;

float inches;

public:

// Default constructor
Distance(int f = 0, float in = 0) {

feet = f;

inches = in;

// Copy constructor

Distance(const Distance &d) {

feet = [Link];

inches = [Link];

// Member function to display the distance

void disp() const {

cout << "Distance: " << feet << " feet " << inches << " inches" << endl;

};

int main() {

// Creating an object of Distance

Distance d1(5, 8.5);

// Creating a copy of d1 using the copy constructor

Distance d2 = d1;
// Displaying both distances

cout << "Original Distance: ";

[Link]();

cout << "Copied Distance: ";

[Link]();

return 0;

Q3. Overload the + operator to add two integers.

#include <iostream>

using namespace std;

class Add {

private:

int value;

public:

// Constructor

Add(int v = 0) {

value = v;

}
// Overloading + operator to add two Add objects

Add operator+(const Add &obj) {

Add result;

[Link] = value + [Link];

return result;

// Function to display the value

void display() const {

cout << "Value: " << value << endl;

};

int main() {

Add a1(10), a2(20), a3;

// Using the overloaded + operator to add two objects

a3 = a1 + a2;

// Displaying the results

cout << "First value: ";

[Link]();

cout << "Second value: ";


[Link]();

cout << "Sum: ";

[Link]();

return 0;

These solutions cover the requirements of the three questions. If you need any further
clarifications, feel free to ask!

You said:
please give more examples of such questions given above
ChatGPT said:
You’re giving feedback on a new version of ChatGPT.
Which response do you prefer? Responses may take a moment to load.
ChatGPT
Response 1

Sure! Here are some more example questions related to C++ object-oriented programming,
focusing on class design, operator overloading, constructors, and member functions similar to the
ones in the exam paper you shared.

Example 1: Class with Member Functions


Q1: Define a class called Time that has two data members: hours (integer)
and minutes (integer). The class should have the following member functions:

1. void setTime(int, int) to set the time.


2. void displayTime() to display time in hours:minutes format.
3. Time addTime(Time) to add two time objects and return the result.

Solution:

#include <iostream>

using namespace std;

class Time {

private:

int hours;

int minutes;

public:

// Function to set the time

void setTime(int h, int m) {

hours = h;
minutes = m;

// Function to display time

void displayTime() const {

cout << "Time: " << hours << " hours " << minutes << " minutes" << endl;

// Function to add two time objects

Time addTime(Time t) {

Time result;

[Link] = minutes + [Link];

[Link] = hours + [Link];


// Handle if minutes exceed 60

if ([Link] >= 60) {

[Link] -= 60;

[Link]++;

return result;

};

int main() {

Time t1, t2, t3;


// Setting times for two objects

[Link](2, 45);

[Link](1, 30);

// Adding times and storing result in t3

t3 = [Link](t2);

// Displaying the times

[Link]();

[Link]();

[Link]();
return 0;

Example 2: Copy Constructor


Q2: Define a class Rectangle with data members length and width. Write a C++ program to:

1. Initialize the values of length and width using a parameterized constructor.


2. Use a copy constructor to create a copy of the Rectangle object.
3. Display the area of the rectangles.

#include <iostream>

using namespace std;

class Complex {

private:

float real;

float imag;
public:

// Set values for real and imaginary parts

void set(float r, float i) {

real = r;

imag = i;

// Display complex number

void display() const {

cout << real << " + " << imag << "i" << endl;

// Add two complex numbers and return the result


Complex add(Complex c) {

Complex result;

[Link] = real + [Link];

[Link] = imag + [Link];

return result;

};

int main() {

Complex c1, c2, c3;

// Set values for c1 and c2

[Link](2.5, 3.5);
[Link](1.6, 2.7);

// Add c1 and c2, store the result in c3

c3 = [Link](c2);

// Display the complex numbers

cout << "First Complex number: ";

[Link]();

cout << "Second Complex number: ";

[Link]();

cout << "Sum of complex numbers: ";

[Link]();
return 0;

Pali
#include

using namespace std;

int reverse(int a){

int res = 0;

while(a!=0){

int dig = a%10;

res = res*10 + dig;

a =a/10;

return res;

int main() {

int a = 1221;

int b = reverse(a);

if(a == b)

cout<<"Palindrome";

else
cout<<"Not palindrome";

return 0;

Question 1:

Define a class to represent a bank account of 10 customers. The class contains four data
members:

 Name: (String) Customer's name.


 AccountNo: (Integer) Account number.
 Type: (Character) 'S' for saving and 'C' for current.
 Balance: (Float) Balance amount.

The class should contain the following member functions:

 Initialize the data members.


 Deposit money.
 Withdraw money after checking the balance.
 Display the data members.

#include <iostream>

#include <string>

using namespace std;

class BankAccount {

private:

string Name;

int AccountNo;

char Type; // 'S' for Saving, 'C' for Current

float Balance;
public:

// Function to initialize account details

void initialize(string name, int accountNo, char type, float balance) {

Name = name;

AccountNo = accountNo;

Type = type;

Balance = balance;

// Function to deposit money

void deposit(float amount) {

if (amount > 0) {

Balance += amount;

cout << "Deposited: " << amount << ". New Balance: " << Balance << endl;

} else {

cout << "Deposit amount must be positive!" << endl;

// Function to withdraw money

void withdraw(float amount) {

if (amount > 0 && amount <= Balance) {


Balance -= amount;

cout << "Withdrawn: " << amount << ". Remaining Balance: " << Balance <<
endl;

} else if (amount > Balance) {

cout << "Insufficient balance!" << endl;

} else {

cout << "Withdrawal amount must be positive!" << endl;

// Function to display account details

void display() const {

cout << "Account Holder: " << Name << endl;

cout << "Account Number: " << AccountNo << endl;

cout << "Account Type: " << (Type == 'S' ? "Saving" : "Current") << endl;

cout << "Balance: " << Balance << endl;

};

int main() {

BankAccount accounts[10]; // Array for 10 customers


// Example initialization of accounts for 2 customers (out of 10)

accounts[0].initialize("Alice", 1001, 'S', 5000.50);

accounts[1].initialize("Bob", 1002, 'C', 10000.00);

// Operations for customer 1 (Alice)

accounts[0].display(); // Display details

accounts[0].deposit(1500); // Deposit money

accounts[0].withdraw(2000); // Withdraw money

accounts[0].display(); // Display details again

// Operations for customer 2 (Bob)

accounts[1].display(); // Display details

accounts[1].deposit(2500); // Deposit money

accounts[1].withdraw(3000); // Withdraw money

accounts[1].display(); // Display details again

return 0;

Question 2: Class for a Car Showroom

Define a class Car to represent cars in a showroom. The class should have the following data
members:
 Model: (String) The model name of the car.
 MakeYear: (Integer) The year of manufacture.
 Price: (Float) The price of the car.
 Available: (Boolean) Whether the car is available for purchase or not.

The class should have the following member functions:

1. void inputDetails() to take the car details from the user.


2. void purchaseCar() to mark the car as sold if available.
3. void displayDetails() to display the car details.

Write a program to create multiple Car objects and allow users to interact with the system to buy
cars and display information.

#include <iostream>

#include <string>

using namespace std;

class Car {

private:

string Model;

int MakeYear;

float Price;

bool Available; // true = available, false = sold

public:

void inputDetails(string model, int year, float price) {

Model = model;

MakeYear = year;
Price = price;

Available = true;

void purchaseCar() {

if (Available) {

Available = false;

cout << "Car purchased successfully!" << endl;

} else {

cout << "Car is already sold." << endl;

void displayDetails() {

cout << "Model: " << Model << ", Year: " << MakeYear

<< ", Price: " << Price << ", Status: "

<< (Available ? "Available" : "Sold") << endl;

};

int main() {

Car showroom[5];
showroom[0].inputDetails("Toyota Corolla", 2020, 25000);

showroom[0].displayDetails();

showroom[0].purchaseCar();

showroom[0].displayDetails();

return 0;

Question 3: Class for a Student Record System

Define a class Student to store student details. The class should have the following data
members:

 Name: (String) Student's name.


 RollNo: (Integer) Student's roll number.
 Marks: (Array of 5 floats) Marks in 5 subjects.

The class should have the following member functions:

1. void input() to input student details.


2. float calculateAverage() to calculate the average marks.
3. void display() to display the student details along with the average marks.

Write a program to create an array of 3 Student objects, input their details, and display the
details along with the calculated averages.

#include <iostream>

#include <string>

using namespace std;

class Student {
private:

string Name;

int RollNo;

float Marks[5];

public:

void input() {

cout << "Enter student name: ";

cin >> Name;

cout << "Enter roll number: ";

cin >> RollNo;

cout << "Enter marks for 5 subjects: ";

for (int i = 0; i < 5; i++) {

cin >> Marks[i];

float calculateAverage() {

float total = 0;

for (int i = 0; i < 5; i++) {

total += Marks[i];

}
return total / 5;

void display() {

cout << "Name: " << Name << ", Roll No: " << RollNo << ", Average Marks: "
<< calculateAverage() << endl;

};

int main() {

Student students[3];

for (int i = 0; i < 3; i++) {

students[i].input();

students[i].display();

return 0;

Question 4: Class for a Bank System with Interest Calculation

Define a class BankAccount for storing account details of customers. The class should have the
following data members:

 AccountHolderName: (String) The name of the account holder.


 AccountNumber: (Integer) The account number.
 Balance: (Float) The current balance.
 AccountType: (Character) S for savings, C for current.

The class should have the following member functions:

1. void deposit(float) to add money to the account.


2. void withdraw(float) to withdraw money after checking the balance.
3. float calculateInterest() to calculate interest (use a fixed interest rate for
simplicity).
4. void displayDetails() to display account details.

Write a program to create accounts for multiple customers, allow deposits and withdrawals, and
calculate interest for savings accounts.

#include <iostream>

#include <string>

using namespace std;

class BankAccount {

private:

string AccountHolderName;

int AccountNumber;

float Balance;

char AccountType; // 'S' for Savings, 'C' for Current

public:

void initialize(string name, int accNo, float bal, char type) {

AccountHolderName = name;

AccountNumber = accNo;

Balance = bal;
AccountType = type;

void deposit(float amount) {

Balance += amount;

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

void withdraw(float amount) {

if (amount <= Balance) {

Balance -= amount;

cout << "Withdrawn: " << amount << ", Remaining Balance: " << Balance << endl;

} else {

cout << "Insufficient Balance!" << endl;

float calculateInterest() {

if (AccountType == 'S') {

return Balance * 0.03; // 3% interest

} else {

return 0;

}
}

void displayDetails() {

cout << "Account Holder: " << AccountHolderName

<< ", Account Number: " << AccountNumber

<< ", Balance: " << Balance

<< ", Interest: " << calculateInterest() << endl;

};

int main() {

BankAccount account;

[Link]("John Doe", 123456, 10000, 'S');

[Link]();

[Link](2000);

[Link](1500);

[Link]();

return 0;

Question 5: Class for a College Course Registration System

Define a class Course to represent a college course. The class should have the following data
members:
 CourseName: (String) Name of the course.
 CourseCode: (String) Unique code for the course.
 Instructor: (String) Name of the instructor.
 EnrolledStudents: (Integer) Number of students enrolled.

The class should have the following member functions:

1. void enrollStudent() to increase the number of enrolled students.


2. void displayCourseInfo() to display course details.
3. void setInstructor(string) to assign or change the course instructor.

Write a program to manage multiple courses and allow users to enroll in courses and display
information about courses.

#include <iostream>

#include <string>

using namespace std;

class Course {

private:

string CourseName;

string CourseCode;

string Instructor;

int EnrolledStudents;

public:

void initialize(string name, string code, string instructor) {

CourseName = name;

CourseCode = code;

Instructor = instructor;
EnrolledStudents = 0;

void enrollStudent() {

EnrolledStudents++;

cout << "One student enrolled in " << CourseName << ". Total Enrolled: " <<
EnrolledStudents << endl;

void displayCourseInfo() {

cout << "Course Name: " << CourseName

<< ", Course Code: " << CourseCode

<< ", Instructor: " << Instructor

<< ", Enrolled Students: " << EnrolledStudents << endl;

void setInstructor(string newInstructor) {

Instructor = newInstructor;

};

int main() {

Course course;
[Link]("Computer Science", "CS101", "Dr. Smith");

[Link]();

[Link]();

[Link]("Dr. Johnson");

[Link]();

return 0;

Question 7: Class for a Company Employee Management System

Define a class Employee to represent employees in a company. The class should have the
following data members:

 EmployeeName: (String) Name of the employee.


 EmployeeID: (Integer) Unique ID of the employee.
 Salary: (Float) Employee's salary.
 Department: (String) Department name.

The class should have the following member functions:

1. void inputDetails() to input employee details.


2. void calculateBonus() to calculate the yearly bonus (use a percentage of salary for
bonus).
3. void displayDetails() to display employee details along with the bonus.

Write a program to create and manage employee records, calculate bonuses, and display
employee details.

#include <iostream>

#include <string>

using namespace std;

class Employee {
private:

string EmployeeName;

int EmployeeID;

float Salary;

string Department;

public:

// Function to initialize employee details

void inputDetails(string name, int id, float salary, string dept) {

EmployeeName = name;

EmployeeID = id;

Salary = salary;

Department = dept;

// Function to calculate 10% bonus

float calculateBonus() {

return Salary * 0.10; // 10% bonus

// Function to display employee details and bonus

void displayDetails() {

cout << "Employee Name: " << EmployeeName << endl;


cout << "Employee ID: " << EmployeeID << endl;

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

cout << "Department: " << Department << endl;

cout << "Bonus (10%): $" << calculateBonus() << endl;

};

int main() {

Employee employees[3]; // Array to store 3 employees

// Input details for 3 employees

employees[0].inputDetails("Alice", 1001, 50000, "HR");

employees[1].inputDetails("Bob", 1002, 60000, "IT");

employees[2].inputDetails("Charlie", 1003, 55000, "Finance");

// Display details for each employee

for (int i = 0; i < 3; i++) {

cout << "\nEmployee " << i + 1 << " Details:" << endl;

employees[i].displayDetails();

return 0;

Vous aimerez peut-être aussi