Kotlin For Loop
Overview
A for loop is like a set of instructions that you give to a computer program to automate the repeating task for you. A for loop is a fundamental control flow statement in computer programming that allows you to perform a task multiple times or iterate over a range, collection, or any other type of iterable element. It provides a convenient way to perform repetitive tasks by executing a block of code for each element in the specified range or collection.
Syntax of "for" Loop in Kotlin
The basic idea behind a for loop is to set up an iteration variable and define the range or collection of values to iterate over. The loop will then execute the code block for each value in the range or collection.
Kotlin supports iteration over arrays, ranges, collections, arrays, etc. because of which it has multiple syntaxes for the for loop.
The simplest and most commonly used syntax of the for loop in kotlin is as follows using the in keyword.
Here it takes each element one by one from the collection and stores it in the item variable. It then executes the body of the loop on each item.
Example: Iterate Through a Range
In Kotlin, you can use a for loop to iterate over a range of values. A range is defined using the ".." operator, and it represents a sequence of values starting from a specified start value and ending at a specified end value, both inclusive.
We can iterate in forward as well as reverse order. We can also use until to exclude the last value of the range.
Example: Different Ways to Iterate Through a Range
Example - 1: Iterating Using "in" Keyword
To iterate over a range of elements we can use the in keyword and ".." to define the range. Look at the example below:
Code:
Output:
Explanation:
Here x is the variable used for iteration. The iteration starts with 7 and goes till 14 in the first loop. The in keyword includes the starting value as well as the ending value of the range.
We can also use characters in range values as shown in the second example.
Example - 2: Iterating Using the "until" Keyword
If we wish to omit the last value of the range to be iterated by the loop we can use the until keyword. Look at the example below:
Code:
Output:
Explanation:
Here, though 14 is there in range, it stops the iteration as soon as it reaches 14 and doesn't run the body of the loop, unlike the in keyword.
Example - 3: Iterating Using the "downTo" Keyword
The for loop in Kotlin allows us to traverse the range in reverse order we can make use of the downTo keyword. It acts just like the in keyword except that it iterates from maximum value to minimum value. The starting value of the variable must be written first as usual.
Have a look at the example below:
Code:
Output:
Example - 4: Using the "step" Keyword in "for" Loop
We can also use the step keyword to the inside for loop in kotlin to traverse the range by specifying a custom increment or step size for iterating over a range of values. step can be used with downTo, in, as well as until.
Code:
Output:
Explanation:
In the example above, we are beginning with 17, and with each iteration, we are decreasing the value of x by 4. Thus, we get 17 - 4 = 13.
Iterating Through an Array
In Kotlin, the for loop can be used to iterate through various types of collections, including arrays. When iterating through an array using a for loop, the loop will go through each element of the array, allowing you to perform a specific task or operation on each element.
Example - 1: Iterating Through an Array
We can traverse the array by simply using the in keyword as we did for range. Let us create an array using the arrayOf() method and traverse the array to filter elements of the array.
Code:
Output:
Explanation:
In the example above we have first created an array of fruits. Next, we use a for loop to traverse through the array. If the fruit doesn't start with a vowel we print the fruit to the output.
Example - 2: Iterating Using Indices
We can also traverse the array using indices as follows:
Code:
Output:
Explanation:
Here, fruits.indices returns the indices for each element, and using [] square brackets we can traverse through the array. It is used when we wish to skip some indices.
Example - 3: Iterating with Indices and Elements
We can also use for loop to get indices and values. Look at the example below:
Code:
Output:
Explanation:
The withIndex() returns a key-value pair of index and item of an array. As the indexing starts from 0 we are adding 1 to it and printing the list of fruits with the count.
Iterating Through a String
The for loop in Kotlin supports the traversal of the string as well. It will visit each character present in the String.
Code:
Output:
Explanation:
We can use all the functionalities of the array for loop for a string such as indices and withIndex().
The first for loop is a simple for loop that traverses each character of the string. The second for loop returns each index of the string using which all the characters can be accessed. The third loop returns the index as well as the character for each element(character) in the string.
Iterate Through Collection
In Kotlin, you can use the for loop to iterate through various types of collections, such as lists, sets, maps, and other iterable objects. The for loop in Kotlin will go through each element or key-value pair (in the case of maps) in the collection, allowing you to work with each item one by one.
Iterate Through a List
In Kotlin, a list is a collection that represents an ordered group of elements. Lists are used to store multiple items of the same type in a specific order. They are one of the most commonly used collection types in Kotlin. We can traverse the list using the in keyword inside the for loop.
Code:
Output:
Explanation:
The in keyword is used in the for loop to iterate through the list.
Iterate Through a Set
In Kotlin, a set is another type of collection that represents an unordered group of unique elements. Unlike lists, sets do not allow duplicate elements, meaning each element can appear only once in a set.
To traverse a set in Kotlin, we can use a for loop with the in keyword. The for loop will automatically go through each element of the set, allowing you to perform a specific action on each item.
Code:
Output:
Explanation:
Here, we are using the in keyword to get each item of the set using a for loop and print the item.
Iterate Through a Map
Maps store key-value pairs, and the for loop in kotlin lets us access each key-value pair one by one. Traversing a Map in Kotlin is achieved using a for loop with the in keyword. The loop variable represents the current key-value pair, and you can perform specific actions on each entry within the loop.
Code:
Output:
Explanation:
Here, the for loop returns the key-value pairs present in the map, one after the other.
Conclusion
- The for loop in Kotlin is used to iterate over a range, collection, or any other type of iterable element.
- It provides a convenient way to perform repetitive tasks by executing a block of code for each element in the specified range or collection.
- The in keyword is used inside the for loop to traverse lists, sets, arrays, strings, and other iterable collections.
- The loop variable represents the current element or key-value pair, allowing you to perform specific actions on each item.
- For ranges, you can use .. or until to specify the start and end values and steps to define a custom increment.
- You can also traverse arrays using indices or use withIndex() to get both indices and values.
- Maps can be traversed using a for loop, and each iteration provides access to key-value pairs using destructuring.