Selection (part 2)

Lesson by Thiago Nepomuceno

Beyond the commands if and else, it is also possible to use the command else if. It is easy to learn it by looking at the following example: Assume a person is considered "Tall" if they are taller than 1.80m, "Regular" if they are taller than 1.50m but less than 1.80m, and "Small" if they are shorter or equal than 1.50m. Write a program that given that person's height, returns if they are "Tall", "Regular" or "Short."

A valid answer for this problem using only the commands if and else would be the following:


#include <iostream> // cin and cout

using namespace std;

int main(){
  
  double height; // declare the variable
  cin>>altura; // read the input and store it in height
  
  if(height > 1.8){
    cout<<"Tall\n"; // The person is considered "Tall"
  }
  else{
    if(height > 1.5){
      cout<<"Regular\n"; // The person is considered "Regular"
    }
    else{
      cout<<"Short\n"; // The person is considered "Short"
    }
  }
  
  return 0;
}

After finding out that the person is not taller than 1.8m, we will look for the answer inside the block else and, again, using the same structure of if and else. Although this code works and gives us the right answer, we can simplify it by using the format "if, else if, else".

In English, we can describe the solution to this problem as: "If a person is taller than 1.8m, they are tall, else, if they are taller than 1.5m, they are regular, and else they are short." We can transform that into C++ code.


#include <iostream> // cin and cout

using namespace std;

int main(){
  
  double height; // declare the variable height
  cin>>height; // read the input and save it in height
  
  if(height > 1.8){
    cout<<"Tall\n"; // The person is considered Tall
  }
  else if(height > 1.5){
    cout<<"Regular\n"; // The person is considered Regular
  }
  else{
    cout<<"Short\n"; // The person is considered Short
  }
  
  return 0;
}

Now, consider solving the problems that require if, else if, and else before moving on to the next lessons.