C++ If Else
Programs become truly useful when they can make decisions. The if...else statement lets your code choose between different paths depending on whether a condition is true or false. This is one of the most important tools you will use in every program you write.
C++ supports the usual logical conditions from mathematics and uses them to run different blocks of code. The idea is simple: if a condition is true, do one thing; otherwise, do something else.
The if statement
Use the if keyword followed by a condition in parentheses. If the condition evaluates to true, the code inside the curly braces runs. If it is false, that code is skipped entirely.
A basic if statement
#include <iostream>
using namespace std;
int main() {
int temperature = 30;
if (temperature > 25) {
cout << "It is a warm day.\n";
}
return 0;
}The else statement
Add an else block to describe what should happen when the condition is false. Only one of the two blocks will ever run.
if with else
#include <iostream>
using namespace std;
int main() {
int hour = 20;
if (hour < 18) {
cout << "Good day.\n";
} else {
cout << "Good evening.\n";
}
return 0;
}The else if statement
When you have more than two possibilities, chain conditions together with else if. C++ checks each condition in order and runs the first one that is true, then skips the rest.
Choosing between several options
#include <iostream>
using namespace std;
int main() {
int score = 82;
if (score >= 90) {
cout << "Grade: A\n";
} else if (score >= 80) {
cout << "Grade: B\n";
} else if (score >= 70) {
cout << "Grade: C\n";
} else {
cout << "Grade: F\n";
}
return 0;
}The parts of an if...else chain
Exercise: C++ If...Else
In an if / else if / else chain, how many branches run for a single evaluation?