100% found this document useful (1 vote)
2K views51 pages

C++ Programs

This document contains C++ programs to demonstrate simple programming concepts like: - Calculating sum and average of three numbers - Raising a number to a positive power - Converting inches to yards, feet, and inches - Finding the ASCII value of a character - Adding two matrices It provides the full source code for each program to help learners understand how to code basic programs in C++. The programs cover topics like input/output, arithmetic operations, conditional statements, loops, functions, and arrays.

Uploaded by

kiran kumar
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
100% found this document useful (1 vote)
2K views51 pages

C++ Programs

This document contains C++ programs to demonstrate simple programming concepts like: - Calculating sum and average of three numbers - Raising a number to a positive power - Converting inches to yards, feet, and inches - Finding the ASCII value of a character - Adding two matrices It provides the full source code for each program to help learners understand how to code basic programs in C++. The programs cover topics like input/output, arithmetic operations, conditional statements, loops, functions, and arrays.

Uploaded by

kiran kumar
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/ 51

C++ Simple Programs

Prepared by:
M.Jagadeesh
1. Write a C++ Program to calculate sum and average of three numbers

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr() //to clear the screen
float a,b,c,sum,av;
cout<<“Enter three numbers:”;
cin>>a>>b>>c;

sum=a+b+c;
av=sum/3;
cout<<“nSUM=”<<sum;
cout<<“nAverage=”<<av;

getch(); //to stop the screen


}

2. Write a C++ Program to raise any number x to a positive power n

#include<iostream.h>
#include<conio.h>
#include<math.h> //for pow() function

void main()
{
clrscr();
int x,n,res;
cout<<“Enter value of x and n:”;
cin>>x>>n;

res=pow(x,n);
cout<<“nResult=”<<res;
getch();
}

3. Write a C++ Program to convert given inches into equivalent yard,feet and inches

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int y,f,i;
cout<<“Enter inches:”;
cin>>i;

y=i/432;
i=i%432;
f=i/12;
i=i%12;

cout<<“Yard=”<<y<<“nFeet=”<<f<<“nInches=”<<i;
getch();
}

4. Write a C++ Program to Find ASCII value of a character


#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char ch,c;
int cha;
cout<<“Enter a character:”;
cin>>ch;
cha=ch;
cout<<“nASCII value of “<<ch<<” is “<<cha;
c=ch+1; cha=c;
cout<<“nAdding one to the character:”<<“nASCII value of “<<c<<” is “<<cha;
getch();
}

5. Write a C++ Program to find Compound Interest


#include<iostream>
#include<math.h>
using namespace std;
int main()
{
float p,r,t,ci;
cout<<"Enter Principle, Rate and Time:\n";
cin>>p>>r>>t;
ci=p*pow((1+r/100),t);
cout<<"\nCompound Interest = "<<ci;
return 0;
}
Output
Enter Principle, Rate and Time:
1000
2
4
Compound Interest = 1082.43

6. Write a C++ Program to find Square Root of a number.


#include<iostream>
#include<math.h>
using namespace std;
int main()
{
float sq,n;
cout<<"Enter any number:";
cin>>n;
sq=sqrt(n);
cout<<"Square root of "<<n<<" is "<<sq;
return 0;
}
Output
Enter any number:9
Square root of 9 is 3

7. Write a C++ Program to Convert Days Into Years, Weeks and Days.

#include<iostream>
using namespace std;
int main()
{
int y,d,w;
cout<<"Enter No. of days:";
cin>>d;
y=d/365;
d=d%365;
w=d/7;
d=d%7;
cout<<"\nYears: "<<y<<"\nWeeks: "<<w<<"\nDays: "<<d;
return 0;
}

8. Write a C++ program to swap two numbers using macros

#include<iostream.h>
#include<conio.h>
#define SWAP(a,b) {int temp; temp=a; a=b; b=temp;}
void main()
{
clrscr();
int x,y;
cout<<“Enter two numbers:”;
cin>>x>>y;

cout<<“x=”<<x<<” y=”<<y;
SWAP(x,y);
cout<<“nx=”<<x<<” y=”<<y;
getch();
}

9. Write a C++ program to swap two numbers without using temp variable

#include<iostream.h>
#include<conio.h>void main()
{
clrscr();
int a,b;
cout<<“Enter value of a:”;
cin>>a;
cout<<“Enter value of b:”;
cin>>b;
a=a+b;
b=a-b;
a=a-b;
cout<<“na=”<<a;
cout<<“nb=”<<b;
getch();
}

if/else programs
10. Write a C++ Program to convert a lowercase alphabet to uppercase or vice-versa

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
cout<<“Enter any Alphabet:”;
cin>>ch;
if(ch>=’a’&&ch<=’z’)
{
cout<<“ntYou have entered a lowercase alphabet”;
ch=ch-32;
cout<<“nnThe uppercase alphabet is “<<ch;
}
else
{
cout<<“ntYou have entered an Uppercase alphabet”;
ch=ch+32;
cout<<“nnThe lowercase alphabet is “<<ch;
}
getch();
}

