This tutorial will teach you how to find the GCD (Greatest Common Divisor) or HCF of two numbers in C. To understand this example, you should have knowledge of the following C programming topics.
The GCD(Greatest Common Divisor) of two integers is the largest integer that can exactly divide both numbers (without a remainder). Example: HCF of 12 and 18 is 6.
1. C Program to Find GCD of two Numbers using while loop and if..else Statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <stdio.h> int main() { int num1, num2; printf("Enter 2 positive integers:\n"); scanf("%d %d", &num1, &num2); while (num1 != num2) { if (num1 > num2) num1 -= num2; else num2 -= num1; } printf("GCD (Greatest Common Divisor): %d", num1); return 0; } |
Output:
Enter 2 positive integers:
12
18
GCD (Greatest Common Divisor): 6
2. C Program to Find GCD of two Numbers using for loop and if Statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> int main() { int num1, num2, i, gcd; printf("Enter 2 integers:\n"); scanf("%d %d", &num1, &num2); for(i = 1; i <= num1 && i <= num2; ++i) { // Checks if i is factor of both integers if(num1%i == 0 && num2%i == 0) gcd = i; } printf("GCD of %d and %d: %d", num1, num2, gcd); return 0; } |
Output:
Enter 2 positive integers:
12
18
GCD of 12 and 18: 6