My teacher has assigned a program to use both if-else
statements and switch
statements, so we understand how to implement both. The program asked u
As always in C++, favour standard library algorithms. In this case you want to do a range lookup. This is easy with an ordered sequence of boundaries:
double const boundaries[] = { 18.5, 25, 30, 35 };
switch (upper_bound(begin(boundaries), end(boundaries), BMI) - boundaries) {
case 0: cout << "You are underweight " << endl; break;
case 1: cout << "You are normal" << endl; break;
case 2: cout << "You are overweight" << endl; break;
case 3: cout << "You are obese" << endl; break;
case 4: cout << "You are gravely overweight" << endl; break;
};
Actually, I suggest you
switch
(see BONUS section below)using namespace std
(see Why is "using namespace std" considered bad practice?)See a live demo on Coliru
#include <iostream>
#include <algorithm>
const char* bmi_classification(double bmi) {
static double const boundaries[] = { 18.5, 25, 30, 35 };
double const* lookup = std::upper_bound(std::begin(boundaries), std::end(boundaries), bmi);
switch (lookup - std::begin(boundaries)) {
case 0: return "underweight";
case 1: return "normal";
case 2: return "overweight";
case 3: return "obese";
case 4: return "gravely overweight";
}
throw std::logic_error("bmi_classification");
}
int main() {
for (double BMI : { 0.0, 18.4999, 18.5, 24.0, 25.0, 29.0, 30.0, 34.0, 35.0, 999999.0 }) {
std::cout << "BMI: " << BMI << " You are " << bmi_classification(BMI) << "\n";
}
}
Prints
BMI: 0 You are underweight
BMI: 18.4999 You are underweight
BMI: 18.5 You are normal
BMI: 24 You are normal
BMI: 25 You are overweight
BMI: 29 You are overweight
BMI: 30 You are obese
BMI: 34 You are obese
BMI: 35 You are gravely overweight
BMI: 999999 You are gravely overweight
BONUS
You can be more elegant without the requirement to use switch
:
Live On Coliru
const char* bmi_classification(double bmi) {
constexpr int N = 5;
static constexpr std::array<char const*, N> classifications {
{ "underweight", "normal", "overweight", "obese", "gravely overweight" }};
static constexpr std::array<double, N-1> ubounds {
{ 18.5, 25, 30, 35 }};
auto lookup = std::upper_bound(std::begin(ubounds), std::end(ubounds), bmi);
return classifications.at(lookup - std::begin(ubounds));
}