11. Write a C++ Program to Find Roots of Quadratic Equation

#include<iostream>
#include<math.h> //to calculate square root
using namespace std;
int main()
{
float root1,root2,a,b,c,d,imaginaryPart,realPart;
cout<<"Quadratic Equation is ax^2+bx+c=0";
cout<<"\nEnter values of a,b and c:";
cin>>a>>b>>c;

d=(b*b)-(4*a*c);

if(d>0)
{
cout<<"\nTwo real and distinct roots";
root1=(-b+sqrt(d))/(2*a);
root2=(-b-sqrt(d))/(2*a);
cout<<"\nRoots are "<<root1<<" and "<<root2;
}
else if(d==0)
{
cout<<"\nTwo real and equal roots";
root1=root2=-b/(2*a);
cout<<"\nRoots are "<<root1<<" and "<<root2;
}
else{
cout<<"\nRoots are complex and imaginary";
realPart = -b/(2*a);
imaginaryPart = sqrt(-d)/(2*a);
cout<<"\nRoots are "<<realPart<<"+"<<imaginaryPart<<"i and "<<realPart<<"-
"<<imaginaryPart<<"i";
}

return 0;
}

Output
Quadratic Equation is ax^2+bx+c=0
Enter values of a,b and c:3
4
1
Two real and distinct roots
Roots are -0.333333 and -1

12. Write a C++ Program to Check whether a year is Leap year or not

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int year;
cout<<“Enter Year(ex:1900):”;
cin>>year;
if(year%100==0)
{
if(year%400==0)
cout<<“nLeap Year”;
}
else
if(year%4==0)
cout<<“nLeap Year”;
else
cout<<“nNot a Leap Year”;
getch();
}

13. Write a C++ Program to Check Number is Odd or Even


#include<iostream>
using namespace std;
int main()
{
int a;
cout<<"enter the number:";
cin>>a;

if(a%2==0)
cout<<"\nEven number";
else
cout<<"\nOdd number";
return 0;
}

Loops Programs
14. Write a C++ Program to find the Reverse Number for a given number

#include<iostream>
using namespace std;
int main()
{
long n,rev=0,d;
cout<<"Enter any number:";
cin>>n;

while(n!=0)
{
d=n%10;
rev=(rev*10)+d;
n=n/10;
}
cout<<"The reversed number is "<<rev;
return 0;
}
15. Write a C++ Program to find the Reverse Number for a given number

#include<iostream>
using namespace std;
int main()
{
long n,rev=0,d;
cout<<"Enter any number:";
cin>>n;
while(n!=0)
{
d=n%10;
rev=(rev*10)+d;
n=n/10;
}
cout<<"The reversed number is "<<rev;
return 0;
}

16. Write a C++ program to check whether the given number is Prime Number or not.

#include<iostream>
using namespace std;
int main()
{
int n,i,flag=1;
cout<<"Enter any number:";
cin>>n;

for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=0;
break;
}
}

if(flag)
cout<<"\n"<<n<<" is a Prime number";
else
cout<<"\n"<<n<<" is not a Prime number";

return 0;
}
17. Write a C++ Program to Find Sum of Digits of a Given Number

#include<iostream>
using namespace std;
int main()
{
unsigned long i,p,n,sum=0;
cout<<"Enter any number:";
cin>>n;
while(n!=0)
{
p=n%10;
sum+=p;
n=n/10;
}
cout<<endl<<"Sum of digits is:"<<sum;
return 0;
}
Output
Enter any number:361
Sum of digits is:10

18. Write a C++ program to find the Factorial to a given number.

#include<iostream>
using namespace std;
int main()
{
unsigned long i,fac,n;
cout<<"Enter number: ";
cin>>n;

for(i=1,fac=1;i<=n;++i)
{
fac=i*fac;
}
cout<<"Factorial of "<<n<<" is: "<<fac;
return 0;
}

Output
Enter number: 5
Factorial of 5 is: 120

19. Write a C++ Program to Find Sum of First n Natural Numbers

#include<iostream>
using namespace std;
int main()
{
int i,n,sum=0;
cout<<"How many numbers? ";
cin>>n;

for(i=1;i<=n;++i)
{
sum+=i;
}
cout<<"Sum="<<sum;
return 0;
}

Output
How many numbers? 5
Sum=15

Functions Programs
20. Write a C++ Program to find cube of a number using function

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr(); //to clear screen
float cube(float); //function prototype
float a,cu;
cout<<“Enter any number:”;
cin>>a;
cu=cube(a); //function calling
cout<<“nCube of “<<a<<” is “<<cu;
getch();
}

float cube(float a)
{
float cu;
cu=a*a*a;
return(cu);
}

21. Write a C++ Program for Fibonacci Series Using Recursion

#include<iostream>
using namespace std;
int fibonacci(int n)
{
if((n==1)||(n==0))
{
return(n);
}
else
{
return(fibonacci(n-1)+fibonacci(n-2));
}
}

int main()
{
int n,i=0;
cout<<"Input the number of terms for Fibonacci Series:";
cin>>n;
cout<<"\nFibonacci Series is as follows\n";

while(i<n)
{
cout<<" "<<fibonacci(i);
i++;
}

return 0;
}
22. Write a C++ Program to do Addition,subtraction and multiplication of two numbers
using function

#include<iostream.h>
#include<conio.h>

int res;
void main()
{
clrscr();
int sum(int,int);
int sub(int,int);
int mul(int,int);
int a,b,m,su,s;
cout<<“Enter two numbers:”;
cin>>a>>b;

s=sum(a,b);
su=sub(a,b);
m=mul(a,b);
cout<<“Sum:”<<s<<“nSubtraction:”<<su<<“nMultiplication:”<<m;
getch();
}
sum(int a,int b)
{
res=a+b;
return(res);
}

sub(int a,int b)
{
res=a-b;
return(res);
}

mul(int a,int b)
{
res=a*b;
return(res);
}

23. Write a C++ program to swap values of two variables using pass by reference method

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int a,b;
void swap(int &,int &);
cout<<“Enter two values:”;
cin>>a>>b;
cout<<“nBefor swapping:na=”<<a<<“tb=”<<b;
swap(a,b);
cout<<“nnAfter swapping:na=”<<a<<“tb=”<<b;
getch();
}

void swap(int & x,int & y)


{
int temp;
temp=x;
x=y;
y=temp;
}
Array Programs
24. Write a C++ Program to Add Two Matrices

#include<iostream>
#include<process.h>

using namespace std;

int main()
{
int A[10][10],B[10][10],c[10][10];
int i,j,m,n,p,q;
cout<<"Enter no. of rows and cloumns of matrix A:";
cin>>m>>n;
cout<<"\nEnter no. of rows and columns of matrix B:";
cin>>p>>q;

if(m==p&&n==q)
cout<<"\n\nMatrices can be Added";
else
{
cout<<"\n\nMatrices can not Added";
exit(0);
}

cout<<"\nEnter matrix A row wise:";

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cin>>A[i][j];
}

cout<<"\nMatrix A:\n";

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<A[i][j]<<" ";
cout<<"\n";
}

cout<<"\nEnter Matrix B row wise:";


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cin>>B[i][j];
}

cout<<"\n\nMatrix B:\n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<B[i][j]<<" ";
cout<<"\n";
}

for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
c[i][j]=A[i][j]+B[i][j];
}

cout<<"\nSum of Matrices A and B:\n";


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
cout<<c[i][j]<<" ";
cout<<"\n";
}

return 0;
}

Output
Enter no. of rows and cloumns of matrix A:2
2
Enter no. of rows and columns of matrix B:2
2
Matrices can be Added
Enter matrix A row wise:4 5
37
Matrix A:
45
37
Enter Matrix B row wise:2 1
82
Matrix B:
21
82
Sum of Matrices A and B:
66
11 9

25. Write a C++ Program to find the Matrix Multiplication

#include<iostream>
using namespace std;
int main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
cout<<"Enter rows and columns of first matrix:";
cin>>m>>n;
cout<<"Enter rows and columns of second matrix:";
cin>>p>>q;

if(n==p)
{
cout<<"\nEnter first matrix:\n";
for(i=0;i<m;++i)
for(j=0;j<n;++j)
cin>>a[i][j];

cout<<"\nEnter second matrix:\n";


for(i=0;i<p;++i)
for(j=0;j<q;++j)
cin>>b[i][j];

cout<<"\nThe new matrix is:\n";


for(i=0;i<m;++i)
{
for(j=0;j<q;++j)
{
c[i][j]=0;
for(k=0;k<n;++k)
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
cout<<c[i][j]<<" ";
}
cout<<"\n";
}
}
else
cout<<"\nSorry!!!! Matrix multiplication can't be done";

return 0;
}
26. Write a C++ Program to Find Sum of Elements Above and Below Main Diagonal of
Matrix

#include<iostream>
using namespace std;
int main()
{
int arr[5][5],a=0,b=0,i,j,n;
cout<<"Enter size of matrix(max 5):";
cin>>n;
cout<<"Enter the matrix:\n";

for(i=0;i<n;++i)
for(j=0;j<n;++j)
cin>>arr[i][j];

for(i=0;i<n;++i)
for(j=0;j<n;++j)
if(j>i)
a+=arr[i][j];
else
if(i>j)
b+=arr[i][j];

cout<<"\nSum of elements above the diagonal:"<<a;


cout<<"\nSum of elements below the diagonal:"<<b;

return 0;
}

