Write a program to find GCD of two numbers.
✅ 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 outputTernary operator
Compact conditional to find minimum of two numbers
No comments:
Post a Comment