All lessonsOpen Open Open Open Open
3. Decisions
if and else
0 of 5 activities0%
Reading 1
if chooses a branch
An if statement runs a block only when a condition is true. An optional else runs when the condition is false.
Comparison operators: == != < > <= >=. Use == to test equality, not a single = (that assigns).
You can chain else if for more than two cases.
if (n > 0) {
cout << "positive" << endl;
} else {
cout << "non-positive" << endl;
}Check 2
When else runs
In if (x > 5) { ... } else { ... }, when does the else block run?
Fill in 3
The other branch
Try it 4
Positive or not
Sample input is 4. Run it, then try a negative number in the input box.
main.cpp
Loading editor…
Output will appear here.
Assignment 5
Classify a number
Read one integer. If it is greater than 0, print positive. Otherwise print non-positive. Use those exact words, each on one line.
main.cpp
Loading editor…