You can use nested if statements to write a program that interprets Body Mass Index.
Body Mass Index (BMI) is a measure of health based on height and weight. You can calculate your BMI by taking your weight in kilograms and dividing it by the square of your height in meters. The interpretation of BMI for people 20 years or older is as follows:
Write a program that prompts the user to enter a weight in pounds and height in inches and displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters. Listing 3.2 gives the program.
Listing 3.2 ComputeAndInterpreteBMI.cpp
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 // Prompt the user to enter weight in pounds
7 cout << “Enter weight in pounds: “;
8 double weight;
9 cin >> weight;
10
11 // Prompt the user to enter height in inches
12 cout << “Enter height in inches: “;
13 double height;
14 cin >> height;
15
16 const double KILOGRAMS_PER_POUND = 0.45359237; // Constant
17 const double METERS_PER_INCH = 0.0254; // Constant
18
19 // Compute BMI
20 double weightInKilograms = weight * KILOGRAMS_PER_POUND;
21 double heightInMeters = height * METERS_PER_INCH;
22 double bmi = weightInKilograms /
23 (heightInMeters * heightInMeters);
24
25 // Display result
26 cout << “BMI is ” << bmi << endl;
27 if (bmi < 18.5)
28 cout << “Underweight” << endl;
29 else if (bmi < 25)
30 cout << “Normal” << endl;
31 else if (bmi < 30)
32 cout << “Overweight” << endl;
33 else
34 cout << “Obese” << endl;
35
36 return 0;
37 }
Two constants KILOGRAMS_PER_POUND and METERS_PER_INCH are defined in lines 16-17. Using constants here makes the program easy to read.
You should test the program by entering the input that covers all possible cases for BMI to ensure that the program works for all cases.
Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.