27. Write a C++ Program to Insert an Element in an Array

#include<iostream>
using namespace std;
int main()
{
int a[20],n,x,i,pos=0;
cout<<"Enter size of array:";
cin>>n;
cout<<"Enter the array in ascending order:\n";

for(i=0;i<n;++i)
cin>>a[i];

cout<<"\nEnter element to insert:";


cin>>x;

for(i=0;i<n;++i)
if(a[i]<=x&&x<a[i+1])
{
pos=i+1;
break;
}

for(i=n+1;i>pos;--i)
a[i]=a[i-1];

a[pos]=x;

cout<<"\n\nArray after inserting element:\n";

for(i=0;i<n+1;i++)
cout<<a[i]<<" ";

return 0;
}
28. Write a C++ Program to Find Largest and Second Largest Number in 2D Array

#include<iostream>
using namespace std;
int main()
{
int a[5][5],big1=1,big2=0,n,m,i,j;
cout<<"Enter no of rows and columns(max 5):";
cin>>m>>n;
cout<<"Enter the array:\n";

for(i=0;i<m;i++)
for(j=0;j<n;++j)
cin>>a[i][j];

for(i=0;i<m;++i)
for(j=0;j<n;++j)
{
if(a[i][j]>big1)
big1=a[i][j];
}
for(i=0;i<m;++i)
for(j=0;j<n;++j)
{
if(a[i][j]>big2&&a[i][j]<big1)
big2=a[i][j];
}

cout<<"\nLargest number:"<<big1;
cout<<"\nSecond largest number:"<<big2;

return 0;
}
Output
Enter no of rows and columns(max 5):3
3
Enter the array:
468
246
2 12 5
Largest number:12
Second largest number:8

29. Write a C++ Program for Bubble Sort


#include<iostream>
using namespace std;
int main()
{
int a[50],n,i,j,temp;
cout<<"Enter the size of array: ";
cin>>n;
cout<<"Enter the array elements: ";

for(i=0;i<n;++i)
cin>>a[i];

for(i=1;i<n;++i)
{
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}

cout<<"Array after bubble sort:";


for(i=0;i<n;++i)
cout<<" "<<a[i];

return 0;
}

30. Write a C++ Program to Delete an Element from Array

#include<iostream>
#include<process.h>
using namespace std;
int main()
{
int a[50],x,n,i,j,b[50];
cout<<"How many elements of Array you want to create?";
cin>>n;
cout<<"\nEnter elements of Array\n";

for(i=0;i<n;++i)
cin>>a[i];

cout<<"\nEnter element to delete:";


cin>>x;

for(i=0,j=0;i<n;++i)
{
if(a[i]!=x)
b[j++]=a[i];
}

if(j==n)
{
cout<<"\nSoory!!!Element is not in the Array";
exit(0);
}
else
{
cout<<"\nNew Array is ";
for(i=0;i<j;i++)
cout<<b[i]<<" ";
}
return 0;
}

Output
How many elements of Array you want to create?5
Enter elements of Array
14 8 3 6 9
Enter element to delete:6
New Array is 14 8 3 9

Class programs
31. Write a C++ program to find the volume of a box using class
#include <iostream>
using namespace std;

class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.height = 4.0;
Box1.length = 6.0;
Box1.breadth = 3.0;

// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 12.0;

// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

32. Write a C++ Program to enter the student details and print the student details.

#include <iostream>
using namespace std;
class stud
{
public:
char name[30],clas[10];
int rol,age;

void enter()
{
cout<<"Enter Student Name: "; cin>>name;
cout<<"Enter Student Age: "; cin>>age;
cout<<"Enter Student Roll number: "; cin>>rol;
cout<<"Enter Student Class: "; cin>>clas;
}

void display()
{
cout<<"\n Age\tName\tR.No.\tClass";
cout<<"\n"<<age<<"\t"<<name<<"\t"<<rol<<"\t"<<clas;
}
};

int main()
{
class stud s;
s.enter();
s.display();
cin.get();//use this to wait for a keypress
}
Array of objects program in C++
33. /*C++ program to create student class, read and print N student's details

#include <iostream>
using namespace std;

#define MAX 10

class student
{
private:
char name[30];
int rollNo;
int total;
float perc;
public:
//member function to get student's details
void getDetails(void);
//member function to print student's details
void putDetails(void);
};

//member function definition, outside of the class


void student::getDetails(void){
cout << "Enter name: " ;
cin >> name;
cout << "Enter roll number: ";
cin >> rollNo;
cout << "Enter total marks outof 500: ";
cin >> total;

perc=(float)total/500*100;
}

//member function definition, outside of the class


void student::putDetails(void){
cout << "Student details:\n";
cout << "Name:"<< name << ",Roll Number:" << rollNo << ",Total:" << total <<
",Percentage:" << perc;
}

int main()
{
student std[MAX]; //array of objects creation
int n,loop;
cout << "Enter total number of students: ";
cin >> n;

for(loop=0;loop< n; loop++){
cout << "Enter details of student " << loop+1 << ":\n";
std[loop].getDetails();
}

cout << endl;

for(loop=0;loop< n; loop++){
cout << "Details of student " << (loop+1) << ":\n";
std[loop].putDetails();
}

return 0;
}

34. Write a C++ program to convert time from seconds to HH:MM:SS format using class

/*C++ program to create class to read and add two times.*/


#include <iostream>
using namespace std;

class Time
{
private:
int hours;
int minutes;
int seconds;

public:
void getTime(void);
void putTime(void);
void addTime(Time T1,Time T2);
};

void Time::getTime(void)
{
cout << "Enter time:" << endl;
cout << "Hours? "; cin>>hours;
cout << "Minutes? "; cin>>minutes;
cout << "Seconds? "; cin>>seconds;
}
void Time::putTime(void)
{
cout << endl;
cout << "Time after add: ";
cout << hours << ":" << minutes << ":" << seconds << endl;
}

void Time::addTime(Time T1,Time T2)


{

this->seconds=T1.seconds+T2.seconds;
this->minutes=T1.minutes+T2.minutes + this->seconds/60;;
this->hours= T1.hours+T2.hours + (this->minutes/60);
this->minutes %=60;
this->seconds %=60;
}
int main()
{
Time T1,T2,T3;
T1.getTime();
T2.getTime();
//add two times
T3.addTime(T1,T2);
T3.putTime();

return 0;
}

35. Write a C++ program that illustrates Friend function


/*C++ program to demonstrate example of friend function with class.*/
#include <iostream>
using namespace std;

class Number
{
private:
int a;
public:
void getNum(int x);
//declaration of friend function
friend void printNum(Number NUM);
};
//class member function definitions
void Number::getNum(int x)
{
a=x;
}

//friend function definition, no need of class name with SRO (::)


void printNum(Number NUM)
{
cout << "Value of a (private data member of class Number): " << NUM.a;

int main()
{
Number nObj; //Object declaration
nObj.getNum(1000);
printNum(nObj);
return 0;
}
36. Write a C++ program to illustrates the constructor concept
#include<iostream>
using namespace std;
class Marks
{
public:
int maths;
int science;
//Default Constructor
Marks() {
maths=0;
science=0;
}
display() {
cout << "Maths : " << maths <<endl;
cout << "Science :" << science << endl;
}
};
int main() {
//invoke Default Constructor
Marks m;
m.display();
return 0;
}

37. Write a C++ program to demonstrates the parameterized constructor


#include <iostream>
using namespace std;

class Demo
{
private:
int A;
int B;
int C;
public:
//parameterized constructor
Demo(int A, int B, int C);
void set(int A, int B, int C);
void print();
};

Demo::Demo(int A, int B, int C)


{
this->A = A;
this->B = B;
this->C = C;
}

void Demo::set(int A, int B, int C)


{
this->A = A;
this->B = B;
this->C = C;
}

void Demo::print()
{
cout<<"Value of A : "<<A<<endl;
cout<<"Value of B : "<<B<<endl;
cout<<"Value of C : "<<C<<endl;
}

int main()
{
//Parameterized Constructor called when object created
Demo obj = Demo(1,1,1);
//here, 1,1,1 will be assigned to A,B and C
//printing the value
obj.print();
//changing the value using set function
obj.set(10,20,30);
//printing the values
obj.print();

return 0;
}

38. Write a C++ program that demonstrates the virtual fuction.


#include<iostream.h>
#include<conio.h>

class base {
public:
virtual void show() {
cout << "\n Base class show:";
}

void display() {
cout << "\n Base class display:";
}
};

class drive : public base {


public:

void display() {
cout << "\n Drive class display:";
}

void show() {
cout << "\n Drive class show:";
}
};
void main() {
clrscr();
base obj1;
base *p;
cout << "\n\t P points to base:\n";

p = &obj1;
p->display();
p->show();

cout << "\n\n\t P points to drive:\n";


drive obj2;
p = &obj2;
p->display();
p->show();
getch();
}

39. Write a C++ program to demonstrates the copy constructor

#include<iostream>
using namespace std;

class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }

// Copy constructor
Point(const Point &p2) {x = p2.x; y = p2.y; }

int getX() { return x; }


int getY() { return y; }
};

int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here

// Let us access values assigned by constructors


cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}

40. Write a C++ program to illustrates the Binary Operator Overloading

#include<iostream.h>
#include<conio.h>
class complex {
int a, b;
public: void getvalue() {
cout << "Enter the value of Complex Numbers a,b:";
cin >> a>>b;
}
complex operator+(complex ob) {
complex t;
t.a = a + ob.a;
t.b = b + ob.b;
return (t);
}
complex operator-(complex ob) {
complex t;
t.a = a - ob.a;
t.b = b - ob.b;
return (t);
}
void display() {
cout << a << "+" << b << "i" << "\n";
}
};
void main() {
clrscr();
complex obj1, obj2, result, result1;

obj1.getvalue();
obj2.getvalue();

result = obj1 + obj2;


result1 = obj1 - obj2;
cout << "Input Values:\n";
obj1.display();
obj2.display();
cout << "Result:";
result.display();
result1.display();
getch();
}

41. Write a C++ program to illustrates the Unary increment (++) and decrement (--)
operator overloading

/*C++ program for unary increment (++) and decrement (--) operator overloading.*/

#include<iostream>
using namespace std;

class NUM
{
private:
int n;

public:
//function to get number
void getNum(int x)
{
n=x;
}
//function to display number
void dispNum(void)
{
cout << "value of n is: " << n;
}
//unary ++ operator overloading
void operator ++ (void)
{
n=++n;
}
//unary -- operator overloading
void operator -- (void)
{
n=--n;
}
};
int main()
{
NUM num;
num.getNum(10);

++num;
cout << "After increment - ";
num.dispNum();
cout << endl;

--num;
cout << "After decrement - ";
num.dispNum();
cout << endl;
return 0;
}

42. Write a C++ program to Add two objects using binary plus (+) operator overloading

/*C++ program to add two objects using binary plus (+) operator overloading.*/

#include<iostream>
using namespace std;

class NUM
{
private:
int n;
public:
//function to get number
void getNum(int x)
{
n=x;
}
//function to display number
void dispNum(void)
{
cout << "Number is: " << n;
}
//add two objects - Binary Plus(+) Operator Overloading
NUM operator +(NUM &obj)
{
NUM x; //create another object
x.n=this->n + obj.n;
return (x); //return object
}
};

int main()
{
NUM num1,num2,sum;
num1.getNum(10);
num2.getNum(20);

//add two objects


sum=num1+num2;

sum.dispNum();
cout << endl;
return 0;
}

43. Write a C++ program to calculate the payroll system of the employees using single
inheritance.

#include<iostream.h>
#include<conio.h>
class emp {
public:
int eno;
char name[20], des[20];

void get() {
cout << "Enter the employee number:";
cin>>eno;
cout << "Enter the employee name:";
cin>>name;

cout << "Enter the designation:";


cin>>des;
}
};
class salary : public emp {
float bp, hra, da, pf, np;
public: void get1() {
cout << "Enter the basic pay:";
cin>>bp;
cout << "Enter the Humen Resource Allowance:";
cin>>hra;
cout << "Enter the Dearness Allowance :";
cin>>da;
cout << "Enter the Profitablity Fund:";
cin>>pf;
}
void calculate() {
np = bp + hra + da - pf;
}
void display() {
cout << eno << "\t" << name << "\t" << des << "\t" << bp << "\t" << hra << "\t" << da
<< "\t" << pf << "\t" << np << "\n";
}
};
void main() {
int i, n;
char ch;
salary s[10];
clrscr();
cout << "Enter the number of employee:";

cin>>n;
for (i = 0; i < n; i++) {
s[i].get();
s[i].get1();
s[i].calculate();
}
cout << "\ne_no \t e_name\t des \t bp \t hra \t da \t pf \t np \n";
for (i = 0; i < n; i++) {
s[i].display();
}
getch();
}

44. C++ program to demonstrate example of multilevel inheritance

#include <iostream>
using namespace std;

//Base Class : class A


class A
{
private:
int a;
public:
void get_a(int val_a)
{
a=val_a;
}

void disp_a(void)
{
cout << "Value of a: " << a << endl;
}
};

//Here Class B is base class for class C


//and Derived class for class A
class B: public A
{
private:
int b;
public:
//assign value of a from here
void get_b(int val_a, int val_b)
{
//assign value of a by calling function of class A
get_a(val_a);
b=val_b;
}

void disp_b(void)
{
//display value of a
disp_a();
cout << "Value of b: " << b << endl;
}
};

//Here class C is derived class and B is Base class


class C: public B
{
private:
int c;
public:
//assign value of a from here
void get_c(int val_a, int val_b,int val_c)
{
/*** Multilevel Inheritance ***/
//assign value of a, bby calling function of class B and Class A
//here Class A is inherited on Class B, and Class B in inherited on Class B
get_b(val_a,val_b);
c=val_c;
}

void disp_c(void)
{
//display value of a and b using disp_b()
disp_b();
cout << "Value of c: " << c << endl;
}
};

