A structure is a collection of items of different data types. It is very useful in creating complex data structures with different data type records. A structure is defined with the struct keyword.
An example of a structure is as follows −
struct DistanceFI {
int feet;
int inch;
};The above structure defines a distance in the form of feet and inches.
A program to add two distances in inch-feet using a structure in C++ is given as follows −
Example
#include <iostream>
using namespace std;
struct DistanceFI {
int feet;
int inch;
};
int main() {
struct DistanceFI distance1, distance2, distance3;
cout << "Enter feet of Distance 1: "<<endl;
cin >> distance1.feet;
cout << "Enter inches of Distance 1: "<<endl;
cin >> distance1.inch;
cout << "Enter feet of Distance 2: "<<endl;
cin >> distance2.feet;
cout << "Enter inches of Distance 2: "<<endl;
cin >> distance2.inch;
distance3.feet = distance1.feet + distance2.feet;
distance3.inch = distance1.inch + distance2.inch;
if(distance3.inch > 12) {
distance3.feet++;
distance3.inch = distance3.inch - 12;
}
cout << endl << "Sum of both distances is " << distance3.feet << " feet and " << distance3.inch << " inches";
return 0;
}Output
The output of the above program is as follows
Enter feet of Distance 1: 5 Enter inches of Distance 1: 9 Enter feet of Distance 2: 2 Enter inches of Distance 2: 6 Sum of both distances is 8 feet and 3 inches
In the above program, the structure DistanceFI is defined that contains the distance in feet and inches. This is given below −
struct DistanceFI{
int feet;
int inch;
};The values of both distances to be added are acquired from the user. This is given below −
cout << "Enter feet of Distance 1: "<<endl; cin >> distance1.feet; cout << "Enter inches of Distance 1: "<<endl; cin >> distance1.inch; cout << "Enter feet of Distance 2: "<<endl; cin >> distance2.feet; cout << "Enter inches of Distance 2: "<<endl; cin >> distance2.inch;
The feet and inches of the two distances are added individually. If the inches are greater than 12, then 1 is added to the feet and 12 is subtracted from the inches. This is done because 1 feet = 12 inches. The code snippet for this is given below −
distance3.feet = distance1.feet + distance2.feet;
distance3.inch = distance1.inch + distance2.inch;
if(distance3.inch > 12) {
distance3.feet++;
distance3.inch = distance3.inch - 12;
}Finally the value of feet and inches in the added distance is displayed. This is given below −
cout << endl << "Sum of both distances is " << distance3.feet << " feet and " << distance3.inch << " inches";