Algorithm


Define a Structure:
Create a structure named Distance with members feet and inches.

Input Distances:
Create a function inputDistance that takes a Distance structure as a parameter.
Inside the function, prompt the user to input the feet and inches values for the distance.

Display Distance:
Create a function displayDistance that takes a const Distance& parameter.
Inside the function, display the feet and inches values of the distance.

Add Distances:
Create a function addDistances that takes two const Distance& parameters and returns a Distance structure.
Inside the function, add the corresponding feet and inches values of the two distances.
If the sum of inches is 12 or more, adjust by subtracting 12 and incrementing the feet.

Main Function:
In the main function, declare three Distance variables: distance1, distance2, and sum.
Call inputDistance for distance1 and distance2 to input the values.
Call addDistances with distance1 and distance2 as arguments and store the result in sum.
Display the original distances and the sum using displayDistance.

Code Examples

#1 Code Example- Add Distances Using Structures

Code - C++ Programming

#include <iostream>
using namespace std;

struct Distance {
    int feet;
    float inch;
}d1 , d2, sum;

int main() {
    cout << "Enter 1st distance," << endl;
    cout << "Enter feet: ";
    cin >> d1.feet;
    cout << "Enter inch: ";
    cin >> d1.inch;

    cout << "\nEnter information for 2nd distance" << endl;
    cout << "Enter feet: ";
    cin >> d2.feet;
    cout << "Enter inch: ";
    cin >> d2.inch;

    sum.feet = d1.feet+d2.feet;
    sum.inch = d1.inch+d2.inch;

    // changing to feet if inch is greater than 12
    if(sum.inch > 12) {
        // extra feet
        int extra = sum.inch / 12;

        sum.feet += extra;
        sum.inch -= (extra * 12);
    } 

    cout << endl << "Sum of distances = " << sum.feet << " feet  " << sum.inch << " inches";
    return 0;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter 1st distance,
Enter feet: 6
Enter inch: 3.4
Enter information for 2nd distance
Enter feet: 5
Enter inch: 10.2
Sum of distances = 12 feet 1.6 inches
Advertisements

Demonstration


C++ Programing Example to Add Two Distances (in inch-feet) System Using Structures-DevsEnv