For Loop and Its Usage in Kotlin
On this page (7sections)
Definition
In Kotlin, for loop is used for looping a certain block based on Range and Array.
Types of Usage
- Range Operator
- Range Operator with downTo
- Range Operator with step
- For loop for Array
- For loop for Array index
- For loop for String
Syntax
for (element in array) {
// body of loop
}
For Loop Example Program
// For Loop in Kotlin example program
// Loop and Control Statements Kotlin Programs, Basic Kotlin Programs
fun main(args: Array<String>) {
var num1 = 0
for (num1 in 1..5) {
println(" Value : $num1")
}
}
Sample Output
Value : 1
Value : 2
Value : 3
Value : 4
Value : 5
How It Works
This Kotlin program demonstrates For Loop and Its Usage. It first prepares the data it needs, then walks through the data with a loop to compute the result, and finally prints the output shown in the Sample Output above.
- Declare the variables that hold the program’s data.
- Iterate over the data using a loop to apply the logic.
- Print the final result to the console so you can compare it with the sample output.
Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.
Frequently Asked Questions
What is For Loop and Its Usage in Kotlin?
In Kotlin, for loop is used for looping a certain block based on Range and Array.
How do I run this Kotlin example?
Run it in IntelliJ IDEA or Android Studio, or compile from the command line with `kotlinc file.kt -include-runtime -d file.jar` and run `java -jar file.jar`.
How can I practice For Loop and Its Usage?
Copy the example into IntelliJ IDEA or Android Studio, run it, then change the values or add print statements to see how the output changes.