Friday, July 19, 2013

C Programming: Adding Fractions and Reducing the Sum to Lowest Term

Leave a Comment
C Programming: Adding Fractions and Reducing the Sum to Lowest Term. This program shows you how to make a program that adds two fraction numbers and reduce their sum to lowest term. This also shows how to return an entire array from a function.

#include <stdio.h>
#include <conio.h>


int * addFrac(int [], int []);
int main()
{
    int frac1[2], frac2[2];
    int *fsum;
  
    printf("***This Program Adds Two Fraction Numbers***\n\n");
    printf("Enter first fraction number: ");
    scanf("%d/%d", &frac1[0], &frac1[1]);
    printf("Enter second fraction number: ");
    scanf("%d/%d", &frac2[0], &frac2[1]);
  
    fsum = addFrac(frac1, frac2);
    printf("\nThe sum of %d/%d and %d/%d is: %d/%d", frac1[0], frac1[1], frac2[0], frac2[1], *fsum, *(fsum+1));
 
    getch();
    return 0;
}


int * addFrac(int frac1[], int frac2[])
{
    int sum[2], i = 2;
  
    sum[0] = frac1[0] * frac2[1] + frac2[0] * frac1[1];
    sum[1] = frac1[1] * frac2[1];
 
    for(;;)
    { 
       if(sum[0] == sum[1])
       {
                 sum[0] = 1;
                 sum[1] = 1;
                 break;
       }
       if(sum[0] > sum[1])
       {
            if(i > sum[0])
            {
                 break;
            }
       }
       if(sum[1] > sum[0])
       {
            if(i > sum[1])
            {
                 break;
            }
       }  
       if(sum[0] % i == 0 && sum[1] % i == 0)
       {
              sum[0] /= i;
              sum[1] /= i;
              i--;
       }
       i++;
    }
  
    return sum;
}

Here's the output of the program: 



0 comments:

Post a Comment