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

CPP Programs1-20

The document contains examples of C++ programs using classes and functions. It includes programs to swap values, perform arithmetic operations using inline functions, calculate area and perimeter of shapes, overload functions, create and use classes to store and manipulate data.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

CPP Programs1-20

The document contains examples of C++ programs using classes and functions. It includes programs to swap values, perform arithmetic operations using inline functions, calculate area and perimeter of shapes, overload functions, create and use classes to store and manipulate data.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

1. Write a C++ program for swapping values of two variables using call by reference.

#include <iostream>
#include<conio.h>
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x, y;
cout << "Enter the first number: ";
cin >> x;
cout << "Enter the second number: ";
cin >> y;

cout << "Before swapping: x = " << x << ", y = " << y << endl;
swap(x, y);
cout << "After swapping: x = " << x << ", y = " << y << endl;

return 0;
}
2. Write a C++ program to read two float numbers. Perform arithmetic binary operations like +,
- , *, / on these numbers using Inline Function. Display resultant value with a precision of two
digits
#include <iostream>
#include <iomanip>

inline float add(float a, float b) {


return a + b;
}
inline float subtract(float a, float b) {
return a - b;
}
inline float multiply(float a, float b) {
return a * b;
}
inline float divide(float a, float b) {
return a / b;
}
int main() {
float num1, num2;

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


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

float sum = add(num1, num2);


float difference = subtract(num1, num2);
float product = multiply(num1, num2);
float quotient = divide(num1, num2);

std::cout << std::fixed << std::setprecision(2);


std::cout << "Sum: " << sum << std::endl;
std::cout << "Difference: " << difference << std::endl;
std::cout << "Product: " << product << std::endl;
std::cout << "Quotient: " << quotient << std::endl;

return 0;
}
3. Write a C++ program to calculate and display perimeter as well as area of a square by using
Inline function.
#include<iostream.h>
inline int calculatePerimeter(int side) {
return 4 * side;
}
inline int calculateArea(int side) {
return side * side;
}
int main() {
int side;
cout << "Enter the side length of the square: ";
cin >> side;
int perimeter = calculatePerimeter(side);
int area = calculateArea(side);
cout << "Perimeter of the square: " << perimeter << endl;
cout << "Area of the square: " << area << endl;
return 0;
}
4. Write a C++ program to calculate area of cone, sphere and circle by using function
overloading.
Cone pi*r*(r+len) sphere 4*pi*r*r circle pi*r*r
#include <iostream.h>
#include <cmath>
const double PI = 3.14;
double calculateArea(double radius) {
return PI * pow(radius, 2);
}

double calculateArea(double radius, bool isSphere) {


if (isSphere) {
return 4 * PI * pow(radius, 2);
}
return calculateArea(radius);
}

double calculateArea(double radius, double height) {


return PI * radius * (radius + sqrt(pow(height, 2) + pow(radius, 2)));
}

int main() {
double radius, height;
cout << "Enter the radius of the circle: ";
cin >> radius;
cout << "Area of the circle: " << calculateArea(radius) << endl;

cout << "Enter the radius of the sphere: ";


cin >> radius;
cout << "Area of the sphere: " << calculateArea(radius, true) << endl;

cout << "Enter the radius and height of the cone (space-separated): ";
cin >> radius >> height;
cout << "Area of the cone: " << calculateArea(radius, height) << endl;

return 0;
}
5. Create a class Person that contains data members as Person_Name, City, Mob_No.
Write a C++ program to perform following functions:
i) To accept and display Person information
ii)To search the mobile number of a given person
iii)To search the Person details of a given mobile number
#include<iostream>
#include<string.h>
#include<conio.h>
class person
{
char name[20];
char city[15];
long mobno;
public:
void getdata()
{
cout<<"person name";
cin>>person name;
cout<<"city name";
cin>>city name;
cout<<"mobileno";
cin>>mobno;
}
void display()
{
cout<<"\n person name"<<name;
cout<<"\n city name"<<city;
cout<<"\n mobile number"<<mobno;
}
void search(char n[])
{
if(strcmp(name,n)==0)
{
cout<<"\n person name"<<name;
cout<<"\n city name"<<city;
cout<<"\n mobile number"<<mobno;

}
}
void search(long mobileno)
{
if(mobno==mobileno)
{
cout<<"\n person name"<<name;
cout<<"\n city name"<<city;
cout<<"\n mobile number"<<mobno;

}
}
};
void main()
{
int n;
long mobno;
char name[20];
int ch;
person*p;
clrscr();
cout<,"\n nter how many records o be entered:";
cin>>n;
p=new.person[n];
while(1)
{
cout<<"\n 1.enter records"
cout<<"\n 2.display records"
cout<<"\n 3.search mobileno"
cout<<"\n 4.search name by long mobno"
cout<<"\n 5.exit"
cout<<"\n enter your choice";
cin>>ch;
switch(ch)
{
case 1:
for(int i=0;i<n;i++)
{
p[i].getdata();
}
break;
case 2:
for(i=0;i<n;i++)
{
p[i].display();
}
break;
case 3:
cout<<"person name"
cin>>name;
for(i=0;i<n;i++)
{
p[i].search(name);
}
break;
case 4:
cout<<"enter mobno of person t be sarched";
cin>>mobno;
for(i=0;i<n;i++)
{
p[i].search(mobno);
}
break;
case 5:
exit(0);
}
getch();

}
}
6. Write a C++ program to create a class Worker with data members as Worker_Name,
No_of_Hours_worked, Pay_Rate. Write necessary member functions to calculate and display
the salary of worker. (Use default value for Pay_Rate)
#include <iostream.h>
class Worker {
private:
string Worker_Name;
int No_of_Hours_worked;
double Pay_Rate;

public:
Worker(string name, int hours, double rate = 10.0) {
Worker_Name = name;
No_of_Hours_worked = hours;
Pay_Rate = rate;
}

double calculateSalary() {
return No_of_Hours_worked * Pay_Rate;
}

void displayDetails() {
cout << "Worker Name: " << Worker_Name << endl;
cout << "No. of Hours Worked: " << No_of_Hours_worked << endl;
cout << "Pay Rate: " << Pay_Rate << " per hour" << endl;
cout << "Salary: " << calculateSalary() << endl;
}
};

int main() {
string name;
int hours;
double rate;

cout << "Enter Worker Name: ";


getline(cin, name);

cout << "Enter No. of Hours Worked: ";


cin >> hours;
cout << "Enter Pay Rate (or press Enter for default): ";
cin.ignore();
string rateInput;
getline(cin, rateInput);

if (rateInput.empty()) {
Worker worker(name, hours);
worker.displayDetails();
} else {
rate = stod(rateInput);
Worker worker(name, hours, rate);
worker.displayDetails();
}

return 0;
}
7. Class person with data members name, address, salary, tax_amt. Calculate tax_amt by
checking salary of the person
i)salary<=5,00,000 then tax_rate=0
ii) salary>5,00,000 and <=10,00,000 then tax_rate=5% of salary
iii)salary>=10,00,000 then tax_rate=10% of salary
#include <iostream.h>
class Person {
public:
string name;
string address;
double salary;
double tax_amt;

void calculateTax() {
if (salary <= 500000) {
tax_amt = 0;
} else if (salary <= 1000000) {
tax_amt = 0.05 * salary;
} else {
tax_amt = 0.10 * salary;
}
}
};

int main() {
Person p;

cout << "Enter name: ";


getline(cin, p.name);
cout << "Enter address: ";
getline(cin, p.address);
cout << "Enter salary: ";
cin >> p.salary;

p.calculateTax();
cout << "\nDetails:\n";
cout << "Name: " << p.name << endl;
cout << "Address: " << p.address << endl;
cout << "Salary: " << p.salary << endl;
cout << "Tax Amount: " << p.tax_amt << endl;

return 0;
}
8. Create a C++ class Time which contains data members as: Hours, Minutes and Seconds.Write
necessary member functions: Do following using(object as argument)
i)To accept a time
ii) To display time in format like: hh:mm:ss
iii) To find difference between two times and display it in format hh:mm:ss
#include<iostream.h>
class Time {
private:
int hours;
int minutes;
int seconds;

public:
void acceptTime() {
cout << "Enter hours: ";
cin >> hours;
cout << "Enter minutes: ";
cin >> minutes;
cout << "Enter seconds: ";
cin >> seconds;
}

void displayTime() {
cout << hours << ":" << minutes << ":" << seconds << endl;
}

void calculateDifference(Time t1, Time t2) {


int totalSeconds1 = t1.hours * 3600 + t1.minutes * 60 + t1.seconds;
int totalSeconds2 = t2.hours * 3600 + t2.minutes * 60 + t2.seconds;
int diffSeconds = abs(totalSeconds2 - totalSeconds1);

hours = diffSeconds / 3600;


minutes = (diffSeconds % 3600) / 60;
seconds = (diffSeconds % 3600) % 60;
}
};