int main()
{
//create object of final class, which is Class C
C objC;

objC.get_c(10,20,30);
objC.disp_c();

return 0;
}

45. Write a C++ program that demonstrates the multiple inheritance

#include <iostream>
using namespace std;
// Base class Shape
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Base class PaintCost
class PaintCost {
public:
int getCost(int area) {
return area * 70;
}
};
// Derived class
class Rectangle: public Shape, public PaintCost {
public:
int getArea() {
return (width * height); }};
int main(void) {
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
// Print the total cost of painting
cout << "Total paint cost: $" << Rect.getCost(area) << endl;
return 0;
}

46. Write a C++ program to create Employee and Student inheriting from Person using
Hierarchical Inheritance

#include <iostream>
#include <conio.h>

using namespace std;

class person
{
char name[100],gender[10];
int age;
public:
void getdata()
{
cout<<"Name: ";
fflush(stdin); /*clears input stream*/
gets(name);
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
}

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

class student: public person


{
char institute[100], level[20];
public:
void getdata()
{
person::getdata();
cout<<"Name of College/School: ";
fflush(stdin);
gets(institute);
cout<<"Level: ";
cin>>level;
}
void display()
{
person::display();
cout<<"Name of College/School: "<<institute<<endl;
cout<<"Level: "<<level<<endl;
}
};

class employee: public person


{
char company[100];
float salary;
public:
void getdata()
{
person::getdata();
cout<<"Name of Company: ";
fflush(stdin);
gets(company);
cout<<"Salary: Rs.";
cin>>salary;
}
void display()
{
person::display();
cout<<"Name of Company: "<<company<<endl;
cout<<"Salary: Rs."<<salary<<endl;
}
};

int main()
{
student s;
employee e;
cout<<"Student"<<endl;
cout<<"Enter data"<<endl;
s.getdata();
cout<<endl<<"Displaying data"<<endl;
s.display();
cout<<endl<<"Employee"<<endl;
cout<<"Enter data"<<endl;
e.getdata();
cout<<endl<<"Displaying data"<<endl;
e.display();
getch();
return 0;
}
Pointers:
47. Write a C++ program to illustrate the pointers in C++

#include <iostream>
using namespace std;
int main () {
int var1;
char var2[10];
cout << "Address of var1 variable: ";
cout << &var1 << endl;
cout << "Address of var2 variable: ";
cout << &var2 << endl;
return 0;
}

48. Write a C++ program to read and print the values on screen
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable

ip = &var; // store address of var in pointer variable

cout << "Value of var variable: ";


cout << var << endl;

// print the address stored in ip pointer variable


cout << "Address stored in ip variable: ";
cout << ip << endl;

// access the value at the address available in pointer


cout << "Value of *ip variable: ";
cout << *ip << endl;

return 0;
}
this pointer
49. Write a C++ program to illustrate the this pointer.
#include<iostream>
using namespace std;
/* local variable is same as a member's name */
class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};

int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
Run on IDE
Output:
x=20

50. Write a C++ program to calculate the total marks of a student using the virtual base
class
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the base class student.
Step 3: Declare and define the functions getnumber() and putnumber().
Step 4: Create the derived class test virtually derived from the base class student.
Step 5: Declare and define the function getmarks() and putmarks().
Step 6: Create the derived class sports virtually derived from the base class student.
Step 7: Declare and define the function getscore() and putscore().
Step 8: Create the derived class result derived from the class test and sports.
Step 9: Declare and define the function display() to calculate the total.
Step 10: Create the derived class object obj.
Step 11: Call the function get number(),getmarks(),getscore() and display().
Step 12: Stop the program.

PROGRAM:
#include<iostream.h>
#include<conio.h>
class student
{
int rno;
public:
void getnumber()
{
cout<<"Enter Roll No:";
cin>>rno;
}
void putnumber()
{
cout<<"\n\n\tRoll No:"<<rno<<"\n";
}
};
class test:virtual public student
{
public:
int part1,part2;
void getmarks()
{
cout<<"Enter Marks\n";
cout<<"Part1:";
cin>>part1;
cout<<"Part2:";
cin>>part2;
}
void putmarks()
{
cout<<"\tMarks Obtained\n";
cout<<"\n\tPart1:"<<part1;
cout<<"\n\tPart2:"<<part2;
}
};
class sports:public virtual student
{
public:
int score;
void getscore()
{
cout<<"Enter Sports Score:";
cin>>score;
}
void putscore()
{
cout<<"\n\tSports Score is:"<<score;
}
};

class result:public test,public sports


{
int total;
public:
void display()
{
total=part1+part2+score;
putnumber();
putmarks();
putscore();
cout<<"\n\tTotal Score:"<<total;
}
};

