0

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++;
3
  • Why would i be incremented during the first iteration? The only time you have i being incremented is at the end of the first iteration. Commented Nov 11, 2016 at 19:30
  • In First iteration of loop, i=0 as specified in inital condition of for loop. Commented Nov 11, 2016 at 19:30
  • If you want to start at 1, initialize i as 1, otherwise it will only increment after the first loop is finished! Commented Nov 11, 2016 at 19:32

2 Answers 2

2

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.

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

1 Comment

@flakes Good point. Adding braces around whole expression to show scoping.
-1
while (j <= i) 

Output: 0 0 1 0 1 2 0 1 2 3 0 1 2 3 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.