C Program to Add Two Distances (in inch-feet system) using Structures

C Program to Add Two Distances (in inch-feet system) using Structures

In this example, you will learn to take two distances (in the inch-feet system), add them and display the result on the screen.

To understand this example, you should have the knowledge of the following C programming topics:


If you do not know, 12 inches is 1 foot.

Program to add two distances in inch-feet system

#include <stdio.h>
struct Distance {
   int feet;
   float inch;
} d1, d2, result;

int main() {
   printf("Enter 1st distance\n");
   printf("Enter feet: ");
   scanf("%d", &d1.feet);
   printf("Enter inch: ");
   scanf("%f", &d1.inch);
   printf("\nEnter 2nd distance\n");
   printf("Enter feet: ");
   scanf("%d", &d2.feet);
   printf("Enter inch: ");
   scanf("%f", &d2.inch);

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

   // while inch is greater than 12, changing it to feet.
   while (result.inch > 12.0) {
      result.inch = result.inch - 12.0;
      ++result.feet;
   }
   printf("\nSum of distances = %d\'-%.1f\"", result.feet, result.inch);
   return 0;
}

Output

Enter 1st distance
Enter feet: 23
Enter inch: 8.6

Enter 2nd distance
Enter feet: 34
Enter inch: 2.4

Sum of distances = 57'-11.0"

In this program, a structure Distance is defined. The structure has two members inch (float) and feet (integer).

Two variables (d1 and d2) are created, which stores two distances (in inch and feet). Then, the sum of the two distances is stored in the result structure variable. If inch is greater than 12, it is converted to feet. Finally, the result is printed on the screen.