Kotlin For Loop

For loop are used to iterator instruction over respect to collection and condition. Collection is like a array, lists, sets in kotlin programming. and condition is depends upon a specified range. Using of this definition we can describe of for loop syntax as follows.

for(item in collection/condition){
//loop statements
}

For loop examples

let's takes examples of different situation to use for loop in our program.

Example 1: Display of array elements.

fun main(args: Array<String>) {
  //create an array of 5 integers
    var collection:Array<Int> =arrayOf(10,12,30,14,50)
  
  for(item in collection){
    //Display array element 
    println(item)
  }
}

Output

10
12
30
14
50

In this example display array element. But note that every element of array are index. And some special cases we can need to use index of array element inside a for loop. Here given solution to display array index.

fun main(args: Array<String>) {
  //create an array of 5 integers
   var collection:Array<Int> =arrayOf(10,12,30,14,50)
  //indices is used for index
  for(item in collection.indices){
    //Display array element 
    println(item)
  }
}

Output

0
1
2
3
4

Example 2: Execute loop between ranges

For loop are also used to iterate group of statement between specified ranges. In general case, Suppose we are need to execute loop in ten times. So we can use this way.

fun main(args: Array<String>) {
  
  var size:Int=10
  // set range from ( 1 to size)
  for(item in 1..size){
    //loop logic here
    println(item*2)
  }
}

Output

2
4
6
8
10
12
14
16
18
20

In this example (1..size) is set execution between of this ranges. This is user define condition. We can modified this range. 1 is indicates start point of the range. And size is indicates terminating point of the range.

Example 3: Iterate a string element

fun main(args: Array<String>) {
  
  var alphabets="ABCXYZ"
  for(ch in alphabets){
    println(ch) //display char one by one
  }
}

Output

A
B
C
X
Y
Z

Nested For Loop

Nested means the one loop are define inside other loops. We can define multiple nested loop depending to situation. let view one example.


fun main(args: Array<String>) {
    //Outer loop
    for (base in 2..5){
        //inner loop
        for(multiplier in 1..base){
            println("$base X $multiplier : ${base*multiplier}")
        }
    }
}

Output

2 X 1 : 2
2 X 2 : 4
3 X 1 : 3
3 X 2 : 6
3 X 3 : 9
4 X 1 : 4
4 X 2 : 8
4 X 3 : 12
4 X 4 : 16
5 X 1 : 5
5 X 2 : 10
5 X 3 : 15
5 X 4 : 20
5 X 5 : 25


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved