C Program to Add Two Distance in Feet-Inch System

There are different systems that use feets and inches to measure length or distance. In all of these systems a foot is equal to exactly 12 inches, and in most an inch is exactly 25.4 mm (milimeter).

This C program illustrates how to add two distamces or length given in feet inch system using structure.

C Source Code: Add Two Distance in Feet Inch System


#include<stdio.h>

struct distance
{
    int feet;
    int inch;
};

int main()
{
    /* Declaring structure variables */
    struct distance d1, d2, sum;
    /* Inputs */
    printf("Enter feet and inch of first distance: ");
    scanf("%d%d", &d1.feet, &d1.inch);
    printf("Enter feet and inch of second distance: ");
    scanf("%d%d", &d2.feet, &d2.inch);

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

    if(sum.inch>=12)
    {
        sum.feet += sum.inch/12;
        sum.inch %= 12;
    }
    printf("Sum is %d' %d''", sum.feet, sum.inch);
    return 0;
}

Output

Enter feet and inch of first distance: 5   9
Enter feet and inch of second distance: 7   10
Sum is 13' 7''

Modification of Above Program Using typedef


#include<stdio.h>

typedef struct
{
    int feet;
    int inch;
}distance;

int main()
{
    /* Declaring structure variables */
    distance d1, d2, sum;
    /* Inputs */
    printf("Enter feet and inch of first distance: ");
    scanf("%d%d", &d1.feet, &d1.inch);
    printf("Enter feet and inch of second distance: ");
    scanf("%d%d", &d2.feet, &d2.inch);

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

    if(sum.inch>=12)
    {
        sum.feet += sum.inch/12;
        sum.inch %= 12;
    }
    printf("Sum is %d' %d''", sum.feet, sum.inch);
    return 0;
}

Output

Enter feet and inch of first distance: 8  11
Enter feet and inch of second distance: 9  17
Sum is 19' 4''