Learning pathOriginal reference
Lesson 4 of 12

Conditions and logical decisions

Build exclusive categories, combine comparisons, and protect operations with short-circuit logic.

Ask a true-or-false question

Use == for equality, != for inequality, and <, <=, >, >= for order. A single = assigns a value; it does not ask whether two values are equal. An if executes its block only when its condition is true, while if/else chooses exactly one of two branches.

Independent if statements can both run. An if / else if / else chain stops after the first matching branch. Use a chain for one category, and independent conditions when several facts can be true at once.

Check the strongest threshold first

For a guaranteed score from 0 through 100, check A before B before C. If you first check score >= 50, then 95 would match that broad condition before reaching the A case.

Test the exact boundaries: 49/50, 74/75, and 89/90. Braces determine the block; indentation helps you read it. An accidental semicolon immediately after if creates an empty statement and changes the intended control flow.

C++23
#include <iostream>

int main() {
    int score = 0;
    std::cin >> score;
    if (score >= 90) {
        std::cout << "A\n";
    } else if (score >= 75) {
        std::cout << "B\n";
    } else if (score >= 50) {
        std::cout << "C\n";
    } else {
        std::cout << "F\n";
    }
    return 0;
}

Both, either, and not

A && B requires both facts. A || B accepts at least one, including both. ! reverses a truth value. To express 10 ≤ x ≤ 20, write x >= 10 && x <= 20. The mathematical chained spelling 10 <= x <= 20 means something different in C++.

Outside that interval is x < 10 || x > 20. Repeat a complete comparison for each choice: choice == 'A' || choice == 'B'. A lone 'B' is not another comparison. The single-character & and | operators are not substitutes for logical && and ||.

Put the safety condition first

For built-in &&, a false left operand prevents evaluating the right one. For built-in ||, a true left operand prevents evaluating the right one. Therefore k != 0 && n % k == 0 checks the divisor before attempting remainder.

For evenness, use n % 2 == 0. For oddness with positive or negative inputs, use n % 2 != 0. Zero is even. These tests work independently of the positive/negative/zero classification.

Decision explorer

Follow if (n > 0), else if (n == 0), and else.

n > 0positive✓ Branch taken
n == 0zeroSkipped
elsenegativeSkipped

Output: positive

Guided simulation · Change the inputs to test your understanding.

Pause & predict

Which expression correctly accepts x from 0 through 100 inclusive?

Choose an answer
Try it yourself

Turn the idea into code

Read positive side lengths a, b, c ≤ 10⁹. Print INVALID, EQUILATERAL, ISOSCELES, or SCALENE for a nondegenerate triangle.

Give me a hint

First require all three pairwise sums to exceed the remaining side. Then test all-equal before any-equal.

Show the explained solution

Validity must come before classification. Equality in a triangle inequality is a flattened shape. Among valid triangles, all equal comes first because it also satisfies “some pair is equal.”

C++23
#include <iostream>

int main() {
    long long a = 0, b = 0, c = 0;
    std::cin >> a >> b >> c;
    if (!(a + b > c && a + c > b && b + c > a)) {
        std::cout << "INVALID\n";
    } else if (a == b && b == c) {
        std::cout << "EQUILATERAL\n";
    } else if (a == b || a == c || b == c) {
        std::cout << "ISOSCELES\n";
    } else {
        std::cout << "SCALENE\n";
    }
    return 0;
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.