In this C program, we'll create a structure to represent distances in the inch-feet system and then demonstrate how to add two distances using structures. Here's the program:
#include <stdio.h>
// Define a structure to represent distances in inch-feet system
struct Distance {
int feet;
float inches;
};
// Function to add two distances and return the result
struct Distance addDistances(struct Distance d1, struct Distance d2) {
struct Distance sum;
sum.feet = d1.feet + d2.feet;
sum.inches = d1.inches + d2.inches;
// Convert inches to feet if the total inches exceed 12
if (sum.inches >= 12.0) {
sum.inches -= 12.0;
sum.feet++;
}
return sum;
}
int main() {
struct Distance distance1, distance2, result;
// Input the first distance
printf("Enter the first distance (feet inches): ");
scanf("%d %f", &distance1.feet, &distance1.inches);
// Input the second distance
printf("Enter the second distance (feet inches): ");
scanf("%d %f", &distance2.feet, &distance2.inches);
// Add the two distances
result = addDistances(distance1, distance2);
// Display the result
printf("Sum of distances: %d feet %.2f inches\n", result.feet, result.inches);
return 0;
}
In this program, we define a structure named Distance
to represent distances in the inch-feet system. Each distance consists of two fields:
feet
: An integer representing the number of feet.inches
: A floating-point number representing the number of inches.
We also define a function addDistances
that takes two Distance
structures and returns their sum. The function adds the feet and inches separately and ensures that the total inches are converted to feet if they exceed 12.
In the main
function:
We input the first distance (feet and inches) and store it in the
distance1
structure.We input the second distance (feet and inches) and store it in the
distance2
structure.We call the
addDistances
function to calculate the sum of the two distances and store the result in theresult
structure.Finally, we display the sum of distances in the inch-feet system.
Here's an example of how the program works:
Enter the first distance (feet inches): 5 9.5
Enter the second distance (feet inches): 3 6.25
Sum of distances: 9 feet 3.75 inches
In this example, the program adds two distances: 5 feet 9.5 inches and 3 feet 6.25 inches, and the result is 9 feet 3.75 inches.