# Program to add two fractions in C

You’re given A/B and C/D. You will have to calculate A/B + C/D and answer it as E/F.

Input specification
On the first line you’re given the test case number N. Then there will be N line following. Each line consist of 4 integers with two “/” in the middle. For example: the each line will be “A/B C/D”.

Output specification
For every test case, print out the sum of the given two fractions in the format: "numerator/denominator".

My code

#include <stdio.h>

int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}

int main()
{
int T;
scanf("%d", &T);

for (int i=1; i<=T; i++)
{
int num1, den1;
int num2, den2;
scanf("%d%*c%d %d%*c%d", &num1,&den1,&num2,&den2);

int num3, den3;
den3 = gcd(den1,den2);
den3 = (den1*den2)/den3;
num3 = (num1)*(den3/den1) + (num2)*(den3/den2);
printf("Case %d: %d/%d\n", i, num3, den3);
}

return 0;
}

• Looks good to me. I'd suggest a few minor changes. I wouldn't assign an intermediate value (the gcd) to the den3 variable. Instead I'd either inline the expression into the final den3 assignment or introduce another variable. And maybe I'd change from int to a long or long long to accomodate bigger numbers. Aug 11, 2017 at 19:37

### Overflow bug

If you use the input:

1
1/100000 2/100000


You get the result:

Case 1: 0/14100


The problem is with this line:

    den3 = (den1*den2)/den3;


Here, all three variables are 100000. But den1*den2 overflows an integer. It would be better to write this as:

    den3 = (den1/den3)*den2;


This expression will work as long as the common denominator fits in an int. However, it will still overflow when the common denominator is larger than what fits in an int. For this reason, you might want to use long long variables to avoid the problem.

### Simplify the result?

If you use the input:

1
1/4 1/4


the answer the program gives is:

Case 1: 2/4


This is correct, but the answer could also be simplified to 1/2. This is purely a cosmetic suggestion, since the specification didn't say the answer had to be reduced to its simplest form.