A Program to Calculate the GCD of Two Integers

In this example, we are giving a program to calculate the GCD(greatest common divisor) of given two integers.


Program to calculate the GCD:

  1. #include <stdio.h>
  2. int main()
  3. {
  4. int n1, n2, i, gcd;
  5. printf("Enter two positive integers: ");
  6. scanf("%d %d", &n1, &n2);
  7. for(i=1; i <= n1 && i <= n2; ++i)
  8. {
  9. if(n1%i==0 && n2%i==0)
  10. gcd = i;
  11. }
  12. printf("GCD of %d and %d = %d", n1, n2, gcd);
  13. return 0;
  14. }

Output:

Enter two positive integers: 49
7
GCD of 49 and 7 = 7