Lesson contents

C++ — Selecting a branch with if and else

In C++, an if and else if chain tests conditions in order. The first true branch runs, and an optional else handles everything left over.

A simple example

Follow one branch

  1. Start with n is 2
  2. Do this Is n positive?
  3. Result yes
The condition selects the first branch. Changing the value to zero selects the other branch.
lesson.cpp
#include <iostream>

int main() {
    int n = 2;
    if (n > 0) {
        std::cout << ("yes") << '\n';
    } else {
        std::cout << ("no") << '\n';
    }
}
Output
yes
Advertisements

Classify a stock level

Every reachable branch assigns the string before it is printed. For a small mutually exclusive set of ranges, an ordered if/else chain makes boundary values easy to check.

On the shelf: 3 books. Low-stock limit: 5 books. Shelf notice: Order soon.
Decide when to restock

A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.

Run the example

C++17. Run these commands from the directory containing the example. Use a Unix-style shell.

c++ -std=c++17 lesson.cpp -o lesson
./lesson
lesson.cpp
#include <iostream>
#include <string>

int main() {
    int stock = 3;
    std::string status;
    if (stock == 0) {
        status = "sold out";
    } else if (stock <= 5) {
        status = "order soon";
    } else {
        status = "in stock";
    }
    std::cout << status << '\n';
    return 0;
}
Output
order soon

The stock count is 3. It passes the low-stock test after failing the zero test, so the program selects “order soon”. Zero belongs to both ranges and must be handled first.

Try it yourself

Try the boundary values 0, 5, and 6.

Check your answer

They produce “sold out”, “order soon”, and “in stock”, respectively. In a real inventory system, reject negative input before this classification.

C++ language and library reference

Related tags

  • C++
  • conditions
  • branching
  • comparison