First day and first attempt at using Scala - so go easy on me! I'm trying to rewrite some old Java code I have which is simply a function which takes two numbers and prints out the numbers from x to y. For example, i have the increment function:
def increment(start: Int, finish: Int) = {
for (i <- start to finish) {
println("Current value (increasing from "+start+" to "+finish+") is "+i)
}
}
However, im struggling writting a corresponding decrement function which will decrease from start to finish? I have read Scala downwards or decreasing for loop? but am still unsure
Thank you
scala>def decrement(start: Int, finish: Int) = {
| for (i <- start to finish by -1)
| println("Current value (decreasing from "+start+" to "+finish+") is "+i);
| }
decrement: (start: Int,finish: Int)Unit
scala> decrement(10, 1)
Current value (decreasing from 10 to 1) is 10
Current value (decreasing from 10 to 1) is 9
Current value (decreasing from 10 to 1) is 8
Current value (decreasing from 10 to 1) is 7
Current value (decreasing from 10 to 1) is 6
Current value (decreasing from 10 to 1) is 5
Current value (decreasing from 10 to 1) is 4
Current value (decreasing from 10 to 1) is 3
Current value (decreasing from 10 to 1) is 2
Current value (decreasing from 10 to 1) is 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With