Search code examples
javafor-loopwhile-loopincrementnested-loops

Incrementing within nested loop


I have a pretty straight forward question. In the program below, why does i not increment to 1 in the first iteration of the for loop? My compiler shows that for the first run, j is not less than i because they are both 0. Thanks!

  int i;
  for (i = 0; i < 5; i++) {
    int j = 0;
    while (j < i) {
      System.out.print(j + " ");
      j++;

Solution

  • The value of i will be 0 for the first iteration and 1 for the second. Take the following:

    for (int i = 0; i < 5; i++) {
        // loop code
    }
    

    The above for loop is just syntactic sugar for:

    { 
        int i = 0;
        while (i < 5) {
            // loop code
            i++;
        }
    }
    

    Note that the outer braces are there to show that after the for loop exits the variable i is no longer in scope.