Add Two Distances using Structure in C

Exercise:

Write a C Program to add two distances (in inch-feet system) using structures.

Click Here to View the Solution!
#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 inches: ");
    scanf("%f", &d1.inch);
    printf("\nEnter 2nd distance\n");
    printf("Enter feet: ");
    scanf("%d", &d2.feet);
    printf("Enter inches: ");
    scanf("%f", &d2.inch);

    // Adding distances
    result.feet = d1.feet + d2.feet;
    result.inch = d1.inch + d2.inch;

    //  Converts inch to feet if greater than 12
    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;
}
Click Here to View the Output!
Enter 1st distance
Enter feet: 300
Enter inches: 50
Enter 2nd distance
Enter feet: 600
Enter inches: 25
Sum of distances = 906'-3.0"
Click Here to View the Explanation!
  • This program is used to compute the sum of two distances in the inch-feet system by using Structures.
  • A Structure Distance is created with the members integer type feet and float type inch.
  • Three struct distance type variables d1, d2 and result are created. These variables will store the distances in inches and feet.
  • In main(), the program requests the user to enter the first distance in feet and in inches separately and stores them in the feet and inches variable referencing to struct Distance using d1 struct variable.
  • The program then requests the user to enter the second distance in both feet and inches using the d2 struct variable.
  • The sum of the two distances is calculated by adding feet of both the distances and inches of the distances separately and are stored in the result variable of struct as result.feet and result.inch.
  • The distance in inches is then checked using a while loop which converts the inches into feet if they are greater than 12.
  • Finally, the result in feet and inches is printed.