Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to add Distance given in cm and meter

C Code Example — Structure Programs

ADVERTISEMENT

C Program to add Distance given in cm and meter

Objective

Write a C program to add two distances given in meters and centimeters.

Algorithm / Approach

  1. Define struct Distance with meter and cm.
  2. Declare global structure variables d1, d2, sum immediately after the struct definition.
  3. Read the two distances.
  4. Add the meters: sum.meter = d1.meter + d2.meter.
  5. Add the centimeters: sum.cm = d1.cm + d2.cm.
  6. If sum.cm > 100.0, subtract 100 from cm and add 1 to the meter.
main.c
#include<stdio.h>
struct Distance {
 int meter;
 float cm;
} d1,d2,sum;
int main( ) {
 printf("Enter Info of Distance1:");
 printf("Enter meter: ");
 scanf("%d",&d1.meter);
 printf("Enter cm: ");
 scanf("%f",&d1.cm);
 printf("Enter Info of Distance2:");
 printf("Enter meter : ");
 scanf("%d",&d2.meter);
 printf("Enter cm : ");
 scanf("%f",&d2.cm);
 sum.meter=d1.meter+d2.meter;
 sum.cm=d1.cm+d2.cm;
 if (sum.cm>100.0) {
  sum.cm=sum.cm-100.0;
  ++sum.meter;
 }
 printf("\nSum of distances = %dm ,%.1fcm",sum.meter,sum.cm);
 return 0;
}

Expected Output

Enter Info of Distance1 : 
Enter meter : 7
Enter cm : 85
Enter Info of Distence2 :
Enter meter : 10
Enter cm : 65
Sum of distances = 18m, 50cm

Explanation of the Program

  • When adding real-world measurements like time or distance, you often have to "carry over" excess values to the next largest unit.
  • Because 100 centimeters equals 1 meter, we check if the total centimeters exceed 100. If they do, we convert those 100 centimeters into 1 extra meter.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT