Summary

In this lesson, you learned that:

  • A loop repeats a block of code. Each run of the block is an iteration. Always write the block in curly braces and indent it by 4 spaces.
  • while (condition) { ... } repeats the block while the condition is true. Something in the block must change, so that the condition becomes false at some point. Otherwise, the loop never ends, and in these exercises, the program is stopped after 5 seconds (or with RuntimeError: unreachable when a number grows too big). Never put a semicolon after the condition.
  • for (int i = 1; i <= 10; i++) { ... } has three parts, separated by semicolons: the start runs once, the condition is checked before every iteration, and the step runs after every iteration. The variable i exists only inside the loop.
  • i-- counts down, and i += 5 counts by fives. for (int i = 0; i < n; i++) runs exactly n times. Check < and <= carefully, so that you aren't off by one.
  • Use for when you know how many times the loop will run, and while when you don't.
  • A sum: a variable that starts at 0 before the loop, adds each value with += inside the loop, and is printed after the loop. For the average, convert the sum to a double before dividing: (double)total / count.
  • Counting: a counter that starts at 0 and increases with count++ inside an if. With if and else, two counters count every value exactly once.
  • break ends the whole loop, for example when you have found what you were looking for.
  • continue skips the rest of the current iteration and goes on to the next one.
  • Loops can be nested: the inner loop runs all the way through in every iteration of the outer one. printf without \n keeps printing on the same line, and printf("\n") after the inner loop ends the row.
  • do { ... } while (condition); checks the condition after the block, so the block runs at least once. Don't forget the semicolon at the end.

In the next lesson, on arrays, you'll store many values under one name, for example the points of a whole class, and go through them with the loops you know now.

Instructions

Let's practice with FizzBuzz, a famous programming exercise that started as a children's counting game. Print the numbers from 1 to 15, each on its own line, but print a word instead of some of them:

  • FizzBuzz instead of a number divisible by both 3 and 5,
  • Fizz instead of any other number divisible by 3,
  • Buzz instead of any other number divisible by 5.

A number is divisible by 3 when the remainder after dividing it by 3 is 0: i % 3 == 0. Check “both 3 and 5” first: otherwise, 15 would become just Fizz. The output starts with 1, 2, Fizz, 4, Buzz and ends with 14, FizzBuzz.

Count the words: before the loop, create a variable words with the value 0, and increase it by 1 each time you print Fizz, Buzz or FizzBuzz. After the loop, print Words: 7.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

11/11