2

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

3
  • 9
    Why not just use i / 2 instead of j? Commented Mar 4, 2014 at 15:31
  • The purpose of my question is to create a chart that shows all the numbers that have a "1" in the "4" binary spot between 5 and 36. Commented Mar 4, 2014 at 15:39
  • 1
    for (int i = 5; i <= 36; ++i) { if (i & 4) printf("%d\n", i); } Commented Mar 4, 2014 at 15:49

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

isn't there sequence point issues in the increment here with the comma operator?
No, the comma operator introduces sequencing.
0

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

Comments