if
An if runs a block of code only if its condition is true:
#include <iostream>
using namespace std;
int main() {
int temperature = 35;
if (temperature > 30) {
cout << "It's hot! Drink water.\n";
}
cout << "Have a nice day.\n";
return 0;
}Output
It's hot! Drink water. Have a nice day.
- The condition goes inside round brackets
( ). - The code to run goes inside curly braces
{ }. - The last line is outside the braces, so it always runs.
else
else gives a second path for when the condition is false:
#include <iostream>
using namespace std;
int main() {
int number;
cin >> number;
if (number % 2 == 0) {
cout << number << " is even\n";
} else {
cout << number << " is odd\n";
}
return 0;
}Input (what the user types)
7
Output
7 is odd
Think of it like this:
if/elseis a fork in the road. The program checks the sign and takes exactly one of the two paths.
else if
For more than two choices, chain else if. C++ checks the conditions from top to bottom and runs the first one that is true. The rest are skipped:
#include <iostream>
using namespace std;
int main() {
int marks;
cin >> marks;
if (marks >= 90) {
cout << "Grade A\n";
} else if (marks >= 75) {
cout << "Grade B\n";
} else if (marks >= 50) {
cout << "Grade C\n";
} else {
cout << "Try again\n";
}
return 0;
}Input (what the user types)
82
Output
Grade B
82 is not ≥ 90, but it is ≥ 75, so it prints Grade B and stops checking.
Common mistake: Don't put a semicolon after the condition:
if (x > 5);ends the if right there, and the block below always runs.
Tip: If a block has only one line you may leave out the braces, but beginners should always use them. It avoids nasty bugs.