Index « Previous Next »

Question

Define a structure Distance to represent distance in feet and inches. Write a program to add two distances. Your program must contains functions:

  1. Input function that takes a distance as parameter
  2. Display function that takes a distance as parameter
  3. Add function that takes two distances as parameter and return their sum

Source Code

#include <stdio.h>

struct distance
{
    int feet;
    int inch;
};

void input(struct distance*);
void display(struct distance);
struct distance add(struct distance, struct distance);

int main()
{
    struct distance d1, d2, d3, d4;
    printf("\nEnter distance 1: \n");
    input(&d1);
    printf("\nEnter distance 2: \n");
    input(&d2);
    printf("\n\nDistance 1 is: ");
    display(d1);
    printf("\n\nDistance 2 is: ");
    display(d2);
    d3 = add(d1, d2);
    printf("\n\nAddition");
    display(d3);

    return 0;
} 

void input(struct distance *t)
{
    printf("Enter feet: ");
    scanf("%d", &t->feet);
    printf("Enter inch: ");
    scanf("%d", &t->inch);
} 

void display(struct distance c)
{
    printf("\n%d\' %d\" ", c.feet, c.inch);
} 

struct distance add(struct distance t1, struct distance t2)
{
    struct distance t;
    t.feet = t1.feet + t2.feet;
    t.inch = t1.inch + t2.inch;
    if (t.inch >= 12)
    {
        t.inch -= 12;
        t.feet++;
    }
    return t;
}

Output

Enter distance 1:
Enter feet: 5
Enter inch: 9

Enter distance 2:
Enter feet: 3
Enter inch: 7


Distance 1 is:
5' 9"

Distance 2 is:
3' 7"

Addition
9' 4"