Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

C++ Programs for Practice and Revision

Q. Write a C++ program to check whether the input number is an even or an odd
number.

Answer:

Following program shows that whether the number entered by user is an Even number or an
Odd number.

#include<iostream>
using namespace std;
int main()
{
int num;
cout<<"\n Enter Number : ";
cin>>num;
if(num%2==0)
{
cout<<"\n Even Number";
}
else
{
cout<<"\n Odd Number";
}
return 0;
}

Output:

Q. Write a C++ program to find the HCF and LCM of two numbers.
Answer:

HCF stands for Highest Common Factor. It is also known as Greatest Common Divisor (GCD)
or Greatest Common Factor (GCF). HCF of two numbers are defined the largest number that
divides both numbers completely with remainder zero.

LCM stands for Lowest Common Multiple. LCM of two numbers are defined as smallest
number that is multiple of both numbers.

#include<iostream>
using namespace std;
int main()
{
int a, b, x, y, temp, hcf, lcm;
cout<<"\n Enter Two Numbers : \n";
cin>>x>>y;
a=x;
b=y;
while(b!=0)
{
temp=b;
b=a%b;
a=temp;
}
hcf=a;
lcm=(x*y)/hcf;
cout<<"\n HCF : "<<hcf<<"\n";
cout<<"\n LCM : "<<lcm<<"\n";
return 0;
}

Output:
Q. Write a C++ program to calculate grade of a student on the basis of his/her
total marks.

Answer:

Following program is calculating grade of student according to his/her total marks.

#include<iostream>
using namespace std;
int main()
{
int marks[5], i;
float sum=0,avg;

cout<<"\n Enter Marks of Student \n";


cout<<"------------------------------------";
cout<<"\n Hindi : ";
cin>>marks[0];
cout<<"\n English : ";
cin>>marks[1];
cout<<"\n Maths : ";
cin>>marks[2];
cout<<"\n History : ";
cin>>marks[3];
cout<<"\n Science : ";
cin>>marks[4];

for(i=0;i<5;i++)
{
sum=sum+marks[i];
}
cout<<"------------------------------------";
cout<<"\n Total Marks of Student = "<<sum;
avg=sum/5;
cout<<"\n Average = "<<avg;
cout<<"\n Grade = ";

if(avg>80)
{
cout<<"A";
}
else if(avg>60 && avg<=80)
{
cout<<"B";
}
else if(avg>40 && avg<=60)
{
cout<<"C";
}
else
{
cout<<"D";
}
return 0;
}

Output:

Q. Write a C++ program to calculate area and perimeter of square and rectangle
using function.

Answer:

Following program is calculating area and perimeter of square and rectangle using function.
#include<iostream>
using namespace std;

int area(int);
int area(int,int);
float peri(float);
float peri(float,float);
int main()
{
int side, length, breadth;
cout<<"\n Enter Side of a Square : ";
cin>>side;
cout<<"\n Enter Length and Breadth of Rectangle : ";
cin>>length>>breadth;
cout<<"\n Area of Square : "<<area(side);
cout<<"\n Area of Rectangle : "<<area(length,breadth);
cout<<"\n Perimeter of Square : "<<peri(side);
cout<<"\n Perimeter of Rectangle : "<<peri(length,breadth);
}
int area(int s)
{
return(s*s);
}
int area(int l,int b)
{
return(l*b);
}
float peri(float s)
{
return(4*s);
}
float peri(float l,float b)
{
return(2*(l+b));
}

Output:
Q. Write a C++ program to display the addition of two numbers using pointer.

Answer:

Following program is performing an addition of two numbers using pointer.

#include<iostream>
using namespace std;
int main()
{
int num1, num2, *ptr1, *ptr2, sum=0;
cout<<"\n Enter Two Numbers : \n";
cout<<" ";
cin>>num1;
cout<<" ";
cin>>num2;
ptr1 = &num1;
ptr2 = &num2;
sum = *ptr1 + *ptr2;
cout<<"\n Addition of Two Numbers : "<<sum;
return 0;
}

Output:

Q. Write a C++ program to calculate the percentage of a student using multi-level


inheritance. Accept the marks of three subjects in base class. A class will derived
from the above mentioned class which includes a function to find the total marks
obtained and another class derived from this class which calculates and displays
the percentage of student.

Answer:

Multilevel inheritance represents a type of inheritance when a derived class is a base class
for another class.

Following program calculates the percentage of a student using multi-level inheritance.

#include<iostream>
using namespace std;

class AddData //Base Class


{
protected:
int subjects[3], i;
public:
void accept_details()
{
cout<<"\n Enter Marks for Three Subjects ";
cout<<"\n ------------------------------- \n";
cout<<"\n English : ";
cin>>subjects[0];
cout<<"\n Maths : ";
cin>>subjects[1];
cout<<"\n History : ";
cin>>subjects[2];
}
};
//Class Total – Derived Class. Derived from class AddData and Base class of class
Percentage
class Total : public AddData
{
protected:
int total;
public:
void total_of_three_subjects()
{
total = subjects[0] + subjects[1] + subjects[2];
}
};
class Percentage : public Total //Class Percentage – Derived Class. Derived from class
Total
{
private:
float per;
public:
void calculate_percentage()
{
per=total/3;
}
void show_result()
{
cout<<"\n ------------------------------- \n";
cout<<"\n Percentage of a Student : "<<per;
}
};
int main()
{
Percentage p;
p.accept_details();
p.total_of_three_subjects();
p.calculate_percentage();
p.show_result();
return 0;
}

Output:

Q. Write a C++ program to find the area of circle using class circle which have following details:
a. Accept radius from the user
b. Calculate the area
c. Display the result
Answer:
Class is a blueprint for the object. Objects are instances of a class. Class holds its own data member
function, accessed and used by creating instance of that class. Object holds the data variables
declared in a class and the member function work on these class objects.
Following program is calculating the area of circle using class circle.
#include<iostream>
using namespace std;
class circle
{
float radius, area; //data members
public:
circle()
{
cout<<"\n Enter the value of Radius : ";
cin>>radius;
}
void calculate(); //member function
void display(); //member function
};
inline void circle :: calculate() //accessing data members of a class circle
{
area = 3.14 * radius * radius;
}
inline void circle :: display()
{
cout<<"\n Area of Circle : "<<area;
}
int main()
{
circle cr; //object created
cr.calculate(); //calling function
cr.display(); //calling function
return 0;
}

Output:

Q. Write a C++ program to define a class employee having members Emp-id, Emp-
name, basic salary and functions accept() and display(). Calculate DA=25% of
basic salary, HRA=800, I-tax=15% of basic salary. Display the payslip using
appropriate output format.

Answer:
Following program is defining a class Employee and calculating DA, HRA, tax of his/her basic
salary and also displaying the payslip of an employee.

#include<iostream>
using namespace std;
class Employee
{
int eid;
char ename[100];
float basic_salary, hra, da, i_tax, net_salary;
public:
void accept_details()
{ cout<<"\n Enter Employee Id : ";
cin>>eid;
cout<<"\n Enter Employee Name : ";
cin>>ename;
cout<<"\n Enter Basic Salary : ";
cin>>basic_salary;
hra = 800;
da = 0.25 * basic_salary;
i_tax = 0.15 * basic_salary;
net_salary = basic_salary + da + hra - i_tax;
}
void display_details()
{
cout<<"\n ----------------------- ";
cout<<"\n Employee Id : "<<eid;
cout<<"\n Employee Name : "<<ename;
cout<<"\n Basic Salary : "<<basic_salary;
cout<<"\n HRA : "<<hra;
cout<<"\n DA : "<<da;
cout<<"\n I-Tax : "<<i_tax;
cout<<"\n Net Salary : "<<net_salary;
}
};
int main()
{
Employee e;
e.accept_details();
e.display_details();
return 0;
}
Output:

Q. Write a class to represent a vector. Include member functions to perform the


following tasks:

1) To create the vector


2) To modify the value of given element.
3) To display the vector in the form (10, 20, 30,…)

Answer:
Following program is creating the vector and modifying the value of given element and also
displaying the vector in the form of 10, 20, 30. . . including the member functions modify(),
multiply() & display().

#include<iostream>
#include<stdio.h>
using namespace std;

class vector
{
int size;
int *coord;
public:
vector();
void modify();
void display();
void multiply();
};
vector::vector()
{
cout<<"\n Enter Number of Co-ordinates : ";
cin>>size;
coord=new int[size];
cout<<"\n Enter " << size << " Co-ordinates : \n";
for(int i=0; i<size; i++)
{
cout<<" ";
cin>>coord[i];
}
}
void vector::modify() //Function for Modifying the Co-ordinates
{
cout<<endl<<"\n Enter " << size << " New Co-ordinates : \n";
for(int i=0; i<size; i++)
{
cout<<" ";
cin>>coord[i];
}
}
void vector::multiply() //Multiplying the Co-ordinates
{
int num;
cout<<endl<<"\n Enter Number to Multiply : ";
cin>>num;
for(int i=0; i<size; i++)
{
coord[i]=coord[i]*num; //Multiplying the co-ordinates with the number
entered by the user
}
}
void vector::display() //Displaying the vector
{
cout<<"\n Vector : (";
for(int i=0; i<size; i++)
{
cout<<coord[i];
if(i!=size-1)
cout<<",";
}
cout<<")";
}
int main()
{
vector v;
v.display();
v.modify();
v.display();
v.multiply();
v.display();
return 0;
}

Output:
Q. Create a C++ class Date which contains:

- Day
- Month
- Year

Write necessary member functions to accept and display a date using >> and <<
operators.

Answer:

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class date
{
private:
int day, month, year;
public:
date(){}
friend void operator>>(istream &in, date &d); //Overloading >> operator
friend void operator<<(ostream &out, date &d) //Overloading << operator
{
out<<"\n Date : ";
out<<d.day;
out<<"/";
out<<d.month;
out<<"/";
out<<d.year;
}
∼ date(){}
};
void operator>>(istream &in, date &d)
{
cout<<"\n Enter Day : ";
in>>d.day;
cout<<"\n Enter Month : ";
in>>d.month;
cout<<"\n Enter Year : ";
cin>>d.year;
cout<<"\n ------------------";
switch(d.month)
{
case 1: //January
case 3: //March
case 5: //May
case 7: //July
case 8: //August
case 10: //October
case 12: //December
if(d.day>31)
{
cout<<"\n Invalid Days ";
exit(0);
}
break;
case 4: //April
case 6: //June
case 9: //September
case 11: //November
if(d.day>30)
{
cout<<"\n Invalid Days ";
exit(0);
}
break;
case 2:
//Function for February Month. Checking whether the year is leap year or
not.
if((d.year%100!=0&&d.year%4==0)||(d.year%400==0))
{
if(d.day>29)
{
cout<<"\n Invalid Days ";
exit(0);
}
}
else
{
if(d.day>28)
{
cout<<"\n Invalid Days ";
exit(0);
}}
break;
}}
int main()
{ date d;
cout<<"\n Enter Date \n";
cout<<"\n ------------------";
cin>>d;
cout<<d;
return 0;
}
Output:

Q. Define a class to represent a bank account. Include the following members:

Data members:
1) Name of the depositor
2) Account number
3) Type of account
4) Balance amount in the account.

Member functions:
1) To assign initial values
2) To deposit an amount
3) To withdraw an amount after checking the balance
4) To display name and balance.

Write a main program to test the program.

Answer:

#include<iostream>
#include<stdio.h>
#include<string.h>

using namespace std;

class bank
{
int acno;
char nm[100], acctype[100];
float bal;
public:
bank(int acc_no, char *name, char *acc_type, float balance) //Parameterized
Constructor
{
acno=acc_no;
strcpy(nm, name);
strcpy(acctype, acc_type);
bal=balance;
}
void deposit();
void withdraw();
void display();
};
void bank::deposit() //depositing an amount
{
int damt1;
cout<<"\n Enter Deposit Amount = ";
cin>>damt1;
bal+=damt1;
}
void bank::withdraw() //withdrawing an amount
{
int wamt1;
cout<<"\n Enter Withdraw Amount = ";
cin>>wamt1;
if(wamt1>bal)
cout<<"\n Cannot Withdraw Amount";
bal-=wamt1;
}
void bank::display() //displaying the details
{
cout<<"\n ----------------------";
cout<<"\n Accout No. : "<<acno;
cout<<"\n Name : "<<nm;
cout<<"\n Account Type : "<<acctype;
cout<<"\n Balance : "<<bal;
}
int main()
{
int acc_no;
char name[100], acc_type[100];
float balance;
cout<<"\n Enter Details: \n";
cout<<"-----------------------";
cout<<"\n Accout No. ";
cin>>acc_no;
cout<<"\n Name : ";
cin>>name;
cout<<"\n Account Type : ";
cin>>acc_type;
cout<<"\n Balance : ";
cin>>balance;
bank b1(acc_no, name, acc_type, balance); //object is created
b1.deposit(); //
b1.withdraw(); // calling member functions
b1.display(); //
return 0;
}

Output:

Q. Create a class staff having fields: Staff_id , name, salary. Write a menu driven
program for:

1) To accept the data


