Lesson 3.5
Count-controlled loop
Part 3: RepetitionReading, about 5 min3 exercises in this lesson
Java answers can't run on Spine yet. You can still read Java, trace it, and put an answer's lines in order.
Count-controlled loop
By the end of this you will be able to write a loop that runs a set number of times, using for in Python and Java, and build a line of text one piece at a time.
A while loop runs until a condition changes. A for loop runs a set number of times, counting for you. Use for when you know how many turns you need before the loop starts.
A for loop
for i in range(5):
print(i)public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}This prints 0, 1, 2, 3 and 4, each on its own line: five numbers, starting from 0. The variable i is the counter.
In Python, range(5) gives the numbers 0, 1, 2, 3, 4. The end value, 5, is not included.
In Java, the for line has three parts, separated by semicolons:
- The start,
int i = 0, runs once, before the first turn. - The condition,
i < 5, is checked before every turn. The loop stops the first time it is false. - The update,
i++, runs at the end of every turn. It adds 1 toi, just likei = i + 1.
A for loop is a counting loop
In the lesson on the counting pattern, a counter started at 0 and went up by 1 on each turn. A for loop packs that pattern into one line. This while loop prints the same five numbers:
i = 0
while i < 5:
print(i)
i = i + 1public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i = i + 1;
}
}The for version is shorter, and everything that controls the counter sits on one line, where it is easy to check.
Choosing start and end
To print 1 to 5 instead of 0 to 4:
for i in range(1, 6):
print(i)public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}In Python, range(1, 6) starts at 1 and stops before 6, so the end you write is one past the last value you want. In Java, the start is 1 and the condition i <= 5 says to keep going up to and including 5.
When the end of a loop is a whole number n, these three forms come up often. For n of 2 or more, the first two run n times and the third does not. In Python:
| Python | Values of i, for n of 2 or more | Turns, for n of 2 or more |
|---|---|---|
range(n) | 0 up to n - 1 | n |
range(1, n + 1) | 1 up to n | n |
range(1, n) | 1 up to n - 1 | n - 1 |
The same three loops in Java:
| Java | Values of i, for n of 2 or more | Turns, for n of 2 or more |
|---|---|---|
int i = 0; i < n | 0 up to n - 1 | n |
int i = 1; i <= n | 1 up to n | n |
int i = 1; i < n | 1 up to n - 1 | n - 1 |
In each table, the last row is the most common slip: it moves the start to 1 but keeps the end of the first row, so it runs one turn too few.
Building a line of text
print in Python and System.out.println in Java end the line each time they run. To put several values on one line, build the line in a text variable first, then print it once. This program counts down from 5:
line = ""
for i in range(5):
line = line + str(5 - i) + " "
print(line + "Go!")public static void main(String[] args) {
String line = "";
for (int i = 0; i < 5; i++) {
line = line + (5 - i) + " ";
}
System.out.println(line + "Go!");
}It prints 5 4 3 2 1 Go!. The line starts as "", the empty text, which has nothing in it. Each turn joins one more piece onto its end:
| Turn | i | 5 - i | The line at the end of the turn |
|---|---|---|---|
| 1 | 0 | 5 | 5 |
| 2 | 1 | 4 | 5 4 |
| 3 | 2 | 3 | 5 4 3 |
| 4 | 3 | 2 | 5 4 3 2 |
| 5 | 4 | 1 | 5 4 3 2 1 |
The counter does not have to be printed as it is. Here it is used in a sum, 5 - i, so the numbers go down while i goes up. In Python, str turns the number into text before it is joined on. In Java, the brackets around 5 - i are needed: without them, Java joins the 5 onto the text first, then tries to take i away from text, and the program does not compile.
When to use for and when to use while
Use for when you know how many times the loop should run before it starts. Use while when the number of turns depends on something that happens inside the loop, like the user typing a stop value.
Now try it yourself on the questions below.
Exercise 3.5.13.5.1 · Write itPrint stars
Write a program that reads a number and prints that many stars on a single line.
- Read one number on a single line.
- Print a line of exactly that many
*characters, with nothing between them. - Use a loop to build the line one star at a time. Do not use string repetition (
*on a string in Python, or.repeatin Java).
The number is always 1 or more. Your program is run several times. Only what it prints is checked.
You cannot use these in this question:
- .__mul__()
- .__rmul__()
This question is about using a for loop, so string repetition shortcuts are not allowed.
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.
You cannot use these in this question:
- .repeat()
This question is about using a for loop, so string repetition shortcuts are not allowed.
Examples
Your program is run 6 times: the 3 examples below, and 3 hidden ones that check the rules above. Only what it prints is checked.
five stars (rule 2)
You type
- typed: 5
It prints
*****
one star (rule 2)
You type
- typed: 1
It prints
*
four stars (rule 2)
You type
- typed: 4
It prints
****
Exercise 3.5.23.5.2 · Write itRepeat message
Write a program that reads a message on the first line and a number on the second line, then prints the message that many times with line numbers starting from 1.
- Read the message (text) on the first line.
- Read the count (whole number) on the second line.
- Print each line as the line number, then a dot and a space, then the message.
- Line numbers start at 1 and go up to the count.
The count is always 1 or more. Your program is run several times. Only what it prints is checked.
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.
Examples
Your program is run 6 times: the 3 examples below, and 3 hidden ones that check the rules above. Only what it prints is checked.
three lines numbered 1 to 3 (rules 3 and 4)
You type
- typed: hello
- typed: 3
It prints
1. hello 2. hello 3. hello
one line (rule 4)
You type
- typed: test
- typed: 1
It prints
1. test
two lines (rule 4)
You type
- typed: bye
- typed: 2
It prints
1. bye 2. bye
Exercise 3.5.33.5.3 · Answer itFor vs while
(a) State when a programmer should use a for loop instead of a while loop. [1]
(b) Give one example of a task where a while loop is more suitable than a for loop. [1]
[2]