Question:1
C++ program using templates to take input for a number calculate and display its square, the number may be an int, float, or double
Sol:
#include<iostream>
#include<conio.h>
using namespace std;
template<class T>
T square(T n)
{
T s;
s=n*n;
return(s);
//or
//return(n*n);
}
//int square(int n);
//float square(float n);
//double square(double n);
int main()
{
int a1,a2;
float b1,b2;
double d1,d2;
//clrscr();
cout<<"Enter any number (int) ";
cin>>a1;
cout<<"Enter any number (float) ";
cin>>b1;
cout<<"Enter any number (double) ";
cin>>d1;
a2=square(a1);
cout<<"square of "<<a1<<" is "<<a2<<endl;
b2=square(b1);
cout<<"square of "<<b1<<" is "<<b2<<endl;
d2=square(d1);
cout<<"square of "<<d1<<" is "<<d2<<endl;
getch();
return(0);
}
Question:2
C++ program using templates to take input for a number calculate and display its cube, the number may be an int, float, or double
Sol:
#include<iostream>
#include<conio.h>
using namespace std;
template<class T>
T cube(T n)
{
T c;
c=n*n*n;
return(c);
//or
//return(n*n*n);
}
//int cube(int n);
//float cube(float n);
//double cube(double n);
int main()
{
int a1,a2;
float b1,b2;
double d1,d2;
//clrscr();
cout<<"Enter any number (int) ";
cin>>a1;
cout<<"Enter any number (float) ";
cin>>b1;
cout<<"Enter any number (double) ";
cin>>d1;
a2=cube(a1);
cout<<"cube of "<<a1<<" is "<<a2<<endl;
b2=cube(b1);
cout<<"cube of "<<b1<<" is "<<b2<<endl;
d2=cube(d1);
cout<<"cube of "<<d1<<" is "<<d2<<endl;
getch();
return(0);
}




