🏗️📚Intermediate

Add N Distances in inch-feet Using Structures

Distance calculation

Adding distances in feet-inches format using structures. 1 foot = 12 inches.

Program Code

struct_distance.c
C
1#include <stdio.h>
2
3struct Distance {
4 int feet;
5 int inches;
6};
7
8struct Distance addDistance(struct Distance d1, struct Distance d2) {
9 struct Distance result;
10
11 result.inches = d1.inches + d2.inches;
12 result.feet = d1.feet + d2.feet;
13
14 // Convert excess inches to feet
15 if (result.inches >= 12) {
16 result.feet += result.inches / 12;
17 result.inches = result.inches % 12;
18 }
19
20 return result;
21}
22
23int main() {
24 struct Distance d1 = {5, 9}; // 5 feet 9 inches
25 struct Distance d2 = {3, 7}; // 3 feet 7 inches
26
27 struct Distance sum = addDistance(d1, d2);
28
29 printf("Distance 1: %d' %d\"\n", d1.feet, d1.inches);
30 printf("Distance 2: %d' %d\"\n", d2.feet, d2.inches);
31 printf("Sum: %d' %d\"\n", sum.feet, sum.inches);
32
33 return 0;
34}
Output

Distance 1: 5' 9"

Distance 2: 3' 7"

Sum: 9' 4"