You are on page 1of 3

C++ programing Lab

File name:program6.cpp

PROGRAM NO. 6
Objective: - Create a class rational which represents a numerical value by two double values- NUMERATOR &DENOMINATOR. Include the following public member functions. Constructors with no arguments (defalult). Constructors with two arguments. Void reduce () that reduces the rational number by eliminating the highest common factor between the numerator and denominator. Overload + operator to add two rational numbers Overload>> operator to enable input through cin. Overload<< operator tto enable output through cout. Write a main() to test all the functions in the class. #include<iostream> //Header File using namespace std; class rational //Class Definition { private: //Declaring the private members int num, den, hcf; public: //Declaring the public members rational(){} //Default Constructor rational(int n, int d) //Parameterized Constructor { num=n; //Assigning the value of n to num den=d; //Assigning the value of d to den } void reduce(int n1, int d1); //Function Declaration void display(); //Function Declaration rational operator+(rational& r2); friend istream& operator>>(istream& cin,rational& r); friend ostream& operator<<(ostream& cout,rational& r); }; void rational::reduce(int n1, int d1) { if(n1%d1==0) //Calculating HCF { hcf=d1; } else { reduce(d1,(n1%d1)); num/=hcf; den/=hcf; } } void rational::display() {
SBIT/CSE/IV/C++ PROGRAMING/CSE-206-F CSE/10/409

C++ programing Lab

cout<<"\nNumerator="<<num; cout<<"\nDenominator="<<den; } rational rational::operator+(rational& r2) { rational r3; r3.den=den*r2.den; r3.num=((r3.den/den)*num+(r3.den/r2.den)*r2.num); reduce(r3.num,r3.den); return(r3); } ostream& operator<<(ostream& cout,rational& r) { cout<<"Rational Number : "<<r.num<<"/"<<r.den; cout<<"\n\n\n"; return(cout); } istream& operator>>(istream& cin,rational& r) { cin>>r.num>>r.den; return(cin); } main() { int num,den; rational r3; cout<<"\nEnter 1st rational number:"; cout<<"\nNumerator:"; cin>>num; cout<<"\nDenominator:"; cin>>den; rational r1(num,den); r1.reduce(num,den); cout<<"\nEnter 2nd rational number:"; cout<<"\nNumerator:"; cin>>num; cout<<"\nDenominator:"; cin>>den; rational r2(num,den); r2.reduce(num,den); r3=r1+r2; cout<<"\nAfter Addtion of two rational numbers the new rational number is:\n"; r3.display(); rational r4; cout<<"\nTo examine << & >> operator. Enter num and den separately.\n"; cin>>r4; cout<<r4; }
SBIT/CSE/IV/C++ PROGRAMING/CSE-206-F CSE/10/409

C++ programing Lab

OUTPUT

SBIT/CSE/IV/C++ PROGRAMING/CSE-206-F

CSE/10/409

You might also like