All lessons

3. Decisions

if and else

0 of 5 activities0%

Reading 1

if chooses a branch

Open

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

Open

In if (x > 5) { ... } else { ... }, when does the else block run?

Fill in 3

The other branch

Open

The keyword that introduces the block that runs when the if condition is false is

Try it 4

Positive or not

Open

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

Open

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…