Looping & Ranges

The for keyword repeats a loop by iterating over a sequence of values.

This set of values can be a range of integers, a string, or, as we’ll see later in the book, a collection of items. We use the in keyword to indicate stepping through values:

for (v in values)

Each time through the loop, v is given the next element in values.

Here, a for loop repeats an action a fixed number of times:

// ForAndRanges/RepeatThreeTimes.kt fun main(args: Array<String>) { for (i in 1..3) println("Hey $i!") } /* Output: Hey 1! Hey 2! Hey 3! */

The output shows the index i receiving each value in the range from 1 to 3. Each of these values is used in the loop.

A range is an interval of values defined by a pair of endpoints. There are two main ways to define ranges:

// ForAndRanges/DefiningRanges.kt fun main(args: Array<String>) { val range1 = 1..10 // [1] val range2 = 0 until 10 // [2] println(range1) println(range2) } /* Output: 1..10 0..9 */

Printing a range conveniently displays the range in a readable format.

Here, we sum the numbers from 10 to 100:

// ForAndRanges/SumUsingRange.kt fun main(args: Array<String>) { var sum = 0 for (n in 10..100) sum += n println("sum = $sum") } /* Output: sum = 5005 */

You can iterate over a range with a step or in reverse order:

// ForAndRanges/ForWithRanges.kt fun showRange(r: IntProgression) { for (i in r) print("$i ") print(" // $r") println() } fun main(args: Array<String>) { showRange(1..5) showRange(0 until 5) showRange(5 downTo 1) // [1] showRange(0..9 step 2) // [2] showRange(0 until 10 step 3) // [3] showRange(9 downTo 2 step 3) } /* Output: 1 2 3 4 5 // 1..5 0 1 2 3 4 // 0..4 5 4 3 2 1 // 5 downTo 1 step 1 0 2 4 6 8 // 0..8 step 2 0 3 6 9 // 0..9 step 3 9 6 3 // 9 downTo 3 step 3 */

In each case, the sequence of numbers form an arithmetic progression, so showRange() accepts an IntProgression argument, which is a general type that includes Int ranges.

You can iterate over a range of characters. Here, we iterate from a to z using for:

// ForAndRanges/ForWithCharRange.kt fun main(args: Array<String>) { for (c in 'a'..'z') print(c) } /* Output: abcdefghijklmnopqrstuvwxyz */

You can iterate over a range of elements which are whole quantities, like integers and characters, but not floating-point values.

Square brackets access characters by index. Because we start counting characters in a string at zero, s[0] selects the first character of the string s. s.lastIndex produces the final index number:

// ForAndRanges/IndexIntoString.kt fun main(args: Array<String>) { val s = "abc" for (i in 0..s.lastIndex) print(s[i] + 1) } /* Output: bcd */

Sometimes people say s[0] more precisely as “the zeroth character.”

Characters are stored as numbers corresponding to their ASCII codes, so adding an integer to a character produces a new character corresponding to the new code value:

// ForAndRanges/AddingIntToChar.kt fun main(args: Array<String>) { val ch: Char = 'a' println(ch + 25) println(ch < 'z') } /* Output: z true */

The second println() shows that you can compare character codes.

A for loop can iterate over strings directly:

// ForAndRanges/IterateOverString.kt fun main(args: Array<String>) { for (ch in "Jnskhm ") print(ch + 1) } /* Output: Kotlin! */

When you iterate over a string, ch receives each character in turn.

The function hasChar() below iterates over the string s and checks whether it contains a given character ch. The return in the middle of the function stops the function when the answer is found:

// ForAndRanges/HasChar.kt fun hasChar(s: String, ch: Char): Boolean { for (c in s) if (c == ch) return true return false } fun main(args: Array<String>) { println(hasChar("kotlin", 't')) println(hasChar("kotlin", 'a')) } /* Output: true false */

The next atom shows that hasChar() is unnecessary—you can use built-in syntax instead.

If you simply want to repeat an action a fixed number of times, you may use repeat instead of a for loop:

// ForAndRanges/Repeat.kt fun main(args: Array<String>) { repeat(2) { println("hi!") } } /* Output: hi! hi! */
repeat is not a keyword, but rather a function from the standard library. We’ll show how it was created much later in the book.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.