void main()
{
result obj;
clrscr();
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
getch();
}
Output:
Enter Roll No: 200
Enter Marks
Part1: 90
Part2: 80
Enter Sports Score: 80
Roll No: 200
Marks Obtained
Part1: 90
Part2: 80
Sports Score is: 80
Total Score is: 250
51. Write a C++ program that illustrates the virtual functions
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the base class base.
Step 3: Declare and define the virtual function show().
Step 4: Declare and define the function display().
Step 5: Create the derived class from the base class.
Step 6: Declare and define the functions display() and show().
Step 7: Create the base class object and pointer variable.
Step 8: Call the functions display() and show() using the base class object and pointer.
Step 9: Create the derived class object and call the functions display() and show() using the
derived class object and pointer.
Step 10: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
class base
{
public:
virtual void show()
{
cout<<"\n Base class show:";
}
void display()
{
cout<<"\n Base class display:" ;
}
};
class drive:public base
{
public:
void display()
{
cout<<"\n Drive class display:";
}
void show()
{
cout<<"\n Drive class show:";
}
};

void main()
{
clrscr();
base obj1;
base *p;
cout<<"\n\t P points to base:\n" ;
p=&obj1;
p->display();
p->show();
cout<<"\n\n\t P points to drive:\n";
drive obj2;
p=&obj2;
p->display();
p->show();
getch();
}
Output:
P points to Base
Base class display
Base class show
P points to Drive
Base class Display
Drive class Show
52. Write a C++ program to swap the numbers using the concept of function template
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the template class.
STEP 3: Declare and define the functions to swap the values.
STEP 4: Declare and define the functions to get the values.
STEP 5: Read the values and call the corresponding functions.
STEP6: Display the results.
STEP 7: Stop the program.
PROGRAM:
#include<iostream.h>
#include<conio.h>
template<class t>
void swap(t &x,t &y)
{
t temp=x;
x=y;
y=temp;
}
void fun(int a,int b,float c,float d)
{
cout<<"\na and b before swaping :"<<a<<"\t"<<b;
swap(a,b);
cout<<"\na and b after swaping :"<<a<<"\t"<<b;
cout<<"\n\nc and d before swaping :"<<c<<"\t"<<d;
swap(c,d);
cout<<"\nc and d after swaping :"<<c<<"\t"<<d;
}
void main()
{
int a,b;
float c,d;
clrscr();
cout<<"Enter A,B values(integer):";
cin>>a>>b;
cout<<"Enter C,D values(float):";
cin>>c>>d;
fun(a,b,c,d);
getch();
}
Output:
Enter A, B values (integer): 10 20
Enter C, D values (float): 2.50 10.80
A and B before swapping: 10 20
A and B after swapping: 20 10
C and D before swapping: 2.50 10.80
C and D after swapping: 10.80 2.50
Class Templates
53. Write a C++ program to illustrates the concept of class templates

#include <iostream.h>
#include <vector>
template <typename T>
class MyQueue
{
std::vector<T> data;
public:
void Add(T const &);
void Remove();
void Print();
};

template <typename T> void MyQueue<T> ::Add(T const &d)


{
data.push_back(d);
}

template <typename T> void MyQueue<T>::Remove()


{
data.erase(data.begin( ) + 0,data.begin( ) + 1);
}

template <typename T> void MyQueue<T>::Print()


{
std::vector <int>::iterator It1;
It1 = data.begin();
for ( It1 = data.begin( ) ; It1 != data.end( ) ; It1++ )
cout << " " << *It1<<endl;
}
//Usage for C++ class templates
void main()
{
MyQueue<int> q;
q.Add(1);
q.Add(2);

cout<<"Before removing data"<<endl;


q.Print();

q.Remove();
cout<<"After removing data"<<endl;
q.Print();
}

54. Write a C++ program that illustrates the division by zero exception.

#include <iostream>
using namespace std;

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}

int main () {
int x = 50;
int y = 0;
double z = 0;

try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}

Output:
Division by zero condition!

55. C++ program to divide two numbers using try catch block.
#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
int a,b;
cout << "Enter 2 numbers: ";
cin >> a >> b;
try
{
if (b != 0)
{
float div = (float)a/b;
if (div < 0)
throw 'e';
cout << "a/b = " << div;
}
else
throw b;

}
catch (int e)
{
cout << "Exception: Division by zero";
}
catch (char st)
{
cout << "Exception: Division is less than 1";
}
catch(...)
{
cout << "Exception: Unknown";
}
getch();
return 0;
}
Output
Enter 2 numbers: 8 5
a/b = 1.6

Enter 2 numbers: 9 0
Exception: Division by zero

Enter 2 numbers: -1 10
Exception: Division is less than 1

You might also like