C++ program to calculate GCD














































C++ program to calculate GCD




Description:

This program is to calculate GCD of two numbers. User enter two numbers if two numbers are positive then find
GCD and display the GCD otherwise display invalid input. In this program i am use data member, member
function and constructor of a GCD class.


Program(gcd.cpp):


#include<iostream>

using namespace std;

class gcd

{

            private:

                        int a,b;//data member

           public:

                         gcd(int x, int y)//constructor

                        {

                                    a=x;b=y;

                        }

                        int gcd_function()//member function

                        {

                                    int t,r;

                                    if(a==0 || b==0)

                                        return 0;

                                   else if(a<b)

                                    {

                                                t=a;

                                                a=b;

                                                b=t;

                                    }

                                    r=a%b;

                                    while(r!=0)

                                    {

                                               a=b;

                                               b=r;

                                               r=a%b;

                                   }

                                    return b;                                    

                        }


};

int main()

{

            int x,y;

            cout<<"Enter two numbers: ";

            cin>>x>>y;

            if(x>=0 && y>=0)

            {

                       gcd g(x,y);// Creation of object

                       cout<<"Result of GCD is: "<<g.gcd_function();//calling member function

            }

            else

               cout<<"Invalid Input";

            return 0;

}



/*



OUTPUT:

            1:         Enter two numbers: 5 2

                        Result of GCD is: 1

            2:         Enter two numbers: 12 36

                        Result of GCD is: 12

            3:         Enter two numbers: 0 5

                        Result of GCD is: 0

            4:         Enter two numbers: -7 8

                        Invalid Input

*/



                


More Articles of Sabyasachi Paul:

Name Views Likes
C++ program to calculate GCD 660 1

Comments