user3386040
user3386040

Reputation:

A "for" loop with two variables, one increments every iteration and the increments every other iteration

I can't seem to figure out a way to write a "for" loop that has two variables (i and j). I want i to increment by adding one every time, and j to increment by adding one every other time that i increments. Any ideas? (I've already tried a nested loop, or having them both initialized in the same condition statement.)

Upvotes: 2

Views: 2227

Answers (2)

Sebastian Redl
Sebastian Redl

Reputation: 71899

Here goes a hacky way:

for (int i = 0, j = 0; i < N; j += i % 2, ++i) {}

This increments j at the end of every iteration where i had an odd value.

Upvotes: 4

ratchet freak
ratchet freak

Reputation: 48196

one way would be to do the following:

for(i=0, j=0; i<max; j += ((++i)&1) ){

}

here j will be incremented when i is even, if you want to increment j when i is odd then use the post increment

Upvotes: 0

Related Questions