Small but important programs using classes and objects
Question:13
C++ program to take input for two numbers, calculate and print their sum?
Sol:
#include <iostream>
#include<conio.h>
using namespace std;
class sum
{
private:
int a,b,c;
public:
void read();
void cal();
void show();
};
void sum::read()
{
cout<<"Enter 2 nos ";
cin>>a>>b;
}
void sum::cal()
{
c=a+b;
}
void sum::show()
{
cal();
cout<<"Sum = "<<c<<endl;
}
int main()
{
sum s;
s.read();
s.show();
return(0);
}
/* Output */ Enter 2 nos 10 20 Sum = 30
Question:14
C++ program to take input for 3 numbers check and print the largest number.
Sol:
#include <iostream>
#include<conio.h>
using namespace std;
class largest
{
private:
int a,b,c,m;
public:
void read();
void cal();
void show();
};
void largest::read()
{
cout<<"Enter 3 nos ";
cin>>a>>b>>c;
}
void largest::cal()
{
if(a>b && a>c)
m=a;
else
if(b>c)
m=b;
else
m=c;
}
void largest::show()
{
cal();
cout<<"Max no = "<<m<<endl;
}
int main()
{
largest la;
la.read();
la.show();
return(0);
}
/* Output */ Enter 3 nos 10 25 63 Max no = 63
Question:15
C++ program to take input for 2 nos, calculate and print their sum, prod and diff?
Sol:
#include <iostream>
#include<conio.h>
using namespace std;
class sample
{
private:
int a,b,s,p,d;
public:
void read();
void cal();
void show();
};
void sample::read()
{
cout<<"Enter 2 nos ";
cin>>a>>b;
}
void sample::cal()
{
s=a+b;
p=a*b;
if(a>b)
d=a-b;
else
d=b-a;
}
void sample::show()
{
cal();
cout<<"Sum = "<<s<<endl;
cout<<"Prod = "<<p<<endl;
cout<<"Diff = "<<d<<endl;
}
int main()
{
sample s;
s.read();
s.show();
return(0);
}
/* Output */ Enter 2 nos 25 63 Sum = 88 Prod = 1575 Diff = 38
Question:16
C++ program to take input for a number calculate and print its square and cube?
Sol:
#include <iostream>
#include<conio.h>
using namespace std;
class sample
{
private:
int n,s,c;
public:
void read();
void cal();
void show();
};
void sample::read()
{
cout<<"Enter any no ";
cin>>n;
}
void sample::cal()
{
s=n*n;
c=n*n*n;
}
void sample::show()
{
cal();
cout<<"Square = "<<s<<endl;
cout<<"Cube = "<<c<<endl;
}
int main()
{
sample s;
s.read();
s.show();
return(0);
}
/* Output */ Enter any no 5 Square = 25 Cube = 125




