Add two fractions in C

Write a C program to Add two fractions.

In this C program we will find  sum of two fraction using C

To find the sum of two fractions we will be using the concept of LCM and GCD.

For example: we have to find the sum of 6/2 and 16/3

Firstly the LCM of 2 and 3 will be found. Using the LCM we will convert the numerators i.e. 6 and 16 into digits that can be added and sum of those digits is found, lastly normalization is done using the GCD of sum and LCM.

Add two fractions in C programming

Working:-

Step 1. Start.

Step 2.Initialize variables of numerator and denominator 

Step 3. Take user input of two fraction 

Step 4. Find numerator using this condition (n1*d2) +(d1*n2 ) where n1,n2 are numerator and d1 andd d2 are denominator .

Step 5. Find denominator using this condition (d1*d2) for lcm.

Step 6. Calculate GCD of a this new numerator and denominator .

Step 7. Display a two value of this condition x/gcd,y/gcd);

Step 8. Stop.

 

 

C Program:-

#include <stdio.h>
int main()
{
//for initialize variables
int numerator1, denominator1,numerator2,denominator2,x,y,c,gcd_no;
//To take user input of numerators and denominators
printf("\nEnter the numerator for 1st number : ");
scanf("%d",&numerator1);
printf("\nEnter the denominator for 1st number : ");
scanf("%d",&denominator1);
printf("\nEnter the numerator for 2nd number : ");
scanf("%d",&numerator2);
printf("\nEnter the denominator for 2nd number : ");
scanf("%d",&denominator2);
//numerator
x=(numerator1*denominator2)+(denominator1*numerator2);
//denominator
y=denominator1*denominator2;
// Trick part. Reduce it to the simplest form by using gcd.
for(c=1; c <= x && c <= y; ++c)
{
if(x%c==0 && y%c==0)
gcd_no = c;
}
//To display fraction of givien numerators and denominators
printf("\nThe added fraction is %d/%d ",x/gcd_no,y/gcd_no);
printf("\n");
return 0;
}

Output:-

Please Login/Signup to comment