﻿ C exercises and solutions: C structure add fractions

C exercises and solutions: C structure add fractions

Write a C program to add two fractions and display the result fraction. Your program will prompt the user to input fraction 1 and fraction 2. The numerator and denominator of each fraction are input separately by space.  See the example output below:

Enter fraction 1(numerator denominator): 1 2
Enter fraction 2(numerator denominator): 2 5
Result: 9/10

Solution:

#include<stdio.h>
#include<conio.h>
typedef struct
{
int num;
int deno;

}Fract;

Fract sum(Fract,Fract);

int main()
{
int num1,deno1,num2,deno2;
printf("Enter fraction 1: numerator denominator:");
scanf("%d%d",&num1,&deno1);
printf("Enter fraction 2:numerator denominator:");
scanf("%d%d",&num2,&deno2);

Fract f1={num1, deno1}; // fraction 1
Fract f2 ={num2, deno2};//fraction 2
Fract result = sum(f1, f2);//sum the fractions
printf("Result=%d/%d",result.num,result.deno);  //display the result

getch();
return 0;
}
Fract sum(Fract f1, Fract f2)
{
Fract result={(f1.num * f2.deno) + (f2.num * f1.deno), f1.deno * f2.deno};
return result;

}