An Array Using while Loop in Kotlin

Iterating over the array’s items and carrying out several actions, such as printing the elements, summing values, or processing them in some way, is a frequent activity when working with arrays in Kotlin. The while loop is still a fundamental and necessary tool for accomplishing iteration, even if Kotlin offers a number of techniques and constructs to iterate over arrays, including the for loop, forEach, and functional programming styles. This lesson covers several examples and use cases for iterating over an array in Kotlin using the while loop.

What Is an Array in Kotlin?

Before diving into the iteration process, it’s important to understand what an array is in Kotlin. An array is a container that holds a fixed number of elements of the same type. Each element in an array can be accessed using its index, which starts from 0 and goes up to the size of the array minus one.

Here’s a quick example of how to create an array in Kotlin:

val numbers = arrayOf(1, 2, 3, 4, 5)

In this example, numbers is an array that contains the elements 1, 2, 3, 4, 5. You can access these elements using their index. For example, numbers[0] will return 1, and numbers[4] will return 5.

What Is a while Loop?

A while loop is a control flow structure that allows code to be executed repeatedly based on a condition. The basic syntax of a while loop in Kotlin is as follows:

while (condition) {
    // Code to be executed
}

The condition is evaluated before the execution of the loop’s body. If the condition evaluates to true, the loop will continue; otherwise, the loop will stop.

Iterating Over an Array with a while Loop

To iterate over an array using a while loop, we need to set up a counter (usually called index or i) to keep track of the current element. The loop will continue as long as the counter is less than the size of the array.

Here’s a simple example of how to iterate over an array using a while loop:

Example 1: Iterating Over an Array

fun main() {
    val numbers = arrayOf(10, 20, 30, 40, 50)
    var index = 0
    
    while (index < numbers.size) {
        println(numbers[index])
        index++
    }
}

Explanation:

  1. We define an array numbers containing five elements.
  2. A variable index is initialized to 0, which will serve as the counter.
  3. The while loop checks if the value of index is less than the size of the array. If it is, the loop will print the current element (numbers[index]) and increment index by 1.
  4. This process continues until the condition index < numbers.size evaluates to false, which happens when index becomes equal to the size of the array.

Output:

10
20
30
40
50

In this example, we printed all the elements of the array using a while loop.

Modifying Array Elements with while Loop

The while loop can also be used to modify the elements of an array during iteration. Let’s see an example where we multiply each element of the array by 2:

Example 2: Modifying Array Elements

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5)
    var index = 0
    
    while (index < numbers.size) {
        numbers[index] *= 2
        index++
    }
    
    println(numbers.joinToString())
}

Explanation:

  1. We define an array numbers containing the values 1, 2, 3, 4, 5.
  2. We use a while loop to iterate through the array.
  3. For each element, we multiply it by 2 and store the result back into the array.
  4. After modifying all the elements, we use the joinToString() function to print the array as a string.

Output:

2, 4, 6, 8, 10

The while loop in this example allows us to modify the elements of the array.

Breaking Out of a while Loop

In some cases, you may want to stop the loop when a certain condition is met, even if the loop has not reached the end of the array. For this, you can use the break statement, which immediately terminates the loop.

Let’s see an example where we stop the loop when we encounter a specific element in the array:

Example 3: Breaking Out of the Loop

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5)
    var index = 0
    
    while (index < numbers.size) {
        if (numbers[index] == 3) {
            println("Found 3! Stopping the loop.")
            break
        }
        println(numbers[index])
        index++
    }
}

Explanation:

  1. The loop iterates through the array.
  2. When the element 3 is encountered, the loop prints a message and terminates using the break statement.
  3. Elements before 3 are printed, but after finding 3, the loop stops.

Output:

1
2
Found 3! Stopping the loop.

Skipping Iteration with continue

Sometimes, you may want to skip certain elements during the iteration. The continue statement allows you to skip the rest of the current iteration and move on to the next one.

Let’s skip printing any even numbers in the following example:

Example 4: Skipping Iteration

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5)
    var index = 0
    
    while (index < numbers.size) {
        if (numbers[index] % 2 == 0) {
            index++
            continue
        }
        println(numbers[index])
        index++
    }
}

Explanation:

  1. The loop iterates through the array.
  2. When an even number is encountered, the continue statement is triggered, skipping the rest of the loop body and moving to the next iteration.
  3. Only odd numbers are printed.

Output:

1
3
5

In this case, the while loop skips even numbers.

Infinite while Loop

One thing to be cautious about when using while loops is creating an infinite loop by mistake. This happens when the loop condition is always true, or the counter is not updated correctly.

Here’s an example of an infinite loop:

fun main() {
    val numbers = arrayOf(1, 2, 3)
    var index = 0
    
    while (index < numbers.size) {
        println(numbers[index])
        // Forgetting to increment index
    }
}

Since index is never incremented, the loop will keep printing the first element of the array, leading to an infinite loop. To avoid such cases, ensure that your loop condition will eventually evaluate to false.

Nesting while Loops

You can also nest while loops within each other, which is useful for iterating over multi-dimensional arrays or performing more complex operations. Here’s an example where we iterate over a 2D array (an array of arrays):

Example 5: Nested while Loops for 2D Array

fun main() {
    val matrix = arrayOf(
        arrayOf(1, 2, 3),
        arrayOf(4, 5, 6),
        arrayOf(7, 8, 9)
    )
    
    var row = 0
    while (row < matrix.size) {
        var col = 0
        while (col < matrix[row].size) {
            print("${matrix[row][col]} ")
            col++
        }
        println()
        row++
    }
}

Explanation:

  1. We define a 2D array matrix.
  2. The outer while loop iterates over the rows of the matrix.
  3. The inner while loop iterates over the elements of each row.
  4. This results in printing the elements of the matrix in a row-wise manner.

Output:

1 2 3 
4 5 6 
7 8 9 

Conclusion

In this article, we explored the use of the while loop to iterate over arrays in Kotlin. The while loop is a flexible tool that can be used to perform a variety of tasks, from simply printing elements to modifying and filtering them based on conditions. While Kotlin provides more advanced constructs for iteration, understanding the fundamentals of the while loop is essential for working with arrays, especially in scenarios where a more traditional loop structure is required.

Key points covered include:

  • Basic iteration using a while loop.
  • Modifying array elements during iteration.
  • Using break to exit a loop early.
  • Skipping iterations using continue.
  • Avoiding infinite loops.
  • Nested while loops for multi-dimensional arrays.

By mastering the while loop, you will have a powerful tool in your toolkit for solving a wide variety of problems in Kotlin, especially when working with arrays.