Home » Java » Why does while loop print all the numbers but for loop doesn't?

Why does while loop print all the numbers but for loop doesn't?

Posted by: admin July 23, 2018 Leave a comment

Questions:

How come the while loop prints all the numbers from 1-10 when I clearly have i < 10, shouldn’t it print out only 0-9 like the for loop?

Both while loop and for loop start at index 0, why’s it printing 1-10 for while loop and 0-9 for loop?

public static void main(String args[]) {
    int i = 0, j = 0;

    while(i < 10) {
        i++;
        System.out.print(i + " ");
    }

    System.out.println();

    for(j = 0; j < 10; j++) {
        System.out.print(j + " ");
    }
}

output:

1 2 3 4 5 6 7 8 9 10 
0 1 2 3 4 5 6 7 8 9 
Answers: