- 2070 Asar · 6 marks
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)
Related questions
- College records with nested date structure · Computer Programming, chapter 8
- Pass student array; display passed students · Computer Programming, chapter 7
- Sending structure members to a function · Computer Programming, chapter 8
- Structure of a FORTRAN program · Computer Programming, chapter 11 · asked 5×
- Declaration vs definition; C program structure · Computer Programming, chapter 3
- Read records until end; show nth record · Computer Programming, chapter 10 · asked 2×
- Program using static members · Object Oriented Programming, chapter 4
- Two groups: best, consistent, SE of difference · Probability and Statistics, chapter 1
- T/F: sag absent with supports at different heights · Transmission and Distribution System Design, chapter 4
- Protected specifier; student/test/result program · Object Oriented Programming, chapter 6