Loop Assignment 1 — Find GCD of Two Numbers Using While Loop
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the GCD (Greatest Common Divisor) of Two Numbers Using a While Loop

📑 On this page:
  • What GCD Really Means
  • Euclid's Algorithm in Plain English
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What a GCD is, in everyday language — not just the textbook definition
  • How Euclid's algorithm works and why it's been trusted for over 2,000 years
  • How to write the modulo version in a compact while loop
  • How the repeated-subtraction version works (useful when the modulo is expensive)
  • How to handle zero and negative inputs without silent bugs
  • Why the loop is guaranteed to terminate

What GCD Really Means

The GCD of two numbers is the largest number that divides both of them without leaving a remainder. If you've ever cut a rectangular piece of paper into identical square tiles with the fewest cuts, you've worked out a GCD. A 24 by 36 cm sheet becomes 6 by 6 cm tiles because GCD(24, 36) = 6 — the largest square that fits whole-number times across both sides.

That's the mental picture to keep. The GCD is the largest square ruler that can measure both lengths exactly. When one number divides the other (say, 12 and 36), the smaller number is automatically the GCD, because it measures both. When they share no common factor other than 1 (like 8 and 15), the GCD is 1 — they're called coprime.

For a loop assignment, the interesting part isn't what the GCD is. It's how to compute it without trying every possible divisor. That's where Euclid comes in.

💡 In one line: GCD(a, b) is the largest number that divides both a and b with no remainder. Euclid's algorithm gets there without ever testing divisors one by one.

Diagram showing the Euclidean algorithm reducing two numbers via modulo until one reaches zero — the other is the GCD

Euclid's Algorithm in Plain English

The rule is short: the GCD of a and b is the same as the GCD of b and the remainder when a is divided by b. Repeat that swap until the remainder is zero. The last non-zero number is the GCD.

Why does it work? Because any number that divides both a and b must also divide a − q·b for any integer q — and a % b is exactly the leftover after subtracting as many bs as possible. So the common divisors of (a, b) are precisely the common divisors of (b, a % b). Same set, smaller numbers. The numbers shrink on every step, so the loop must stop — at zero.

Here's the trace for GCD(48, 18):

Step a b a % b Action
1481812a ← 18, b ← 12
218126a ← 12, b ← 6
31260a ← 6, b ← 0
—60—b is zero — stop. GCD = 6

Three iterations. A brute-force loop from 1 to min(48, 18) would take 18 iterations. For larger numbers the gap gets enormous — that's why Euclid's algorithm is still used in cryptography and computer algebra today.

Complete C Program

Program: GCD using a while loop (modulo version)

#include <stdio.h>

int main(void) {
    int a, b;

    printf("Enter two integers: ");
    if (scanf("%d %d", &a, &b) != 2) {
        printf("Invalid input.\n");
        return 1;
    }

    /* Work with absolute values so negatives don't break the modulo */
    if (a < 0) a = -a;
    if (b < 0) b = -b;

    if (a == 0 && b == 0) {
        printf("GCD of 0 and 0 is undefined.\n");
        return 0;
    }
    if (a == 0) {
        printf("GCD = %d\n", b);
        return 0;
    }
    if (b == 0) {
        printf("GCD = %d\n", a);
        return 0;
    }

    /* Euclid's algorithm — the loop shrinks the pair until b hits 0 */
    while (b != 0) {
        int rem = a % b;
        a = b;
        b = rem;
    }

    printf("GCD = %d\n", a);
    return 0;
}
                                    

And here is the same algorithm written as the repeated-subtraction version. It's slower for large gaps but easier to reason about if you're meeting the idea for the first time:

Same GCD, using repeated subtraction

/* Both a and b are positive at this point */
while (a != b) {
    if (a > b)
        a = a - b;
    else
        b = b - a;
}
/* Loop ends when a == b, and that common value is the GCD */
printf("GCD = %d\n", a);
                                    

Both versions arrive at the same answer. The modulo version usually runs in far fewer iterations, because a single a % b subtracts as many copies of b as fit. The subtraction version is the historical form of the algorithm, useful when modulo is costly on small microcontrollers.

Program Output

Enter two integers: 48 18
GCD = 6
                                

