[Solved] For loop with variable step size – C++


You could try using ternary operators. It makes the readability of your code more difficult (my opinion, but some people like it), but you put everything inside your for statement.

For the numbers that can be divided by 3, for instance:

for (int i = 1; i < N; i = (((i+1)%3 == 0) ? i+2 : i+1)) {
    //Instructions
}

And, for numbers that can be divided by 3 and 2, you could try this:

for (int i = 1; 
 i < N; 
 i = (i+1)%3 == 0 || ((i+1)%2) == 0 ? 
     ((i+2)%3 == 0 || i%2 == 0 ? 
        (i%3 == 0 || (i+1)%2 == 0 ? i+4 : i+3) : i+2 ) : i+1) {
    //Instructions
}

For more information about ternary operators, click here

EDIT Adding @AMA’s suggestion, from comments (simpler than mine)

for (int i = 1; 
     i < N; 
     i = (i+1)%2 == 0 
         ? (i+2)%3 == 0
             ? i+4
             : i+2
         : (i+1)%3 == 0 
             ? i+2
             : i+1) {
    //Instructions
}

8

solved For loop with variable step size – C++