c
  1. c-program-to-find-gcd-of-two-numbers

Program to Find GCD of Two Numbers - (C Programs)

Heading

GCD (Greatest Common Divisor) of two numbers is the largest number that divides both of them perfectly, without leaving any remainder. In this program, we'll learn how to find the GCD of two numbers using C Programming Language.

Example

#include <stdio.h>

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

    printf("Enter first number: ");
    scanf("%d", &num1);

    printf("Enter second number: ");
    scanf("%d", &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 is: %d", num1, num2, gcd);

    return 0;
}

Output

Enter first number: 16
Enter second number: 24
GCD of 16 and 24 is: 8

Explanation

In this program, we first take input from the user for two numbers to find their GCD. We then use a for-loop to check for all numbers from 1 to the minimum of the two input numbers, whether they are factors of both inputs.

If a number is a factor of both inputs, we store it as the GCD. Finally, we print the GCD of the two inputs to the console using printf() function.

Use

This program can be used by programmers, students, and professionals to calculate the GCD of two numbers through C programming language.

Summary

In summary, the program to find the GCD of two numbers using C Programming Language takes input from the user for two numbers, uses a for-loop to check for factors of both inputs and stores the highest common factor as the GCD, and outputs the GCD. This program can be used for various applications in fields such as Mathematics, Computer Science, and many others.

Published on: