Register

C++ for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Operators and decisions

Starting out11 min readLesson 4 of 6

4.1 Expressions produce values

An operator combines values into a new value. Arithmetic operators (+, -, *, /, %) work on numbers. Comparison operators (==, !=, <, <=, >, >=) produce a bool. Logical operators (&&, ||, !) combine those results. Assignment (=) stores a value in a variable.

Precedence decides which operation happens first when an expression has several operators. Parentheses make the order visible. If you need to check a precedence table twice, add parentheses.

cpp
#include <iostream>

int main() {
    int total = 7 + 3 * 4;
    int grouped = (7 + 3) * 4;
    int remainder = 17 % 5;
    std::cout << "Total: " << total << "\n";
    std::cout << "Grouped: " << grouped << "\n";
    std::cout << "Remainder: " << remainder << "\n";
    return 0;
}

Output

Total: 19
Grouped: 40
Remainder: 2

4.1.1 Whole numbers and remainders

Division behaves differently for integers and floating point values. 9 / 4 is 2, and 9.0 / 4 is 2.25. The % operator returns the remainder after integer division, so 9 % 4 is 1.

Compound assignment updates a variable in place. score += 5; adds five, and score -= 2; subtracts two. The increment operators ++i and i++ both add one, and their values differ inside a larger expression. Beginner code is easier to read when the update sits on its own line.

cpp
#include <iostream>

int main() {
    int stock = 20;
    stock += 5;
    stock -= 3;
    stock *= 2;
    std::cout << "Stock: " << stock << "\n";
    return 0;
}

Output

Stock: 44

4.1.2 Comparing values

== tests equality, and = assigns. This pair causes many beginner bugs. If a condition looks like if (score = 5), stop and check whether == was intended. C++ compiles some accidental assignments inside conditions, so the mistake can survive the build.

Floating point numbers often have tiny rounding differences. Test an expected range or compare with a tolerance when exact equality is not guaranteed. For a beginner calculator, integer comparisons are easier to trust.

cpp
#include <iostream>

int main() {
    int a = 8;
    int b = 12;
    std::cout << std::boolalpha;
    std::cout << "a < b: " << (a < b) << "\n";
    std::cout << "a == b: " << (a == b) << "\n";
    std::cout << "a != b: " << (a != b) << "\n";
    return 0;
}

Output

a < b: true
a == b: false
a != b: true

4.1.3 Choosing a path

An if statement runs a block when its condition is true. Use else if for mutually exclusive cases and else for the remaining case. Conditions can be any expression convertible to bool, though an explicit comparison often reads better.

Order matters in a chain. Test the most specific condition first. If score >= 60 comes before score >= 90, every passing score takes the first branch and the higher grade is never reached.

cpp
#include <iostream>

int main() {
    int score = 78;
    if (score >= 90) {
        std::cout << "Grade A\n";
    } else if (score >= 75) {
        std::cout << "Grade B\n";
    } else if (score >= 60) {
        std::cout << "Grade C\n";
    } else {
        std::cout << "Keep practising\n";
    }
    return 0;
}

Output

Grade B

4.1.4 Combining conditions

&& means both sides must be true. || means at least one side must be true. ! reverses a bool. These operators short-circuit: the right side is not evaluated when the left side already decides the result. That behavior is useful and also a source of surprises when the right side has side effects.

Wrap each condition clearly when you mix && and ||. A pair of simpler checks, or a small helper function, often reads better than one dense line.

cpp
#include <iostream>

int main() {
    int age = 20;
    bool has_ticket = true;
    bool has_id = false;
    if (age >= 18 && has_ticket) {
        std::cout << "Entry allowed.\n";
    } else {
        std::cout << "Entry denied.\n";
    }
    if (!has_id) {
        std::cout << "Bring ID.\n";
    }
    return 0;
}

Output

Entry allowed.
Bring ID.

4.1.5 Testing exact values

A switch works with an integer, char, or enumeration value. Each case label compares against the switched value. Reach for switch when one variable can take a small set of known values and each case does the same kind of work.

break leaves the switch. Without it, execution falls through into the next case, which is occasionally intentional and more often a bug. Add a default branch for values you did not list.

cpp
#include <iostream>

int main() {
    int day = 3;
    switch (day) {
        case 1:
            std::cout << "Monday\n";
            break;
        case 3:
            std::cout << "Wednesday\n";
            break;
        default:
            std::cout << "Another day\n";
            break;
    }
    return 0;
}

Output

Wednesday

4.1.6 The conditional operator

The conditional operator has the form condition ? value_if_true : value_if_false and produces one value. It fits a short choice such as double rate = age < 18 ? 6.0 : 10.0;. Long nested uses become hard to scan, so use if when the branches perform different actions.

The conditional operator is an expression, and if is a statement. A ternary can sit inside an assignment; an if block cannot.

4.1.7 Debugging and practice

4.1.7.1 Debugging checklist

  • Read = and == separately.
  • Add braces to every branch.
  • Test boundary values: the cutoff itself, one below, and one above.
  • Print the condition result when a branch does not run as expected.

4.1.7.2 Practice

  1. Classify a number as positive, negative, or zero.
  2. Build a ticket price rule with a student discount and a weekend surcharge.
  3. Convert a numeric score to a letter grade and test the exact cutoffs.
  4. Add a switch that prints a weekday name from a number.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What is the difference between = and ==?

    A single equals sign assigns the value on the right to the variable on the left. Two equals signs compare two values and produce a bool.

  • 02When is switch a better choice than a chain of if statements?

    Use switch when one integer or character value is compared against a small set of exact cases. Use if when the conditions involve ranges or mixed expressions.

  • 03What does short-circuit evaluation mean?

    In a && or || expression, the right operand may be skipped when the left operand already determines the result. The skipped expression is not evaluated.