Kotlin For Loop


Kotlin For Loop

In this tutorial, we will learn about for loops in Kotlin. We will cover the basics of iterative execution using for loops.


What is a For Loop

A for loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop is typically used when the number of iterations is known before entering the loop.


Syntax

The syntax for the for loop in Kotlin is:

for (initialization; condition; increment) {
    // Code block to be executed
}

The for loop evaluates the initialization statement, then the condition. If the condition is true, the code block inside the loop is executed. After each iteration, the increment statement is executed, and the condition is re-evaluated. This process repeats until the condition becomes false.

Flowchart of For Loop


Printing Numbers from 1 to 10

  1. Declare an integer variable i.
  2. Use a for loop to print numbers from 1 to 10.

Kotlin Program

fun main() {
    for (i in 1..10) {
        print("$i ")
    }
}

Output

1 2 3 4 5 6 7 8 9 10 


Calculating the Factorial of a Number

  1. Declare an integer variable n and factorial.
  2. Assign a value to n.
  3. Initialize factorial to 1.
  4. Use a for loop to calculate the factorial of n.
  5. Print the factorial.

Kotlin Program

fun main() {
    val n = 5
    var factorial = 1
    for (i in 1..n) {
        factorial *= i
    }
    println("Factorial of $n is $factorial")
}

Output

Factorial of 5 is 120


Summing the Elements of an Array

  1. Declare an array of integers arr and an integer variable sum.
  2. Initialize the array with values.
  3. Initialize sum to 0.
  4. Use a for loop to calculate the sum of the elements in arr.
  5. Print the sum.

Kotlin Program

fun main() {
    val arr = intArrayOf(1, 2, 3, 4, 5)
    var sum = 0
    for (element in arr) {
        sum += element
    }
    println("Sum of the elements in the array is $sum")
}

Output

Sum of the elements in the array is 15