How do I increment the loop by 2 as equivalent to this in Java:
for (int i = 0; i < max; i+=2)
Right now in Scala I have:
for (a <- 0 to max)
For a fact max
will always be even. I don't know how to increment the counter to 2 in each loop.
A for loop doesn't increment anything. Your code used in the for statement does.
Also, Scala encourages immutable variables, and ++ is intrinsically a mutating operation. If you require += , at least you can force all your mutations to go through a common assignment procedure (e.g. def a_= ).
In the next line, for loop is declared that starts from 1 and ends when the value of i is less than n and inside this loop the index value of variable i is increment by 2. Inside the loop, the print function is used, which uses variable i to prints its increment value.
Increment is an expression that determines how the loop control variable is incremented each time the loop repeats successfully (that is, each time condition is evaluated to be true). The for loop can proceed in a positive or negative fashion, and it can increment the loop control variable by any amount.
Try for (a <- 0 until max by 2)
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