Kotlin program of integer range using downTo() function

Learn how to create integer range using downTo() function in Kotlin?
Submitted by IncludeHelp, on March 26, 2022

downTo() Function

The downTo() function is used for creating a range in descending order i.e., from the given larger value to the smaller value. The downTo() function is the reverse of the (..) operator and rangeTo() function.

Here, we will demonstrate the example of creating an integer range using the downTo() function.

Example 1:

fun main(args : Array<String>){
	// creating integer ranges 
	// in descending order
	println("Integer range 1:")	
	for(x in 10.downTo(1)){
		println(x)
	}
	println()

	println("Integer range 2:")	
	for(x in 5.downTo(-5)){
		println(x)
	}
	println()
}

Output:

Integer range 1:
10
9
8
7
6
5
4
3
2
1

Integer range 2:
5
4
3
2
1
0
-1
-2
-3
-4
-5

Example 2:

fun main(args : Array<String>){
	// creating integer ranges
	// in descending order
	println("Integer range 1:")	
	for(x in 10.downTo(1) step 2){
		println(x)
	}
	println()

	println("Integer range 2:")	
	for(x in 5.downTo(-5) step 2){
		println(x)
	}
	println()
}

Output:

Integer range 1:
10
8
6
4
2

Integer range 2:
5
3
1
-1
-3
-5

Kotlin Ranges Programs »


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.