Decisions and loops

Introduction

A program becomes useful when it can choose and repeat. These tools look nearly the same in C, Java and JavaScript, so what you learn here will carry over to many other languages.

How it works

if chains. C++ checks each condition from the top, runs the first block whose condition is true, and skips the rest. Comparisons are ==, !=, <, <=, > and >=. Conditions combine with && (and), two vertical bars (or), and ! (not).

A very common typing mistake is if (x = 5). One = stores a value and does not compare.

switch compares one value with many fixed choices. Each case needs a break, or execution carries on into the next one.

#include <iostream>
using namespace std;

int main() {
    int marks = 75;
    char grade;
    if (marks >= 80) {
        grade = 'A';
    } else if (marks >= 60) {
        grade = 'B';
    } else {
        grade = 'F';
    }
    cout << "Grade " << grade << endl;
    switch (grade) {
    case 'A':
    case 'B':
        cout << "Well done" << endl;
        break;
    default:
        cout << "Try again" << endl;
    }
    return 0;
}
Open in compiler

Loops. for suits counting, and while suits repeating until something changes. do ... while always runs at least once.

break and continue. break leaves the loop at once, and continue skips to the next round.

A later lesson introduces the range-based for loop, which goes through every item of a list.

Syntax

if (a > b && b > 0) { ... } else { ... }

for (int i = 0; i < n; i++) { ... }
while (n > 0) { ... }
do { ... } while (again);

Example

#include <iostream>
using namespace std;

int main() {
    int sum = 0;
    for (int i = 1; i <= 5; i++) {
        if (i == 4) {
            continue;
        }
        sum += i;
    }
    cout << "sum " << sum << endl;
    int n = 4096, digits = 0;
    while (n > 0) {
        n /= 10;
        digits++;
    }
    cout << "digits " << digits << endl;
    return 0;
}
Open in compiler

Line by line

  1. sum starts at 0, outside the loop.
  2. The for loop runs with i from 1 to 5.
  3. When i is 4, continue skips the addition, so the sum is 1 + 2 + 3 + 5.
  4. The while loop divides n by 10 until nothing is left.
  5. Each division removes one digit, so the counter ends up holding the number of digits.

Expected result

sum 11
digits 4

In the real world

A game checks every object on every frame with loops and conditions. Network servers loop forever, handling one request after another. An off-by-one error in a loop is among the most common bugs in all of programming.

Common mistakes

  • Writing = instead of == in a condition.
  • Forgetting break in a switch.
  • Off by one. i <= n when you meant i < n.
  • A semicolon after for (...), which makes the loop body empty.

Best practices

  • Always use curly brackets, even for one line.
  • Declare the loop variable inside the for.
  • Make sure something in a while loop changes its condition.

Summary

if chains run the first true branch, and switch selects among fixed cases. for and while repeat. break leaves a loop, and continue skips to the next round.

Quick check

1. How many times does for (int i = 0; i < 4; i++) run?
2. What does continue do?
3. What happens when a case has no break?
4. What does if (x = 5) do?

Key takeaways

  • Only the first true branch of an if chain runs.
  • Each case in a switch needs a break.
  • Check where each loop starts and stops.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.