5.x — Chapter 5 summary and quiz

📘 Chapter 5⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

Quick review#

  • while (condition) repeats while the condition is true.
  • for (start; check; step) is great for counting.
  • break leaves a loop. continue skips to the next trip.
  • do { } while ( ); always runs at least once.
  • Nested loops: the inner loop runs fully for each outer trip.
  • <random> makes random numbers: one engine, many rolls.
Quick check

Pick an answer. You find out right away if it is right.

Quick check #1

How many times does for (int i { 0 }; i < 3; ++i) loop?

Quick check #2

What does continue; do in a loop?

Quick check #3

Which loop always runs its body at least once?

Quiz time
Question #1

How many times does this print "Hi"?

C++
for (int i { 0 }; i < 4; ++i){    std::cout << "Hi\n";}

4 times (for i = 0, 1, 2, 3).

Question #2

What does this print?

C++
int n { 10 };while (n > 0){    std::cout << n << ' ';    n -= 3;}

10 7 4 1. After 1, n becomes -2, which is not > 0, so the loop ends.

Question #3

Write a loop that adds up all numbers from 1 to 100 and prints the total.

C++
int total { 0 };for (int i { 1 }; i <= 100; ++i){    total += i;}std::cout << total << '\n';   // 5050
Question #4

FizzBuzz! Print the numbers 1 to 30. But for multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.

C++▶ Run
#include <iostream> int main(){    for (int i { 1 }; i <= 30; ++i)    {        if (i % 15 == 0)            std::cout << "FizzBuzz\n";        else if (i % 3 == 0)            std::cout << "Fizz\n";        else if (i % 5 == 0)            std::cout << "Buzz\n";        else            std::cout << i << '\n';    }    return 0;}

The trick: check "both" (% 15) first. Otherwise 15 would stop at "Fizz".

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.