top of page

Loops in Kotlin - Kotlin Assignment Help

Updated: Feb 15, 2023



The loop is used to execute a specific block of code repeatedly until a certain condition is met. If you have to print counting from 1 to 100 then you have to write the print statement 100 times. But with help of a loop, you can save time and you need to write only two lines.


While loop – It consists of a block of code and a condition. First of all the condition is evaluated and if it is true then execute the code within the block is. It repeats until the condition becomes false because every time the condition is checked before entering into the block. The while loop can be thought of as a repeating if statement.


The syntax of the while loop-

while(condition) {
           // code to run
}


Kotlin program to print numbers from 1 to 10 using while loop:


fun main(args: Array<String>) {
    var number = 1
 
    while(number <= 10) {
        println(number)
        number++;
    }
}

Output:

1
2
3
4
5
6
7
8
9
10


Kotlin do-while loop:

do-while loop working – First, all the statements within the block are executed, and then the condition is evaluated. If the condition is true the block of code is executed again. The process of execution of the code block is repeated as long as the expression evaluates to true.


Syntax of the do-while loop-

do {
      // code to run
}
while(condition)

Kotlin program to find the factorial of a number using a do-while loop –

fun main(args: Array<String>) {
    var number = 6
    var factorial = 1
    do {
        factorial *= number
        number--
    }while(number > 0)
    println("Factorial of 6 is $factorial")
}

Output:

Factorial of 6 is 720


Kotlin for loop:

In Kotlin, for loop is equivalent to foreach loop of other languages It is used very differently than the for loop of other programming languages like Java or C.

The syntax of for loop in Kotlin:


for(item in collection) {
       // code to execute
}              

Iterate through the range to print the values:


fun main(args: Array<String>)
{
    for (i in 1..6) {
        print("$i ")
    }
}
Output:
1 2 3 4 5 6

Hope you understand the loops and the syntax of kotlin in the next blog we are going to learn exception handling in kotlin.

Thank you!


The journey of solving bug and completing project on time in Kotlin can be challenging and lonely. If you need help regarding other sides to Kotlin, we’re here for you!


Drop an email to us at contact@codersarts.com with the Project title, deadline, and requirement files. Our email team will revert back promptly to get started on the work.

Comments


bottom of page