Discussion: More Simple
Execute the code to understand the output and gain insights into simplifying a fraction using C.
We'll cover the following...
Run the code
Now, it's time to execute the code and observe the output.
#include <stdio.h> int main() { int n, d, larger, smaller, diff; printf("Enter a fraction (nn/nn): "); scanf("%d/%d", &n, &d); // Check if the denominator is zero if (d == 0) { printf("Error: Denominator cannot be zero.\n"); return 1; // Exit the program with an error code } printf("%d/%d = ", n, d); larger = n > d ? n : d; smaller = n < d ? n : d; diff = larger - smaller; while (diff != larger) { larger = smaller > diff ? smaller : diff; smaller = smaller == larger ? diff : smaller; diff = larger - smaller; } if (diff > 1) printf("%d/%d\n", n / diff, d / diff); else printf("%d/%d\n", n, d); return 0; }
C code for the given puzzle
Understanding the output
The code requires that you input two integers in the form of a fraction, such as 21/63
. Here's the output:
Enter a fraction (nn/nn):21/63 = 1/3
Code output
The fraction is reduced—simplified—if it can be. When the fraction can’t be simplified, the original fraction is returned as output.