Sunday, 17 August 2025

Write a program to find GCD of two numbers.

Write a program to find GCD of two numbers.

gcd_calculator.c
#include <stdio.h>

int main() {
    int a, b, i, gcd;

    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    // Find the minimum of a and b
    int min = (a < b) ? a : b;

    for(i = 1; i <= min; i++) {
        if(a % i == 0 && b % i == 0) {
            gcd = i;
        }
    }

    printf("GCD of %d and %d is %d\n", a, b, gcd);

    return 0;
}

✅ Step-by-Step Explanation

🔹 1. Input

  • User enters two numbers (say a = 48, b = 18)
  • scanf() reads both integers from standard input

🔹 2. Find the smaller number

  • GCD can never be greater than the smaller number
  • Ternary operator (a < b) ? a : b determines the minimum

🔹 3. Check common divisors

for(i = 1; i <= min; i++) {
    if(a % i == 0 && b % i == 0) {
        gcd = i;
    }
}
  • Loop from 1 to the smaller number
  • Modulo operator % checks divisibility
  • When both numbers are divisible by i, update gcd

🔹 4. Output

  • After the loop ends, gcd holds the largest common divisor
  • printf() displays the final result

🖨️ Example Run

Input:

Enter two numbers: 48 18

Output:

GCD of 48 and 18 is 6

📌 Key Concepts Covered

Loop (for)
To check all possible divisors from 1 to the smaller number
Modulo operator %
To test divisibility of both numbers by the current index
Decision making (if)
Conditional statement to update GCD when common divisor found
Basic I/O
scanf() for input and printf() for output
Ternary operator
Compact conditional to find minimum of two numbers

No comments:

Post a Comment

Total Pageviews

Search This Blog

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display() ...