The for loop in Kotlin is used to iterate or cycle though the elements ofarray,ranges, collections etc. In this guide, we will learn how to use for loop in Kotlin with the help of various examples. A simple example of for loop in Kotlin In the following example we are iterating though...
The syntax offorloop in Kotlin is: for (item in collection) { // body of loop } Example: Iterate Through a Range funmain(args:Array<String>){for(iin1..5) { println(i) } } Here, the loop iterates through the range and prints individual item. ...
Kotlin – For i in range Kotlin – Infinite While loop Examples In the following, we cover examples for each of the looping statements, break and continue statements. 1. For Loop Example – Iterate over elements of a list In the following program, for loop is used to print each item of ...
Kotlin For LoopOften when you work with arrays, you need to loop through all of the elements.To loop through array elements, use the for loop together with the in operator:Example Output all elements in the cars array: val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda") for (x ...
In the example, we generate a random number. Based on the random value, we print a message to the console. Kotlin while loopThe while keyword is used to create a loop. It runs until the given condition is met. while_loop.kt package com.zetcode fun main() { var i:Int = 0 while(...
Kotlin For Loop - Learn how to use the for loop in Kotlin with detailed examples and explanations. Enhance your programming skills with practical coding techniques.
In the final example, we used when i.e. switch statement is used to print the case statement on the console with forEach loop iteration. Conclusion In the kotlin language, we used different kinds of loops to store and retrieve the elements for the iterating process. Also, the iteration st...
In this example, we have two nested for loops. The inner loop will break when both i equals 1 and j equals 1. Therefore, the output will show values for i and j until that condition is met. This method is useful when you want to exit just one level of the loop while keeping the...
In Kotlin, You can useifas an expression instead of a statement. For example, you can assign the result of anif-elseexpression to a variable. Let’s rewrite theif-elseexample of finding the maximum of two numbers that we saw in the previous section as an expression - ...
Working of ranged for loop in C++ Example 1: Ranged for Loop Using Array #include<iostream>usingnamespacestd;intmain(){// initialize arrayintnumArray[] = {1,2,3,4,5};// use of ranged for loop to print array elementsfor(intn : numArray) {cout<< n <<" "; ...