Search code examples
javafor-loopnested-loops

Can I split this two-variable for loop into two nested loops?


I would like to know about the given for loop which looks weird to me:

for (int i = 0, j = s.length - 1; i < j; i++, j--)

So far, I was using for loop with one variable. However in this example there are two variables within one loop.

Can I split the for loop into two nested loops?

for (int j = 0; j < s.length - 1; j--) {
    for (int i = 0; i < j; i++) {
    }
}

Solution

  • it is wrong conversion, correct one will be:

    int j = s.length - 1;
    for (int i = 0; i < j; i++) {
        // inside logic
        j--;
    }