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
- Define
struct Distancewithmeterandcm. - Declare global structure variables
d1, d2, sumimmediately after the struct definition. - Read the two distances.
- Add the meters:
sum.meter = d1.meter + d2.meter. - Add the centimeters:
sum.cm = d1.cm + d2.cm. - 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)