Lesson 4 of 10
Loops
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Repetition with for, while and nested loops
Explanation
Use for when you know how many times to repeat. for (int i = 1; i <= n; i++) has three parts separated by two semicolons: the value the counter starts at, a condition checked before each pass, and a step that runs after each pass. i++ adds one to the counter, and total += i adds i to the total. Watch the boundary: if you write < instead of <=, the last pass is lost without any warning.
Use while (n != 0) when you don't know the number of passes in advance: it keeps repeating as long as its condition is true, like dividing a number by 10 while there's something left in it. do { ... } while (n != 0); checks its condition after each pass instead of before, so it always runs at least once. And watch out for a loop that never changes what its condition checks: if you forget n /= 10, the loop runs forever, until the server stops it a few seconds later.
With a loop inside a loop you can draw shapes: the outer loop goes through the rows, the inner loop draws a single row, and the inner loop's limit comes from the outer loop's counter, as in for (int i = 0; i < row; i++). Give each loop a counter with a different name.
Your task
Complete int sumTo(int n) with a for loop so it returns the sum of the numbers from 1 to n, or zero if n is zero or negative. Then complete int countDigits(int n) so it returns how many digits n has by dividing it by 10 over and over. Keep in mind that zero has one digit, and that a negative number's digits are counted without the sign, so countDigits(-907) is 3. Finally, use two nested loops to print this staircase from main, and nothing else: #, then ##, then ###, then ####, each on its own line.
Checks
6 checks- sumTo(5) returns 15
- sumTo(1) and sumTo(100) are correct
- sumTo returns zero for zero and negative numbers
- countDigits(12345) returns 5 and countDigits(7) returns 1
- countDigits counts zero as one digit and ignores the sign of a negative number
- The staircase was printed with its four lines and nothing else