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.
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.for (int i = 1; i <= 10; i++) { ... }has three parts: the start runs once, the condition is checked before every iteration, and the step runs after every iteration.i--counts down, andi += 5counts by fives. The variableiexists only inside the loop.- Use
forwhen you know how many times the loop will run, andwhilewhen you don't. for (int i = 0; i < numbers.size(); i++)goes through the indexes of a vector. Use<, because the last index issize() - 1.- The range-based
forgoes through the elements one by one:for (int number : numbers),for (std::string name : names)orfor (char character : text). The variable holds a copy of each element. - Without
std::endlin the loop, the output continues on the same line. End the line after the loop. - Typical patterns: the sum (a variable that starts at 0 before the loop and adds each value with
+=), the average (the sum divided bysize(); collect the sum in adouble, otherwise integer division drops the decimals), counting (count++inside anif), the largest value (start with the first element and keep every larger one) and building a new vector (push_back()inside anif). 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.
Next comes another small project: a playlist for your bus ride to school. Then, in the lesson on functions, you will learn to give a piece of code a name and run it whenever you need it, for example a function that works out the average of any vector of numbers.
Instructions
- 1
Let's practice with a shopping receipt. The vectors
itemsandpricesbelong together:prices[0]is the price ofitems[0],prices[1]is the price ofitems[1], and so on. Go through both with one loop with an index, and print each item with its price:bread: 35,milk: 25,cheese: 89andapples: 42, each on its own line. - 2
In the same loop, add up the prices. After the loop, print the total as
Total: 191. - 3
Finally, print the name of the most expensive item as
Most expensive: cheese. Look for the largest price the way you learned, but keep its index instead of the price: start with index0, and wheneverprices[i]is greater than the price at the kept index, keepi. After the loop, print the item at that index.