Try a few more: 100 and 75 give 25. 17 and 13 give 1 (they're coprime). 8 and 0 give 8. 0 and 0 print the "undefined" message. Each of these exercises a different branch of the input handling.

Step-by-Step Explanation

Let's follow the program through the 48 and 18 case, then look at the parts that often confuse beginners.

1. Reading input safely

scanf("%d %d", &a, &b) returns the number of values it successfully read. Checking for exactly 2 protects the program from being fed letters or an empty input. If the user types something that isn't a number, the program prints "Invalid input." instead of computing nonsense.

2. Absolute values

a % b in C keeps the sign of a, so -48 % 18 is -12, not 12. That can drive the loop into negative territory and produce a wrong answer. Converting both inputs to positive at the start sidesteps the problem entirely. The GCD is always non-negative, so this is safe.

3. The zero checks

Euclid's algorithm assumes both numbers are positive. The three early returns handle the edge cases before the loop: if both are zero, GCD is undefined; if one is zero, the GCD is the other number. (Yes, GCD(0, b) = |b| — every non-zero number divides 0 cleanly.) Without these checks, 0 % 0 would trigger undefined behaviour.

4. The while loop

The loop runs as long as b isn't zero. Inside, rem = a % b finds the leftover. Then we slide the pair: a = b and b = rem. Each iteration, b becomes strictly smaller (because a % b < b), so the loop cannot spin forever. When b finally hits zero, a holds the GCD.

For 48 and 18:

  1. rem = 48 % 18 = 12; a = 18, b = 12
  2. rem = 18 % 12 = 6; a = 12, b = 6
  3. rem = 12 % 6 = 0; a = 6, b = 0
  4. b == 0 — exit; a = 6 is the GCD

5. Why the loop must stop

Because a % b is always strictly less than b (as long as b > 0), each iteration replaces b with something smaller. The sequence of b values is a strictly decreasing sequence of non-negative integers, so it must reach 0 in finitely many steps. This is the same argument behind every "the algorithm terminates" proof you'll see for Euclid's method.

6. Why not start at the smaller number and count down?

You could: for (i = min(a, b); i >= 1; i--) if (a % i == 0 && b % i == 0) break;. That's simpler to read, and it's a fine first attempt. But for GCD(1,000,000, 999,999) it tests roughly a million candidates, while Euclid's algorithm finishes in about 20 steps. Euclid wins, every time, and that's why it's the algorithm taught — and asked about in interviews.

7. A hidden benefit: LCM for free

Once you have GCD, LCM is one multiplication away: LCM(a, b) = (a / GCD(a, b)) * b. Dividing before multiplying keeps the intermediate result small and avoids overflow. The LCM assignment on this site uses exactly that relationship — it's worth reading next.

🎯 Remember this: Euclid's algorithm says GCD(a, b) = GCD(b, a % b). Repeat until the second number is zero, and the first number is your answer. The loop is short, fast, and guaranteed to stop — and it's the same idea behind the LCM, coprime, and amicable-number programs in this series.

Frequently Asked Questions

1. Why does the loop stop when b becomes zero?

Because by then, a has absorbed all the shared factors. In each iteration we replace (a, b) with (b, a % b). The last non-zero b before the zero step is the GCD — and once we shift, that value sits in a. So when the loop exits, a is the answer.

2. What if the user enters negative numbers?

The program converts them to positive at the start with if (a < 0) a = -a;. C's % operator keeps the sign of the left operand, so -48 % 18 is -12 — that would push the loop into negative values and produce the wrong answer. Taking absolute values is the simplest fix. The GCD is always reported as a positive number.

3. Is the modulo version always faster than repeated subtraction?

In terms of iterations, almost always yes. a % b is equivalent to subtracting b repeatedly until the result is less than b, but it does the job in a single machine instruction on most CPUs. There is one exception: on a few small microcontrollers, division is emulated in software and can be much slower than a subtract loop. For those, the subtraction version may win.

4. What is GCD(0, 0)?

Mathematically, it's undefined. Every number divides 0, so there's no largest common divisor. The program prints "GCD of 0 and 0 is undefined." That's the honest answer — inventing 0 or 1 would be misleading. If you need to keep the code compact, returning 0 is a common convention, but a printed message is clearer for a teaching program.

5. Can I use a for loop instead of while?

Yes, but the syntax gets awkward because you don't know in advance how many iterations you'll need. Write for (; b != 0; ) { int rem = a % b; a = b; b = rem; } and it works, but a while loop is the more natural fit here. This is the general guideline: use while when you're repeating until a condition changes, and for when you know the number of iterations.

6. How is this used in real programs?

GCD shows up in reducing fractions, aligning memory or buffer sizes, determining the size of the smallest repeating unit in tiling problems, and — with the extended version — in modular inverses for RSA encryption. Whenever you need "the largest common chunk," the answer is somewhere in Euclid's algorithm.

💡 Tip: Once this program clicks, try solving it again using the repeated-subtraction loop above. You'll find you understand why the modulo version works once you've walked through the slower version by hand. Then move on to the LCM assignment — it builds directly on this one with a single extra line.

📖 Related Tutorials

  • 2. Find the LCM of Two Numbers Using a For Loop
  • 3. Check Whether Two Numbers Are Coprime Using a While Loop
  • 4. Find All Common Divisors of Two Numbers Using a For Loop
  • 5. GCD of Three Numbers Using Nested Loops
  • 30. Check Whether Two Integers Are Amicable Using a For Loop
  • While Loop
  • Do-while Loop
  • All 30 Loop Assignments

Previous Topic: -->> Loop Assignment Index — 30 Programs   ||   Next Topic: -->> 2. Find the LCM of Two Numbers Using a For Loop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.