Arrays, loops

We have two numbers a and b that need to be set via the console. And then print the sum of all numbers from a to b. For example a = 13 b = 17. Result: 13+14+15+16+17 = 75 I wonder how this is done

The idiomatic Kotlin way to sum all numbers from a to b would be:

val sum = (a..b).fold(0) { acc, value -> acc + value }

You define a range [a,b] and then sum all numbers up.
To read a number from the stdin you could use the following:

val number = readLine()?.toInt()
  ?: throw IllegalStateException("stdin is not available.")

From a performance point of view, it might be better to use this approach:

For the “idiomatic” approach, one could even go with

val sum = (a..b).sum()
2 Likes