Q:

C++ Greatest common divisor loop

I tried to write a program which shows Greatest common divisor and It doesn't work properly, Could you help me figure where the problem is?
I have to write it by while or do while.
Thanks in advance!
#include<iostream>
using namespace std;
int main()
{
    int num1,num2,mod,div;
    cout<<"Enter 2 numbers:"<<endl;
    cin>>num1>>num2;
    if (num1>=num2)
    {
     do{
        mod=0;
        mod= num1%num2;
        div= num1/num2;
        num1=num2;
        num2=mod;

     }while(mod!=0);
     cout<<div<<endl;
    }
    else if (num2>=num1)
    {
        do{
            mod=0;
            mod= num2%num1;
            div=num2/num1;
            num2=num1;
            num1=mod;

        }while(mod!=0);
        cout<<div<<endl;
    }
    return 0;
}

A:

The GCD in your logic is not div but num1 in the if branch and num2 in the else branch.
Computation of div is useless for the final result. It is useful only if you wish to produce debug output.
I recommend creating a function and avoiding duplicated logic.
int gcd(int num1, int num2)
{
   int mod = 0;

   if ( num1 < num2 )
   {
      return gcd(num2, num1)
   }

   do {
      mod = num1%num2;
      num1 = num2;
      num2 = mod;
   } while ( mod != 0 );

   return num1;
}

and use it from main as:
int main()
{
    int num1,num2;
    cout<<"Enter 2 numbers:"<<endl;
    cin>>num1>>num2;
    cout << "GCD: " << gcd(num1, num2) << endl;
}

