Write a C program to reduce any fraction to least terms using while loop

Reducing a fraction to its lowest terms means finding the simplest form where the numerator and denominator have no common factors other than 1. This is achieved by dividing both numbers by their Greatest Common Divisor (GCD).

Syntax

while (condition) {
    // Find GCD and reduce fraction
}

Method 1: Using Euclidean Algorithm

This method uses the Euclidean algorithm to find the GCD efficiently −

#include <stdio.h>

int main() {
    int numerator, denominator, original_num, original_den;
    int temp, gcd;
    
    printf("Enter fraction (numerator/denominator): ");
    scanf("%d/%d", &numerator, &denominator);
    
    if (denominator == 0) {
        printf("Error: Denominator cannot be zero
"); return 1; } original_num = numerator; original_den = denominator; // Find GCD using Euclidean algorithm int a = numerator, b = denominator; while (b != 0) { temp = b; b = a % b; a = temp; } gcd = a; // Reduce fraction numerator = original_num / gcd; denominator = original_den / gcd; printf("Original fraction: %d/%d
", original_num, original_den); printf("Reduced fraction: %d/%d
", numerator, denominator); return 0; }
Enter fraction (numerator/denominator): 24/36
Original fraction: 24/36
Reduced fraction: 2/3

Method 2: Using Iterative GCD Finding

This approach finds the GCD by iterating from the smaller number down to 1 −

#include <stdio.h>

int main() {
    int num1, num2, gcd;
    
    printf("Enter numerator and denominator: ");
    scanf("%d %d", &num1, &num2);
    
    if (num2 == 0) {
        printf("Error: Denominator cannot be zero
"); return 1; } // Find GCD by checking divisibility gcd = (num1 < num2) ? num1 : num2; while (gcd > 1) { if (num1 % gcd == 0 && num2 % gcd == 0) { break; } gcd--; } printf("Original fraction: %d/%d
", num1, num2); printf("Reduced fraction: %d/%d
", num1 / gcd, num2 / gcd); return 0; }
Enter numerator and denominator: 48 72
Original fraction: 48/72
Reduced fraction: 2/3

Key Points

  • The Euclidean algorithm is more efficient with O(log min(a,b)) time complexity.
  • Always check for zero denominator to avoid division by zero error.
  • The iterative method has O(min(a,b)) time complexity but is easier to understand.

Conclusion

Both methods effectively reduce fractions to lowest terms using while loops. The Euclidean algorithm is preferred for larger numbers due to its superior efficiency in finding the GCD.

Updated on: 2026-03-15T13:44:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements