Write a function named convertToLowestTerms that inputs two integer parameters by reference named numerator and denominator. The function should treat these variables as a fraction and reduce them to lowest terms. For example, if numerator is 20 and denominator is 60, then the function should change the variables to 1 and 3, respectively. This will require finding the greatest common divisor for the numerator and denominator then dividing both variables by that number. If the denominator is zero, the function should return false , otherwise the function should return true . Write a test program that uses convertToLowestTerms to reduce and output several fractions.
PROGRAM CODE:
//Header section
#include <iostream>
using namespace std;
// Function to find the greatest common divisor (GCD) using Euclid's algorithm
int findGCD(int a, int b)
{
if (b == 0)
{
return a;
}
return findGCD(b, a % b);
}
// Function to reduce a fraction to its lowest terms
bool convertToLowestTerms(int& numerator, int& denominator)
{
// Check for division by zero
if (denominator == 0)
{
return false;
}
// Find the greatest common divisor (GCD)
int gcd = findGCD(numerator, denominator);
// Reduce the fraction by dividing both numerator and denominator by the GCD
numerator /= gcd;
denominator /= gcd;
return true;
}
//Program begins with a main method
int main()
{
//Declare variables
int numerator, denominator;
// Test case 1
numerator = 20;
denominator = 60;
if (convertToLowestTerms(numerator, denominator))
{
cout << "Fraction 20/60 reduced to lowest terms: " << numerator << "/" << denominator <<endl;
} else
{
cout << "Invalid fraction! Denominator cannot be zero." <<endl;
}
// Test case 2
numerator = 8;
denominator = 12;
if (convertToLowestTerms(numerator, denominator)) {
cout << "Fraction 8/12 reduced to lowest terms: " << numerator << "/" << denominator <<endl;
} else {
cout << "Invalid fraction! Denominator cannot be zero." <<endl;
}
// Test case 3
numerator = 15;
denominator = 5;
if (convertToLowestTerms(numerator, denominator)) {
cout << "Fraction 15/5 reduced to lowest terms: " << numerator << "/" << denominator <<endl;
} else {
cout << "Invalid fraction! Denominator cannot be zero." <<endl;
}
return 0;
}
OUTPUT OF THE PROGRAM CODE:
Enter the start time in military notation (HHMM): 2000
Enter the end time in military notation (HHMM): 40000
The difference in minutes between the start and end times is: 22800 minutes