C Online Compiler
Example: Body Mass Index (BMI) Calculator in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Body Mass Index (BMI) Calculator #include <stdio.h> int main() { float weight_kg; // Variable to store weight in kilograms float height_m; // Variable to store height in meters float bmi; // Variable to store the calculated BMI // Step 1: Prompt user for weight input printf("Welcome to the BMI Calculator!\n"); printf("Please enter your weight in kilograms (e.g., 70.5): "); // Step 2: Read weight from user if (scanf("%f", &weight_kg) != 1) { printf("Invalid input for weight. Please enter a numerical value.\n"); return 1; // Indicate an error } // Step 3: Prompt user for height input printf("Please enter your height in meters (e.g., 1.75): "); // Step 4: Read height from user if (scanf("%f", &height_m) != 1) { printf("Invalid input for height. Please enter a numerical value.\n"); return 1; // Indicate an error } // Step 5: Check for invalid inputs (zero or negative height/weight) if (weight_kg <= 0 || height_m <= 0) { printf("Weight and height must be positive values. Please try again.\n"); return 1; // Indicate an error } // Step 6: Calculate BMI using the formula: weight / (height * height) bmi = weight_kg / (height_m * height_m); // Step 7: Display the calculated BMI printf("\nYour calculated BMI is: %.2f\n", bmi); // .2f formats to two decimal places // Step 8: Provide BMI category interpretation for context printf("BMI Categories:\n"); printf(" Underweight: < 18.5\n"); printf(" Normal weight: 18.5 - 24.9\n"); printf(" Overweight: 25 - 29.9\n"); printf(" Obesity: >= 30\n"); return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS