Lesson 4 of 10
Loops
- 14 min
- 5 checks
- 3 hints
- Go to task
Goal
Repeating with for, while and for-each
Explanation
Use a for loop when you know how many times to repeat. Its header has three parts (the start, the condition and the step), as in for (int i = 1; i <= n; i++), where i++ adds one to i. Put one loop inside another to draw shapes: the outer loop handles the rows and the inner one handles what goes in each row. System.out.print prints without moving to a new line, and System.out.println() then ends the line.
The enhanced for loop, or for-each, walks through items without a counter: for (char c : word.toCharArray()) hands you the string's characters one at a time. Use while when you don't know the number of iterations in advance. It keeps going as long as its condition is true, so make sure something inside it moves it toward the end, or it will never stop.
The best-known loop trap is the boundary: the condition i < n stops before n, while i <= n includes it. This is called an off-by-one error. It doesn't crash your program, it just gives you a result with one iteration too few or one too many.
Your task
Write sumTo(n) to return the sum of the numbers from 1 to n using for, and countVowels(s) to count the vowels a e i o u, lower or upper case, using for-each. In nightsUntil(zombies, target) the number of zombies doubles every night: use while to return how many nights it takes for the number to reach at least target. Then write printStairs(n) to print a staircase of n rows that starts with #, then ##, and so on until the last row has n of them, and call printStairs(4) from main.
Checks
5 checks- sumTo adds up the numbers from 1 to n
- countVowels counts lower and upper case vowels
- nightsUntil gets from 1 to 1000 in 10 nights
- printStairs(2) prints two steps
- A four-row staircase was printed