int main() {
Time t1, t2, diffTime;

cout << "Enter first time: ";


t1.acceptTime();

cout << "Enter second time: ";


t2.acceptTime();

cout << "First time: ";


t1.displayTime();

cout << "Second time: ";


t2.displayTime();

diffTime.calculateDifference(t1, t2);

cout << "Time difference: ";


diffTime.displayTime();

return 0;
}
9. Write a C++ program to create class student with data members roll_no, name, marks.
Write member functions to accept and display n student details.(Use dynamic memory
allocation)
#include <iostream.h>
class Student {
private:
int roll_no;
string name;
float marks;

public:
void acceptDetails() {
cout << "Enter Roll No: ";
cin >> roll_no;
cout << "Enter Name: ";
cin >> name;
cout << "Enter Marks: ";
cin >> marks;
}

void displayDetails() {
cout << "Roll No: " << roll_no << ", Name: " << name << ", Marks: " << marks << endl;
}
};

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

Student* students = new Student[n];

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


cout << "Enter details for student " << i+1 << ":" << endl;
students[i].acceptDetails();
}

cout << "\nDetails of students:" << endl;


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

delete[] students;

return 0;
}
10. Write program to create class product with data members product_id, product_name, qty, price.
Write member functions to accept and display product information also display the number of objects
created for product class (use static data member and static member function)
#include<iostream.h>
class Product {
private:
static int objectCount;
int product_id;
string product_name;
int qty;
float price;
public:
Product() {
product_id = 0;
product_name = "";
qty = 0;
price = 0.0;
objectCount++;
}

Product(int id, string name, int quantity, float cost) {


product_id = id;
product_name = name;
qty = quantity;
price = cost;
objectCount++;
}

void acceptProductInfo() {
cout << "Enter Product ID: ";
cin >> product_id;
cout << "Enter Product Name: ";
getline(cin, product_name);
cout << "Enter Quantity: ";
cin >> qty;
cout << "Enter Price: $";
cin >> price;
}

void displayProductInfo() {
cout << "Product ID: " << product_id << endl;
cout << "Product Name: " << product_name << endl;
cout << "Quantity: " << qty << endl;
cout << "Price: $" << price << endl;
}

static int getObjectCount() {


return objectCount;
}
};

int Product::objectCount = 0;

int main() {
Product product1, product2;
cout << "Enter details for Product 1:\n";
product1.acceptProductInfo();

cout << "\nEnter details for Product 2:\n";


product2.acceptProductInfo();

cout << "\nProduct 1 Information:\n";


product1.displayProductInfo();
cout << "\nProduct 2 Information:\n";
product2.displayProductInfo();

cout << "\nTotal Number of Products: " << Product::getObjectCount() << endl;

return 0;
}
11. Write a c++ program to calculate maximum of two integer numbers of two different classes
using friend function
#include<iostream.h>
class B;
class A {
private:
int numA;

public:
A() {
cout << "Enter value for numA: ";
cin >> numA;
}

friend int maxNum(A, B);


};

class B {
private:
int numB;

public:
B() {
cout << "Enter value for numB: ";
cin >> numB;
}

friend int maxNum(A, B);


};

int maxNum(A objA, B objB) {


return (objA.numA > objB.numB) ? objA.numA : objB.numB;
}

int main() {
A objA;
B objB;
int max = maxNum(objA, objB);
cout << "Maximum number is: " << max << endl;

return 0;
}

12. Write a C++ program to create two classes Class1 and Class2. Each class contains one float
data member. Write following functions:
i.To accept float numbers
ii. To display float numbers in right justified format with precision of two digits
iii.To Exchange the private values of both these classes by using Friend function
#include <iostream.h>
class Class2; class Class1 {
private:
float number1;

public:
void acceptFloat() {
std::cout << "Enter a float for Class1: ";
std::cin >> number1;
}

void displayFloat() {
std::cout << std::fixed << std::setprecision(2) << std::right << std::setw(10) << number1 <<
std::endl;
}
friend void exchangeValues(Class1& obj1, Class2& obj2);
};

