write a c program to calculate the sum of weights of two objects represented in kilograms and grams using structures
Answers
Answer:
#include <stdio.h>
struct weight{
int kilograms;
int grams;
};
void addWeight(struct weight w1,struct weight w2){
struct weight w3;
w3.kilograms= w1.kilograms + w2.kilograms;
w3.grams= w1.grams + w2.grams;
w3.kilograms= w3.kilograms + w3.grams/1000; //1 kilogram has 1000 grams
w3.grams= w3.grams%1000;
printf("\nTotal weight => %d kilograms %d grams",w3.kilograms,w3.grams);
}
int main()
{
struct weight w1,w2;
printf("Enter first object weight in kilograms:");
scanf("%d",&w1.kilograms);
printf("Enter first object weight in grams:");
scanf("%d",&w1.grams);
printf("Enter second object weight in kilograms:");
scanf("%d",&w2.kilograms);
printf("Enter second object weight in grams:");
scanf("%d",&w2.grams);
addWeight(w1,w2);
return 0;
}
Explanation: