Program to Find GCD of Two Numbers

Description:
This program finds the Greatest Common Divisor (GCD) of two numbers. The GCD is the largest positive integer that divides both numbers without leaving a remainder. It demonstrates the use of loops and conditional logic to find common divisors.

Usage:
The user inputs two numbers, and the program finds and prints their GCD.

Code:

C
#include <stdio.h>

int main() {
    int num1, num2, i, gcd;

    // Asking user to input two integers
    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);

    // Finding the GCD of two numbers
    for (i = 1; i <= num1 && i <= num2; ++i) {
        if (num1 % i == 0 && num2 % i == 0) {
            gcd = i;
        }
    }

    printf("GCD of %d and %d is %d\n", num1, num2, gcd);

    return 0;
}

Explanation:

  • The GCD is found by checking for the largest integer that divides both numbers without a remainder.
  • A for loop iterates from 1 to the smaller of the two numbers.

Test here:

Leave a Reply

Your email address will not be published. Required fields are marked *