C Programming Tutorial

Advertisements

Write program to display the gcd (greatest common divisior) of a given number in C++



       #include<iostream.h>
       #include<conio.h>
       void main()
       {
              int num1,num2,i,gcd=1; 
              clrscr();

              cout<<"\nEnter 1st number : "; 
              cin>>num1;

              cout<<"\nEnter 2nd number : "; 
              cin>>num2;
              
              for(i=2; i<=num1 && i<=num2; i++)
              {
                     if(num1%i == 0 && num2%i==0)
                           gcd=i;
              }
              
              cout<<"The gcd is : "<<gcd;

              getch();
       }

   Output : 

              Enter 1st number : 36
              Enter 2nd number : 72
              The gcd is : 36




Advertisement