for Loops
The for loop in Kotlin operates in much the same way as Python’s for
loop. It is quite different from C’s for loop (which is effectively just a
different way of writing a while loop).
We’ll see more for loops later, when we explore collection types.
For now, let us concentrate on two particular examples: iterating over the
characters in a string, and iterating over an integer range.
Here is how you could use a for loop to print each character from a
string on a separate line:
val message = "Hello!"
for (character in message) {
println(character)
}
Notice that character is not declared as a val or var here; indeed, it
would be an error to do so. The loop variable of a for loop is
implicitly a val.
Here is a traditional ‘counting’ loop, using for and a closed integer
range, with the closest equivalent in Python provided for comparison:
for (n in 1..10) {
println(n)
}
for n in range(1, 11):
print(n)
This works because Kotlin can treat integer ranges as progressions, in which there are clearly-defined values between the start and end points of the range. Those values are generated by repeated addition of a step, which has a default value of 1.
You can supply your own value for this step. For example, to print only the even integers between 2 and 20, you could do
for (n in 2..20 step 2) {
println(n)
}
for n in range(2, 21, 2):
print(n)
It is also possible to create descending progressions, using the downTo
function. Here’s a small example1, with its closest equivalent in
Python:
for (n in 10 downTo 1) {
println(n)
}
for n in range(10, 0, -1):
print(n)
You can also use step with downTo:
for (n in 10 downTo 1 step 2) {
println(n)
}
for n in range(10, 0, -2):
print(n)
Note that the value used with step is always positive.
It is important to understand that iteration with a for loop is not
supported for all types of range, because not all of them can be treated
as progressions.
For example, you can iterate over a range with Char or Int endpoints,
but you cannot iterate over a range with Float or String endpoints.
Task 4.5
Create a file named OddSum.kt, in the tasks/task4_5 subdirectory of
your repository.
In this file, write a Kotlin program that uses a for loop to sum up all of
the odd integers between 1 and some user-specified limit. You program should
prompt the user to input this upper limit, and it should print the result
of the summation.
Check that the program behaves as expected, and fix any problems that you observe.
Be sure to try some reasonably large values for the upper limit.
You may observe some surprising behaviour here, if you haven’t thought carefully enough about the type of value used to represent the sum…
-
Although it might not look like it,
10 downTo 1is indeed a function call, made using infix notation. When a function is called with infix notation, we are allowed to omit the dot operator and the parentheses. We could have avoided infix notation and written this instead as10.downTo(1). ↩