Kotlin example of reversed() function with integer, character range

Learn the use of reversed() function with integer, character range in Kotlin.
Submitted by IncludeHelp, on March 26, 2022

reversed() Function

The reversed() function reverses the given range type, we can use reversed() function instead of downTo() function. Here, we will demonstrate how to print an integer, character range in reversed /descending order using reversed() function?

Example 1:

fun main(args: Array<String>) {
	// Creating an integer range
	var int_range = 1..10

	// Printing the range
	print("Range is: ")
	for (value in int_range){
		print("$value ")
	}    
	// Printing the range in reverse order
	print("\nReverse Range is: ")    
	for (value in int_range.reversed()){
		print("$value ")
	}
}

Output:

Range is: 1 2 3 4 5 6 7 8 9 10 
Reverse Range is: 10 9 8 7 6 5 4 3 2 1 

Example 2:

fun main(args: Array<String>) {
	// Creating a character range
	var chr_range = 'a'..'p'

	// Printing the range
	print("Range is: ")
	for (value in chr_range){
		print("$value ")
	}    
	// Printing the range in reverse order
	print("\nReverse Range is: ")    
	for (value in chr_range.reversed()){
		print("$value ")
	}
}
Range is: a b c d e f g h i j k l m n o p 
Reverse Range is: p o n m l k j i h g f e d c b a 

Kotlin Ranges Programs »




Comments and Discussions!

Load comments ↻





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