2) To display the data
3) To sort the data by name

Answer:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<cstdlib>
using namespace std;
class staff
{
int staff_id;
char name[20];
float salary;
public:
staff()
{

}
void accept()
{
cout<<"\n Enter Staff Id : ";
cin>>staff_id;
cout<<"\n Enter Staff Name : ";
cin>>name;
cout<<"\n Enter Salary : ";
cin>>salary;
}
void display();
friend void sort(char nm[], int n, staff *s);
void operator =(staff s1);
};
void staff::operator=(staff s1)
{
staff_id = s1.staff_id;
strcpy(name,s1.name);
salary = s1.salary;
}
void staff::display()
{
cout<<"\n Staff Id : "<<staff_id;
cout<<"\n Name : "<<name;
cout<<"\n Salary : "<<salary<<"\n";
}
void sort(char nm[], int n, staff *s) //Function for sorting the data by employee name
{
staff temp;
for(int i=0; i<n; i++)
{
for(int j=i+1; j<n; j++)
{
int r = strcmp(s[i].name,s[j].name);
if(r>0)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
}
}
int main()
{
int ch;
staff *s;
int n;
cout<<"\n Enter No.of Records You Want : ";
cin>>n;
s = new staff[n];
do
{
cout<<"\n 1. Accept Data ";
cout<<"\n 2. Display Data ";
cout<<"\n 3. Sort Data by Name ";
cout<<"\n 4. Exit: ";
cout<<"\n\n Enter Your Choice : ";
cin>>ch;
switch(ch)
{
case 1:
for(int i=0; i<n; i++)
{
cout<<"\n\n Enter Data for Employee " <<i+1<<"\n";
s[i].accept();
}
break;
case 2:
for(int i=0; i<n; i++)
{
s[i].display();
}
break;
case 3:
sort("a", n, s); //Passing parameter to sort() function
cout<<"\n Data is Sorted!!!\n";
break;
case 4:
exit(0);
default:
cout<<"\n Invalid Choice . . .";
}
}
while(ch!=4);
return 0;
}

Output:
Q. Create two classes dist1(meters, centimeters) and dist2(feet, inches). Accept two
distances from the user, one in meter and centimeter and other in feet and inches.
Find the sum and differences of the two distances. Display the result in, meters and
centimeters as well as feet and inches (using friend function). (1 inch = 2.54 cm and
1 feet = 0.30 m)

Answer:

#include<iostream>
using namespace std;

class dist2;
class dist1
{
public:
float mtr, cm;
public:
void accept()
{
cout<<"\n Enter Data in Meter & Centimeter : ";
cin>>mtr>>cm;
}
friend void diff(dist1 d1, dist2 d2);
friend void sum(dist1 d1, dist2 d2);
};
class dist2
{
float feet, inch;
public:
void accept()
{
cout<<"\n Enter Data in Feet & Inch : ";
cin>>feet>>inch;
}
friend void difference(dist1 d1, dist2 d2);
friend void sum(dist1 d1, dist2 d2);
};
void difference(dist1 d1,dist2 d2)
{
int n1, n2, n3, ans, m, c, f, in;
n1=d2.inch*2.54;
n2=d2.feet*0.30;
n3=d1.mtr*100;
ans=((d1.cm + n3) - (n1 + n2));
m=ans/100;
c=ans%100;
cout<<"\n --------------------------------------------------------------------";
cout<<"\n Difference in Meters & Centimeters = "<<m<<" mtrs & "<<c<<" cms";
f=m/0.30;
in=c/2.54;
cout<<"\n Difference in Feets & Inches = "<<f<<" feets & "<<in<<" inches";
}
void sum(dist1 d1, dist2 d2)
{
int n1, n2, n3, ans, m, c, f, in;
n1=d2.inch*2.54;
n2=d2.feet*0.30;
n3=d1.mtr*100;
ans=((d1.cm + n3) + (n1+n2));
m=ans/100;
c=ans%100;
cout<<"\n ------------------------------------------------------------------";
cout<<"\n Sum in Meters & Centimeters = "<<m<<" mtrs & "<<c<<" cms";
f=m/0.30;
in=c/2.54;
cout<<"\n Sum in Feets & Inches = "<<f<<" feets & "<<in<<" inches";
}
int main()
{
dist1 d1;
dist2 d2;
d1.accept();
d2.accept();
difference(d1,d2);
sum(d1,d2);
return 0;
}

Output:

---------------------------------------------------------------------------------------------------------------------

You might also like