Kotlin Training Program

DOWNLOAD APP

FEEDBACK

for Loop

for loop can be used for custom range of loop variable. For example - (5 to 10), (25 to -10), (2, 4, 6, 8, …, 20). Syntax :

 for (/* Loop variable */ in /* Range */) {
    // Code
}
 

Examples :

 fun main() {
		for (i in 5..10) {
		    print("$i, ")
		}
		// Output : 5, 6, 7, 8, 9, 10,
		
		for (i in 5 until 10) {
		    print("$i, ")
		}
		// Output 5, 6, 7, 8, 9:
		
		for (i in 3 downTo -2) {
		    print("$i, ")
		}
		// Output : 3, 2, 1, 0, -1, -2,
		
		for (i in 2..10 step 2) {
		    print("$i, ")
		}
		// Output : 2, 4, 6, 8, 10,
}
 

Note :

Program to print Multiplication Table of a number :

 fun main() {
    val n = 6
    for (i in 1..10) {
        println("$n X $i = ${n * i}")
    }
}

/* Output :

6 X 1 = 6
6 X 2 = 12
6 X 3 = 18
6 X 4 = 24
6 X 5 = 30
6 X 6 = 36
6 X 7 = 42
6 X 8 = 48
6 X 9 = 54
6 X 10 = 60
*/