For loop in C++ vs Kotlin

Let's compare how the standard For loop works in Kotlin and C++

In C++, you can use a for loop to iterate over a range of values as follows:

for (int i = 0; i < 10; i++) { 
	// code to be executed 
}

This for loop will iterate from 0 to 9 (inclusive). The loop variable i is initialized to 0, and the loop will continue to execute as long as i < 10 is true. The value of i is incremented by 1 at the end of each iteration.

In Kotlin, you can use a for loop in a similar way as follows:

for (i in 0 until 10) { 
	// code to be executed 
}

This for loop will iterate from 0 to 9 (exclusive). The loop variable i is automatically initialized to the values in the range 0 until 10. The loop will continue to execute as long as there are more values in the range.

Alternatively, you can also use the step function to specify the increment for the loop variable as follows:

for (i in 0 until 10 step 2) { 
	// code to be executed 
}

This for loop will iterate from 0 to 8 (exclusive) in steps of 2. The loop variable i will take on the values 0, 2, 4, 6, and 8 in each iteration.

You can also use a for loop to iterate over an array in Kotlin as follows:

val numbers = arrayOf(1, 2, 3, 4, 5) 
for (number in numbers) { 
	// code to be executed 
}

In this example, the loop variable number will take on the values 1, 2, 3, 4, and 5 in each iteration.

You can create a downTo for loop in Kotlin using the downTo function on an Int range. Here's an example:

for (i in 10 downTo 1) {
    println(i)
}

This will print the numbers 10 through 1 (inclusive) on separate lines. The downTo function creates a range of integers that decrements by 1 with each iteration of the loop. You can also specify a step value, like this:

for (i in 10 downTo 1 step 2) {
    println(i)
}

This will print the numbers 10, 8, 6, 4, 2.

You can also use downTo with forEach

(10 downTo 1).forEach {
    println(it)
}

This will also print the numbers 10 through 1 (inclusive) on separate lines.