Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn kotlin For Loops


Sure! The for loop in Kotlin is used to iterate over a range, array, or any other iterable collection. Here's a simple explanation with examples:

Syntax

Example

for (item in collection) {
// Code to be executed for each item in the collection
}

Example 1: Iterating over a Range

Let's say we want to print numbers from 1 to 5 using a for loop:

Example

fun main() {
for (i in 1..5) { // Range: 1 to 5
println("Number: $i")
}
}

OutPut

Example

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Example 2: Iterating over an Array

Let's say we have an array of colors and we want to print each color:

Example

fun main() {
val colors = arrayOf("Red", "Green", "Blue", "Yellow", "Orange")
for (color in colors) {
println("Color: $color")
}
}

OutPut

Color: Red
Color: Green
Color: Blue
Color: Yellow
Color: Orange

Example 3: Iterating over a Collection with Index

If you need both the index and the item, you can use the withIndex() function:

fun main() {
val fruits = listOf("Apple", "Banana", "Orange")
for ((index, fruit) in fruits.withIndex()) {
println("Index: $index, Fruit: $fruit")
}
}

OutPut

Index: 0, Fruit: Apple
Index: 1, Fruit: Banana
Index: 2, Fruit: Orange

Conclusion

The for loop in Kotlin is versatile and allows you to iterate over ranges, arrays, lists, and other iterable collections with ease. It simplifies the process of performing operations on each item in a collection and is a fundamental construct in Kotlin programming.

Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java