Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment for-loop by 2 in Scala

Tags:

for-loop

scala

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.

like image 880
cYn Avatar asked Jul 22 '13 15:07

cYn


People also ask

Can I increment 2 in for loop?

A for loop doesn't increment anything. Your code used in the for statement does.

What is the ++ operation in Scala?

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_= ).

Can I increment by 2 in a for loop in Java?

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.

How do we increment loops?

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.


1 Answers

Try for (a <- 0 until max by 2)

like image 143
tkroman Avatar answered Sep 22 '22 21:09

tkroman