Loops/With multiple ranges: Difference between revisions

Content added Content deleted
(Added Chipmunk Basic)
Line 1,843: Line 1,843:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Nothing special here, just a series of individual for loops.
Using a series of individual for loops:
<syntaxhighlight lang="scala">// Version 1.2.70
<syntaxhighlight lang="kotlin">// Version 1.2.70


import kotlin.math.abs
import kotlin.math.abs
Line 1,879: Line 1,879:
for (j in x downTo y step -z) process(j)
for (j in x downTo y step -z) process(j)
for (j in p..p + one) process(j)
for (j in p..p + one) process(j)
System.out.printf("sum = % ,d\n", sum)
System.out.printf("prod = % ,d\n", prod)
}</syntaxhighlight>

{{output}}
<pre>
sum = 348,173
prod = -793,618,560
</pre>

The following version does it in a similar way to PL/I and Algol-60, i.e. without defining a function to process the loop, using a _single_ loop, and without creating a list from which to iterate:
<syntaxhighlight lang="kotlin">
import kotlin.math.abs
import kotlin.math.pow

private infix fun Int.`^`(exponent: Int): Int = toDouble().pow(exponent).toInt()

fun main() {
var prod = 1
var sum = 0
val x = 5
val y = -5
val z = -2
val one = 1
val three = 3
val seven = 7
val p = 11 `^` x

for (j in sequenceOf(
-three..(3 `^` 3) step three,
-seven..seven step x,
555..550-y,
22 downTo -28 step three,
1927..1939,
x downTo y step -z,
p..p + one
).flatten()) {
sum += abs(j)
if (abs(prod) < (2 `^` 27) && j != 0) prod *= j
}
System.out.printf("sum = % ,d\n", sum)
System.out.printf("sum = % ,d\n", sum)
System.out.printf("prod = % ,d\n", prod)
System.out.printf("prod = % ,d\n", prod)