
This is the "if … otherwise …" idea. If the condition in brackets is true the first block runs; if not, the else block runs.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
if (n > 0) {
cout << "Positive" << endl;
} else if (n < 0) {
cout << "Negative" << endl;
} else {
cout << "Zero" << endl;
}
return 0;
}> what you see
(input: -5) Negative
//LINE BY LINE
Watch it run
score = 85. The chain is checked from the top down, one test at a time.
Three or more choices
Chain else if for as many choices as you like. The computer checks top to bottom and stops at the first one that matches.
if (score >= 90) {
cout << "A";
} else if (score >= 80) {
cout << "B";
} else if (score >= 70) {
cout << "C";
} else {
cout << "F";
}The order matters. If score >= 70 came first, a student with 95 would get a "C".
Always write the braces
For a single line you may leave the braces out — but don't. It breaks as soon as you add a second line.
The trap of leaving braces out:
if (x > 0)
cout << "positive";
cout << " number"; // ✗ энэ мөр if-ээс ГАДНА байна!With braces — always correct:
if (x > 0) {
cout << "positive";
cout << " number"; // ✓ хоёулаа if дотор
}