Question:3
C++ program using templates to take input for two numbers calculate and display its sum, the number may be an int, float, or double
Sol:
#include<iostream> #include<conio.h> using namespace std; template<class T> T sum(T n1,T n2) { T s; s=n1+n2; return(s); //or //return(n1+n2); } //int sum(int n1,int n2); //float sum(float n1,float n2); //double sum(double n1,double n2); int main() { int a1,a2,a3; float b1,b2,b3; double d1,d2,d3; //clrscr(); cout<<"Enter 2 numbers (int) "; cin>>a1>>a2; cout<<"Enter 2 numbers (float) "; cin>>b1>>b2; cout<<"Enter 2 numbers (double) "; cin>>d1>>d2; a3=sum(a1,a2); cout<<"sum of "<<a1<<" and "<<a2<<" is "<<a3<<endl; b3=sum(b1,b2); cout<<"sum of "<<b1<<" and "<<b2<<" is "<<b3<<endl; d3=sum(d1,d2); cout<<"sum of "<<d1<<" and "<<d2<<" is "<<d3<<endl; getch(); return(0); }
Question:4
C++ program using templates to take input for two numbers calculate and display their prod, the number may be an int, float, or double
Sol:
#include<iostream> #include<conio.h> using namespace std; template<class T> T prod(T n1,T n2) { T s; s=n1*n2; return(s); //or //return(n1*n2); } //int prod(int n1,int n2); //float prod(float n1,float n2); //double prod(double n1,double n2); int main() { int a1,a2,a3; float b1,b2,b3; double d1,d2,d3; //clrscr(); cout<<"Enter 2 numbers (int) "; cin>>a1>>a2; cout<<"Enter 2 numbers (float) "; cin>>b1>>b2; cout<<"Enter 2 numbers (double) "; cin>>d1>>d2; a3=prod(a1,a2); cout<<"prod of "<<a1<<" and "<<a2<<" is "<<a3<<endl; b3=prod(b1,b2); cout<<"prod of "<<b1<<" and "<<b2<<" is "<<b3<<endl; d3=prod(d1,d2); cout<<"prod of "<<d1<<" and "<<d2<<" is "<<d3<<endl; getch(); return(0); }