How do I use ranges and step values in Kotlin for loops?

In Kotlin, you can use ranges and step values in for loops to iterate over a sequence of numbers or characters. Here’s a detailed guide:

1. Ranges in Kotlin

A range is defined using the .. operator. For example:

for (i in 1..5) {
    println(i)
}
  • Output: 1 2 3 4 5
  • The loop iterates from 1 to 5 (both inclusive).

2. Stepping Through a Range

To define the step value, you can use the step function. For instance:

for (i in 1..10 step 2) {
    println(i)
}
  • Output: 1 3 5 7 9
  • The loop starts from 1 and increments by 2 on each iteration.

3. Descending Ranges

If you want to iterate in reverse order, use the downTo function:

for (i in 10 downTo 1) {
    println(i)
}
  • Output: 10 9 8 7 6 5 4 3 2 1

You can combine downTo with step:

for (i in 10 downTo 1 step 2) {
    println(i)
}
  • Output: 10 8 6 4 2

4. Iterating Over Characters

Kotlin ranges also work with characters:

for (ch in 'a'..'e') {
    println(ch)
}
  • Output: a b c d e

You can also provide a step value:

for (ch in 'a'..'z' step 3) {
    println(ch)
}
  • Output: a d g j m p s v y

5. Using until

The until function creates a range that excludes the upper boundary:

for (i in 1 until 5) {
    println(i)
}
  • Output: 1 2 3 4
  • The loop stops before reaching 5.

Summary of Functions and Keywords

  1. ..: Creates a range that includes the start and end values.
  2. downTo: Creates a descending range.
  3. step: Sets the step value for the range.
  4. until: Excludes the upper boundary of the range.

These features make Kotlin’s for loops flexible and expressive.

How do I loop through items using for and while in Kotlin?

In Kotlin, you can use both for and while loops to iterate through items. Here is a quick overview of how you can use these loops with examples:


1. Using a for Loop

A for loop is used to iterate through a range, array, list, or any iterable.

Iterating through a range:

for (i in 1..5) {
    println("Current number is $i")
}
  • 1..5 creates a range from 1 to 5 (inclusive).
  • You can also use until to exclude the end value:
for (i in 1 until 5) {
    println("Current number is $i") // 1 to 4
}
  • To iterate in reverse, use the downTo keyword:
for (i in 5 downTo 1) {
    println("Countdown: $i")
}
  • To skip steps, use the step keyword:
for (i in 1..10 step 2) {
    println("Step: $i")
}

Iterating through a list or array:

val items = listOf("Apple", "Banana", "Orange")
for (item in items) {
    println(item)
}

Iterating with index:

val items = arrayOf("A", "B", "C")
for ((index, value) in items.withIndex()) {
    println("Index: $index, Value: $value")
}

2. Using a while Loop

A while loop is used when you want to execute a block of code as long as a condition is true.

Example of a while loop:

var counter = 1
while (counter <= 5) {
    println("Count: $counter")
    counter++
}

Example of a do-while loop:

The do-while loop ensures the block of code executes at least once.

var counter = 1
do {
    println("Count: $counter")
    counter++
} while (counter <= 5)

Summary of Differences:

  • for Loop: Best for iterating over ranges, collections, and when the number of iterations is known.
  • while (and do-while) Loop: Best for scenarios where the number of iterations depends on a condition.

Why do I get ArrayIndexOutOfBoundsException in Java?

The ArrayIndexOutOfBoundsException exception is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Array with 10 elements

For example see the code snippet below:

String[] vowels = new String[]{"a", "i", "u", "e", "o"}
String vowel = vowels[10]; // throws the ArrayIndexOutOfBoundsException

Above we create a vowels array with five elements. This will make the array have indexes between 0..4. On the next line we tried to access the tenth element of the array which is illegal. This statement will cause the ArrayIndexOutOfBoundsException thrown.

We must understand that arrays in Java are zero indexed. The first element of the array will be at index 0 and the last element will be at index array-size - 1. So be careful with your array indexes when accessing array elements. For example if you have an array with 5 elements this mean that the index of the array is from 0 to 4.

If you are trying to iterate an array using for loop. Make sure the index start from 0 and execute the loop while the index is less than the length of the array, you can get the length of the array using the array length property. Let’s see the code snippet below:

for (int i = 0; i < vowels.length; i++) {
    String vowel = vowels[i];
    System.out.println("vowel = " + vowel);
}

Or if you don’t need the index you can simplify your code using the for-each or enhanced for-loop statement instead of the classic for loop statement as shown below:

for (String vowel : vowels) {
    System.out.println("vowel = " + vowel);
}