﻿ C++ exercises and solutions: Structure fractions

# C++ exercises and solutions: Structure fractions

## C++ structure exercise: add fractions

Exercise:  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. You will need to use a C++ structure to define a fraction. The structure has two members: numerator and denominator.

Enter fraction 1(numerator denominator): 1 2

Enter fraction 2(numerator denominator): 2 5

Result: 9/10

Solution:

#include<iostream>
#include<conio.h>
using namespace std;
struct Fract
{
int num;
int deno;

};

Fract sum(Fract,Fract);

int main()
{
int num1,deno1,num2,deno2;
cout<<"Enter fraction 1: numerator denominator:";
cin>>num1>>deno1;
cout<<"Enter fraction 2:numerator denominator:";
cin>>num2>>deno2;

Fract f1={num1, deno1};/* 1/2 */
Fract f2 ={num2, deno2};/* 2/5 */
Fract result = sum(f1, f2);//sum the fractions
cout<<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;

}