This blog is under construction

Monday 8 July 2013

C program to simplify the given fraction using GCF

Write a C program to simplify the given fraction using Greatest Common Factor.


  #include <stdio.h>
  int main() {
        int x1, x2, gcd;

        /* input fraction from the user */
        printf("Enter the value for x and y(x/y):");
        scanf("%d%d", &x1, &x2);

        if (x1 < x2) {
                gcd = x1;
        } else {
                gcd = x2;
        }

        /* if numerator is 0, fraction is 0.  If deno is 0, infinity */
        if (x1 == 0 || x2 == 0) {
                printf("Simplified fraction is %s\n", x1?"Infinity":"0");

        }

        /* calculate the gcd */
        while (gcd > 1) {
                if (x1 % gcd == 0 && x2 % gcd == 0)
                        break;
                gcd--;
        }

        /* simplify the fraction and print the output */
        printf("Simplified fraction %d/%d\n", x1 / gcd, x2 / gcd);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for x and y(x/y):100 25
  Simplified fraction 4/1





See Also:

2 comments: