Plaban
Plaban

Reputation: 97

How to multiply all integer values in a Range in Kotlin?

I created a range of integer value. Now I don't know how can I multiply those numbers and print them.

Upvotes: 2

Views: 2873

Answers (1)

Willi Mentzel
Willi Mentzel

Reputation: 29844

A really handy way to multiply all values of an Iterable or range is to use reduce:

val m = (1..4).reduce { accumulator, element ->
    accumulator * element
}

println(m)

This would print:

24

The accumulator is initially the first value of the range. This will be multiplied with the next element and becomes the accumulator for the next run.

Upvotes: 8

Related Questions