This blog is under construction

Sunday 7 July 2013

C program to add two fractions

Write a C program to add two fractions.


  #include <stdio.h>
  int main () {
        int x1, y1, x2, y2, x3, y3, div, i;

        /* get the inputs for first fraction from user */
        printf("Enter the value for x1 and y1(x1/y1):");
        scanf("%d%d", &x1, &y1);

        /* get the inputs for second fraction from user */
        printf("Enter the value for x2 and y2(x2/y2):");
        scanf("%d%d", &x2, &y2);

        /* calculating the numerator */
        x3 = (x1 * y2) + (x2 * y1);

        /* calculating the numerator */
        y3 = (y1 * y2);

        /* simplifying the fraction */
        if (x3 > y3) {
                div = y3;
        } else {
                div = x3;
        }

        for (i = div; i > 0; i--) {
                if (x3 % i == 0 && y3 % i == 0) {
                        x3 = x3 / i;
                        y3 = y3 / i;
                }
        }

        /* print the output */
        printf("Sum of given two fraction is %d/%d\n", x3, y3);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for x1 and y1(x1/y1):5 2
  Enter the value for x2 and y2(x2/y2):7 3
  Sum of given two fraction is 29/6





See Also:

No comments:

Post a Comment