Skip to main content

Height difference using nested structure

Short answer

Convert each height to total inches (feet*12 + inches), calculate the absolute difference, then convert back: feet = diff/12, inches = diff%12. For input 5 9 and 5 4, the difference is 0 feet 5 inches.

Write a program to read the heights of two students and display the difference between their heights. Use feet and inches as members of a structure to define height.

Method. The structure height has the members feet and inches. Each height is converted to total inches (feet × 12 + inches), the smaller is subtracted from the larger, and the result is converted back with / 12 (feet) and % 12 (inches). This avoids a separate borrow step (1 foot = 12 inches).

#include <stdio.h>

struct height {
    int feet;
    int inches;
};

int main(void)
{
    struct height h1, h2, d;
    int t1, t2, diff;

    printf("Height of first student (feet inches): ");
    scanf("%d %d", &h1.feet, &h1.inches);
    printf("Height of second student (feet inches): ");
    scanf("%d %d", &h2.feet, &h2.inches);

    t1 = h1.feet * 12 + h1.inches;      /* convert to inches */
    t2 = h2.feet * 12 + h2.inches;
    diff = t1 > t2 ? t1 - t2 : t2 - t1;

    d.feet = diff / 12;
    d.inches = diff % 12;
    printf("Difference = %d feet %d inches\n", d.feet, d.inches);
    return 0;
}

Sample run (5 ft 9 in and 5 ft 4 in)

Input: 5 9 5 4

Height of first student (feet inches): Height of second student (feet inches): Difference = 0 feet 5 inches

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 8 questions →