class Class2 {
private:
float number2;

public:
void acceptFloat() {
std::cout << "Enter a float for Class2: ";
std::cin >> number2;
}

void displayFloat() {
std::cout << std::fixed << std::setprecision(2) << std::right << std::setw(10) << number2 <<
std::endl;
}
friend void exchangeValues(Class1& obj1, Class2& obj2);
};
void exchangeValues(Class1& obj1, Class2& obj2) {
float temp = obj1.number1;
obj1.number1 = obj2.number2;
obj2.number2 = temp;
}

int main() {
Class1 obj1;
Class2 obj2;
obj1.acceptFloat();
obj2.acceptFloat();
std::cout << "\nValues before exchange:\n";
std::cout << "Class1: ";
obj1.displayFloat();
std::cout << "Class2: ";
obj2.displayFloat();
exchangeValues(obj1, obj2);
std::cout << "\nValues after exchange:\n";
std::cout << "Class1: ";
obj1.displayFloat();
std::cout << "Class2: ";
obj2.displayFloat();
return 0;
}
13. Write a C++ program using class which contains two data members of type integer. Create
and initialize the object using default constructor and parameterized constructor with
default value. Write a member function to display maximum from given two numbers for
all objects.
#include<iostream.h>
class NumberPair {
private:
int num1;
int num2;
public:
NumberPair() {
num1 = 0;
num2 = 0;
}
NumberPair(int n1 = 0, int n2 = 0) {
num1 = n1;
num2 = n2;
}

void displayMaximum() {
if (num1 > num2) {
cout << "Maximum: " << num1 << endl;
} else {
cout << "Maximum: " << num2 << endl;
}
}
};

int main() {
int num1, num2;
cout << "Enter num1: ";
cin >> num1;
cout << "Enter num2: ";
cin >> num2;

NumberPair pair(num1, num2);


pair.displayMaximum();

return 0;
}
14. Write a C++ program to create a class Integer. Write necessary member functions to
overload the operator unary pre and post increment ‘++’ for an integer number.
#include<iostream.h>
class Integer {
private:
int value;
public:
Integer(int val) : value(val) {}

Integer& operator++() {
++value;
return *this;
}
Integer operator++(int) {
Integer temp = *this;
++(*this);
return temp;
}

void display() {
cout << "Value: " << value << endl;
}
};

