Google News
logo
C Program to Add Two Distances (in inch-feet system) using Structures
In the following example of a C program that adds two distances (in inch-feet system) using structures :
Program :
#include <stdio.h>

struct distance {
    int feet;
    int inches;
};

int main() {
    struct distance d1, d2, sum;

    printf("Enter first distance:\n");
    printf("Feet: ");
    scanf("%d", &d1.feet);
    printf("Inches: ");
    scanf("%d", &d1.inches);

    printf("\nEnter second distance:\n");
    printf("Feet: ");
    scanf("%d", &d2.feet);
    printf("Inches: ");
    scanf("%d", &d2.inches);

    sum.feet = d1.feet + d2.feet;
    sum.inches = d1.inches + d2.inches;

    // If sum of inches is greater than 12, convert to feet and adjust inches
    if (sum.inches >= 12) {
        sum.feet += sum.inches / 12;
        sum.inches = sum.inches % 12;
    }

    printf("\nSum of distances: %d feet %d inches\n", sum.feet, sum.inches);

    return 0;
}
Output :
Enter first distance:
Feet: 18
Inches: 5.6
Enter second distance:
Feet: Inches: 
Sum of distances: 18 feet 5 inches
In this example, the program defines a structure distance that contains two members : feet and inches.

The program then creates three instances of the distance structure called d1, d2, and sum, initializes d1 and d2 with input values from the user using the scanf function, adds d1 and d2 to obtain sum, and prints the sum of the distances in feet and inches using the printf function.