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.)
2 Answers
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.
2 Comments
ratchet freak
isn't there sequence point issues in the increment here with the comma operator?
Sebastian Redl
No, the comma operator introduces sequencing.
i / 2instead ofj?for (int i = 5; i <= 36; ++i) { if (i & 4) printf("%d\n", i); }