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 withRuntimeError: unreachablewhen 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 variableiexists only inside the loop.i--counts down, andi += 5counts by fives.for (int i = 0; i < n; i++)runs exactlyntimes. Check<and<=carefully, so that you aren't off by one.- Use
forwhen you know how many times the loop will run, andwhilewhen 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 adoublebefore dividing:(double)total / count. - Counting: a counter that starts at 0 and increases with
count++inside anif. Withifandelse, two counters count every value exactly once. breakends the whole loop, for example when you have found what you were looking for.continueskips 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.
printfwithout\nkeeps printing on the same line, andprintf("\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:
FizzBuzzinstead of a number divisible by both 3 and 5,Fizzinstead of any other number divisible by 3,Buzzinstead 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
11/11