Archive

Archive for January 25, 2010

C++ Program to implement Generic Classes for user defined maths library – Q25

January 25, 2010 Leave a comment

Q25. Program to implement Generic Classes for user defined maths library:

Create a user defined maths class for implementing following functions using the concept of generic classes – SUM, N_ROOT, PRODUCT, POWER

… from College notes (BCA/MCA assignments):

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

template <class T>
class Cmath{
	private:
		T n1, n2, n3;
	public:
		void getData();
		void Sum();
		void nRoot();
		void Product();
		void Power();
	};

template <class T>
void Cmath<T> :: getData(){
	cout<<"\n Enter 1st Number : ";
	cin>>n1;
	cout<<"\n Enter 2nd Number : ";
	cin>>n2;
	}

template <class T>
void Cmath<T> :: Sum(){
	n3 = n1 + n2;
	cout<<"\n Sum = "<<n3;
	}

template <class T>
void Cmath<T> :: nRoot(){
	n3 = sqrt(n1);
	cout<<"\n Sq Root of "<<n1<<" = "<<n3;
	n3 = sqrt(n2);
	cout<<"\n Sq Root of "<<n2<<" = "<<n3;
	}

template <class T>
void Cmath<T> :: Product(){
	n3  = n1 * n2;
	cout<<"\n Product = "<<n3;
	}

template <class T>
void Cmath<T> :: Power(){
	n3 = pow(n1, n2);
	cout<<"\n Power = "<<n3;
	}

void main(){
	int ch;
	Cmath<int> Obj_i;
	Cmath<float> Obj_f;
	while(1){
		clrscr();
		cout<<"\n Generic Classes";
		cout<<"\n ~~~~~~~~~~~~~~~\n";
		cout<<"\n 1 -> Sum.";
		cout<<"\n 2 -> Root.";
		cout<<"\n 3 -> Product.";
		cout<<"\n 4 -> Power.";
		cout<<"\n 5 -> Exit.";
		cout<<"\n\n Enter your choice: ";
		cin>>ch;
		switch(ch){
			case 1:	// Sum.
				cout<<"\n Integer:- ";
				Obj_i.getData();
				Obj_i.Sum();
				cout<<"\n Floating:- ";
				Obj_f.getData();
				Obj_f.Sum();
				break;
			case 2:	// Root.
				cout<<"\n Integer:- ";
				Obj_i.getData();
				Obj_i.nRoot();
				cout<<"\n Floating:- ";
				Obj_f.getData();
				Obj_f.nRoot();
				break;
			case 3:	// Root.
				cout<<"\n Integer:- ";
				Obj_i.getData();
				Obj_i.Product();
				cout<<"\n Floating:-";
				Obj_f.getData();
				Obj_f.Product();
				break;
			case 4:	// Power.
				cout<<"\n Integer:- ";
				Obj_i.getData();
				Obj_i.Power();
				cout<<"\n Floating:-";
				Obj_f.getData();
				Obj_f.Power();
				break;
			case 5:	// Exit.
				exit(1);
			} // end of switch.
		getch();
		} // end of while.
	} // end of main.

 

Output:

Generic Classes

1 -> Sum.
2 -> Root.
3 -> Product.
4 -> Power.
5 -> Exit.

Enter your choice: 1

Integer:-
Enter 1st Number : 23
Enter 2nd Number : 32

Sum = 55

Floating:-
Enter 1st Number : 23.22
Enter 2nd Number : 32.45

Sum = 55.669998

Generic Classes

1 -> Sum.
2 -> Root.
3 -> Product.
4 -> Power.
5 -> Exit.

Enter your choice: 4

Integer:-
Enter 1st Number : 2
Enter 2nd Number : 5

Power = 32

Floating:-
Enter 1st Number : 23.44
Enter 2nd Number : 4.5

Power = 1461535.25


Advertisement
Categories: Cpp Tags: , ,