Question:2
C++ program using class 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> class sample { private: T n1,n2,n3; public: void get(); void disp(); void cal(); }; template<class T> void sample<T>::get() { cout<<"Enter 2 numbers "; cin>>n1>>n2; } template<class T> void sample<T>::cal() { n3=n1*n2; } template<class T> void sample<T>::disp() { cal(); cout<<"prod is "<<n3<<endl; } int main() { //clrscr(); sample <int> s1; sample <float> s2; cout<<"for int values"<<endl; s1.get();s1.disp(); cout<<"for float values"<<endl; s2.get();s2.disp(); getch(); return(0); }
Question:3
C++ program using class templates to take input for two numbers calculate and display their sum, prod and difference. The number may be int, float, or double.
Sol:
#include<iostream> #include<conio.h> using namespace std; template<class T> class sample { private: T n1,n2,s,p,d; public: void get(); void disp(); void cal(); }; template<class T> void sample<T>::get() { cout<<"Enter 2 numbers "; cin>>n1>>n2; } template<class T> void sample<T>::cal() { s=n1+n2; p=n1*n2; if(n1>n2) d=n1-n2; else d=n2-n1; } template<class T> void sample<T>::disp() { cal(); cout<<"sum = "<<s<<endl; cout<<"prod = "<<p<<endl; cout<<"diff = "<<d<<endl; } int main() { //clrscr(); sample <int> s1; sample <float> s2; cout<<"for int values"<<endl; s1.get();s1.disp(); cout<<"for float values"<<endl; s2.get();s2.disp(); getch(); return(0); }