int main() {
int initialValue;
cout << "Enter the initial value: ";
cin >> initialValue;
Integer num(initialValue)
cout << "Before incrementing:" << endl;
num.display();
++num;
cout << "After pre-increment:" << endl;
num.display();
num++;
cout << "After post-increment:" << endl;
num.display();
return 0;
}
15. reate a class ComplexNumber containing members as:
- real
- imaginary
Write a C++ program to calculate and display the sum of two complex numbers. (Use friend
function and return by object)
#include<iostream.h>
class ComplexNumber {
private:
float real;
float imaginary;

public:
ComplexNumber(float r, float i) : real(r), imaginary(i) {}

friend ComplexNumber addComplex(ComplexNumber c1, ComplexNumber c2);

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

ComplexNumber addComplex(ComplexNumber c1, ComplexNumber c2) {


float realSum = c1.real + c2.real;
float imagSum = c1.imaginary + c2.imaginary;
return ComplexNumber(realSum, imagSum);
}

int main() {
float real1, imag1, real2, imag2;
cout << "Enter real and imaginary parts of first complex number: ";
cin >> real1 >> imag1;
cout << "Enter real and imaginary parts of second complex number: ";
cin >> real2 >> imag2;
ComplexNumber num1(real1, imag1);
ComplexNumber num2(real2, imag2);
ComplexNumber sum = addComplex(num1, num2);
cout << "Sum of ";
num1.display();
cout << "and ";
num2.display();
cout << "is ";
sum.display();

return 0;
}
16. Create a class for inventory of Mobile containing Model_Number, Company_Name,
Price, Stock as data members. Mobile can be sold, if stock is available, otherwise purchase will
be made. Write a C++ program to perform following functions. i. To accept and display mobile
details ii. To sale a Mobile (Sale contains Model_Number & Quantity of mobile)
iii. To Purchase a Mobile (Purchase contains Model_Number & Quantity of mobile)
#include <iostream.h>
#include <vector>
class Mobile {
public:
string Model_Number;
string Company_Name;
double Price;
int Stock;

Mobile(string model, string company, double price, int stock) {


Model_Number = model;
Company_Name = company;
Price = price;
Stock = stock;
}

void SellMobile(int quantity) {


if (Stock >= quantity) {
Stock -= quantity;
cout << "Sold " << quantity << " " << Company_Name << " " << Model_Number << "(s)."
<< endl;
} else {
cout << "Not enough stock available for " << Company_Name << " " << Model_Number
<< "." << endl;
}
}

void PurchaseMobile(int quantity) {


Stock += quantity;
cout << "Purchased " << quantity << " " << Company_Name << " " << Model_Number <<
"(s)." << endl;
}
};

int main() {
vector<Mobile> mobileInventory;
string model, company;
double price;
int stock;
cout << "Enter Model Number: ";
cin >> model;
cout << "Enter Company Name: ";
cin >> company;
cout << "Enter Price: ";
cin >> price;
cout << "Enter Stock: ";
cin >> stock;
mobileInventory.push_back(Mobile(model, company, price, stock));
int choice;
int quantity;

do {
cout << "\nMenu:\n1. Sell Mobile\n2. Purchase Mobile\n3. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter the quantity to sell: ";
cin >> quantity;
mobileInventory[0].SellMobile(quantity);
break;
case 2:
cout << "Enter the quantity to purchase: ";
cin >> quantity;
mobileInventory[0].PurchaseMobile(quantity);
break;
case 3:
break;
default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 3);
for (const Mobile& mobile : mobileInventory) {
cout << "Model: " << mobile.Model_Number << ", Company: " << mobile.Company_Name
<< ", Price: $" << mobile.Price << ", Stock: " << mobile.Stock << endl;
}

return 0;
}
17. Write a C++ program to create a class Part which contains data members as Part_Id,
Part_Name, Part_Price. Create and Initialize all values of Part object by using parameterized
constructor and copy constructor. Display the values of Part object. (Part_price should be right
justified with a precision of two digits)
#include <iostream.h>
#include <iomanip>
class Part {
private:
int Part_Id;
string Part_Name;
double Part_Price;

public:
Part(int id, string name, double price) : Part_Id(id), Part_Name(name), Part_Price(price) {}

Part(const Part& other) : Part_Id(other.Part_Id), Part_Name(other.Part_Name),


Part_Price(other.Part_Price) {}

void display() {
cout << "Part ID: " << Part_Id << endl;
cout << "Part Name: " << Part_Name << endl;
cout << fixed << setprecision(2) << "Part Price: " << setw(10) << Part_Price << endl;
}
};

int main() {
int id;
string name;
double price;
cout << "Enter Part ID: ";
cin >> id;
cin.ignore(); // Clear the input buffer
cout << "Enter Part Name: ";
getline(cin, name);
cout << "Enter Part Price: ";
cin >> price;
Part part1(id, name, price);
Part part2 = part1;
cout << "Details of Part 1:" << endl;
part1.display();
cout << "\nDetails of Part 2 (Copied from Part 1):" << endl;
part2.display();

return 0;
}
18. Write a C++ program to find maximum and minimum of two integer numbers(use inline
function & conditional operator)
#include<iostream.h>
inline int findMax(int a, int b) {
return (a > b) ? a : b;
}
inline int findMin(int a, int b) {
return (a < b) ? a : b;
}

int main() {
int num1, num2;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Maximum: " << findMax(num1, num2) << endl;
cout << "Minimum: " << findMin(num1, num2) << endl;

return 0;
}
19. Write a C++ program to read an array of an ’n’ integer from user and display it in a reverse
order(use dynamic allocation).
#include <iostream.h>
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int* arr = new int[n];
cout << "Enter " << n << " integers:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Array in reverse order:" << endl;
for (int i = n - 1; i >= 0; i--) {
cout << arr[i] << " ";
}
delete[] arr;

return 0;
}
20. Write a C++ program to find average of 3 integers and 3 float numbers (use function
overloading)
#include <iostream>
float average(int a, int b, int c) {
return (a + b + c) / 3.0;
}
float average(float x, float y, float z) {
return (x + y + z) / 3.0;
}

int main() {
int int1, int2, int3;
float float1, float2, float3;
cout << "Enter three integers: ";
cin >> int1 >> int2 >> int3;
cout << "Enter three float numbers: ";
cin >> float1 >> float2 >> float3;
float intAvg = average(int1, int2, int3);
cout << "Average of integers: " << intAvg << endl;
float floatAvg = average(float1, float2, float3);
cout << "Average of floats: " << floatAvg << endl;

return 0;
}

You might also like