5.x — Chapter 5 summary and quiz
Quick review#
while (condition)repeats while the condition is true.for (start; check; step)is great for counting.breakleaves a loop.continueskips 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.
Pick an answer. You find out right away if it is right.
How many times does for (int i { 0 }; i < 3; ++i) loop?
i is 0, 1, then 2. When it reaches 3, i < 3 is false.
What does continue; do in a loop?
continue skips the rest of this trip. break leaves the loop completely.
Which loop always runs its body at least once?
do-while checks its condition at the end, after running once.
How many times does this print "Hi"?
for (int i { 0 }; i < 4; ++i){ std::cout << "Hi\n";}4 times (for i = 0, 1, 2, 3).
What does this print?
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.
Write a loop that adds up all numbers from 1 to 100 and prints the total.
int total { 0 };for (int i { 1 }; i <= 100; ++i){ total += i;}std::cout << total << '\n'; // 5050FizzBuzz! 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.
#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".
Tip: press ← / → to move between lessons, / to search.