4.2 — else and else if

📘 Chapter 4⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

else: otherwise#

else runs when the if condition is false.

C++
int age {};std::cin >> age; if (age >= 18){    std::cout << "You can vote.\n";}else{    std::cout << "Not yet!\n";}

Exactly one of the two blocks runs. Never both.

else if: more choices#

Chain more questions with else if. C++ checks them from top to bottom and runs the first one that is true.

C++
int score { 72 }; if (score >= 90){    std::cout << "Grade A\n";}else if (score >= 70){    std::cout << "Grade B\n";}else if (score >= 50){    std::cout << "Grade C\n";}else{    std::cout << "Keep practising!\n";}
Output
Grade B
Key idea

Only the first true branch runs. Score 72 is also >= 50, but C++ already stopped at "Grade B".

Nesting#

You can put an if inside another if:

C++
if (isLoggedIn){    if (isAdmin)    {        std::cout << "Welcome, boss.\n";    }    else    {        std::cout << "Welcome back.\n";    }}
Tip

Too many nested ifs get hard to read. Often && can join them: if (isLoggedIn && isAdmin).

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.