c
  1. c-program-to-add-two-distances-in-inch-feet-system-using-structures

Program to Add Two Distances (in inch-feet system) using Structures - (C Programs)

In this tutorial, we will write a C program to add two distances in inch-feet system using structures. We will define a structure Distance with two members feet and inch. We will read two distances from the user and add them. The sum will be displayed in the feet-inch format.

Syntax

struct Distance {
   int feet;
   int inch;
};

struct Distance d1, d2, sum;

Example

#include <stdio.h>

struct Distance {
   int feet;
   int inch;
};

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

   printf("Enter information for 1st distance:\n");
   printf("Enter feet: ");
   scanf("%d", &d1.feet);
   printf("Enter inch: ");
   scanf("%d", &d1.inch);

   printf("\nEnter information for 2nd distance:\n");
   printf("Enter feet: ");
   scanf("%d", &d2.feet);
   printf("Enter inch: ");
   scanf("%d", &d2.inch);

   // adding distances
   sum.feet = d1.feet + d2.feet;
   sum.inch = d1.inch + d2.inch;

   // convert inches to feet if greater than 12
   while (sum.inch >= 12) {
      ++sum.feet;
      sum.inch = sum.inch - 12;
   }

   printf("\nSum of distances = %d feet %d inch", sum.feet, sum.inch);
   return 0;
}

Output

Enter information for 1st distance:
Enter feet: 5
Enter inch: 11

Enter information for 2nd distance:
Enter feet: 2
Enter inch: 8

Sum of distances = 8 feet 7 inch

Explanation

We define a Distance structure with two members feet and inch. We read two distances from the user using scanf() and store them in variables d1 and d2. We define another variable sum of type Distance to store the sum of the two distances.

We add the feet and inch values of the two distances and store them in the feet and inch members of sum. If the inch value in sum is greater than or equal to 12, we convert it to feet and add it to the feet member of sum. Finally, we display the sum of the two distances in the feet-inch format using printf().

Use

This program is useful whenever we need to add distances in inch-feet system. It can be used in any application that requires working with distances.

Summary

In this tutorial, we learned how to add two distances in inch-feet system using structures in C. We defined a structure Distance with two members feet and inch. We read two distances from the user and added them. We displayed the sum of the two distances in the feet-inch format. This program can be used in any application that requires working with distances in inch-feet system.

Published on: