- Write a C++ program to add two distances in inch and feet using structure variable.

In this C++ program, we will add two distances in inch and feet system using a user defined structure. We created a custom structure name "Distance" which contains two member variables feet and inch.

struct Distance{ int feet; float inch; };

We will use variable of structure Distance, to store the distance in inch and feet. Here is the feet to inch conversion equation:

**1 feet = 12 inches.**

## C++ Program to Add Two Distances in Inch and Feet

// C++ program to add two distances in inch feet using structure #include <iostream> using namespace std; // Structure storing distance in inch and feet struct Distance{ int feet; float inch; }; int main() { Distance d1, d2, d3; cout << "Enter first distance as [feet inch]\n"; cin >> d1.feet >> d1.inch; cout << "Enter second distance as [feet inch]\n"; cin >> d2.feet >> d2.inch; // Adding d1 and d2 and storing the sum in d3 d3.feet = d1.feet + d2.feet; d3.inch = d1.inch + d2.inch; // NOTE : 12 inch = 1 feet // If feet > 12 then feet = feet%12 and inch++ if(d3.inch > 12){ d3.feet++; d3.inch = d3.inch - 12; } cout << "Total distance = " << d3.feet << " feet, " << d3.inch <<" inches"; return 0; }Output

Enter first distance as [feet inch] 5 7 Enter second distance as [feet inch] 3 8 Total distance = 9 feet, 3 inches

In this program, we first ask user to enter two distances in inch-feet system and store it in Distance variable d1 and d2. To find the sum of d1 and d2, we add the inch and feet member of both structure variables and store it in inch and feet members of d3 respectively. If the value of inch is greater than 12 than we convert it to feet.

**Recommended Posts**