In this example, we will see how to pass or return a structure to a function
#include <iostream>
using namespace std;
struct Distance{
int kilometer;
int meter;
};
void TotalDistance(Distance d1, Distance d2){
Distance d;
d.kilometer = d1.kilometer + d2.kilometer+(d1.meter + d2.meter)/ 1000;
d.meter = (d1.meter + d2.meter) % 1000;
cout<<"Total Distance"<<endl;
cout<<"kilometer : "<<d.kilometer<<endl;
cout<<"Meter : "<<d.meter<<endl;
}
void intialize(){
Distance distance1,distance2;
distance1.kilometer = 10;
distance1.meter = 300;
distance2.kilometer = 9;
distance2.meter = 250;
TotalDistance(distance1,distance2);
}
int main(){
intialize();
return 0;
}
Output:
Total Distance
kilometer : 19
Meter : 550
Explanation:
Step1: Structure Definition: Distance
struct Distance {
int kilometer;
int meter;
};
A struct
named Distance
is declared with two members:
kilometer
: An integer to store the distance in kilometers.meter
: An integer to store the distance in meters.
Step2: Function: TotalDistance()
void TotalDistance(Distance d1, Distance d2) {
Distance d;
d.kilometer = d1.kilometer + d2.kilometer + (d1.meter + d2.meter) / 1000;
d.meter = (d1.meter + d2.meter) % 1000;
cout << "Total Distance" << endl;
cout << "kilometer : " << d.kilometer << endl;
cout << "Meter : " << d.meter << endl;
}
Function Breakdown:
- Input: Takes two
Distance
objects (d1
andd2
) as arguments, representing two distances. - Add kilometers and meters:
d1.kilometer + d2.kilometer
: Adds the kilometers of both distances.(d1.meter + d2.meter) / 1000
: Adds the meters and converts the excess meters into kilometers. This ensures that meters greater than or equal to 1000 are carried over to kilometers (since 1000 meters = 1 kilometer).
- Calculate remaining meters:
d.meter = (d1.meter + d2.meter) % 1000;
This line calculates the remaining meters after any full kilometers have been added.
Output: The total kilometers and meters are printed.
Step3: Function: initialize()
void intialize() {
Distance distance1, distance2;
distance1.kilometer = 10;
distance1.meter = 300;
distance2.kilometer = 9;
distance2.meter = 250;
TotalDistance(distance1, distance2);
}
Function Breakdown:
- Define two distances:
distance1
: Initialized with 10 kilometers and 300 meters.distance2
: Initialized with 9 kilometers and 250 meters.
- Call
TotalDistance
: The functionTotalDistance()
is called to calculate and print the total distance by passingdistance1
anddistance2
.
Step4: Main Function
int main() {
intialize();
return 0;
}
The main()
function calls the initialize()
function, which performs the necessary operations to calculate the total distance.