C Online Compiler
Example: Calculate Weight from Mass in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Calculate Weight from Mass #include <stdio.h> #define GRAVITY_EARTH 9.81 // Acceleration due to gravity on Earth in m/s^2 int main() { float mass; float weight; // Step 1: Prompt user for mass input printf("Please enter the object's mass in kilograms (kg): "); // Step 2: Read mass from user with basic validation if (scanf("%f", &mass) != 1 || mass < 0) { printf("Invalid input. Please enter a non-negative number for mass.\n"); return 1; // Indicate an error } // Step 3: Calculate weight using the formula W = m * g weight = mass * GRAVITY_EARTH; // Step 4: Display the calculated mass and weight printf("The mass of the object is: %.2f kg\n", mass); printf("The weight of the object on Earth is: %.2f N\n", weight); return 0; }
Output
Clear
ADVERTISEMENTS