]1

my classmate thinks it's 10 I know it's 11. I can't explain it properly so anyone wanna give it a shot?

The variable starts at 10. Each time it passes it decrements by one and the loop exits when x isn't greater than 0. so when x becomes 0 the loop exits. so it happens from 10 to 0. That's 11 times.

2

Best Answer


This is probably more than you want to know but here you go.

Your example is no different than for (x = 10; x < 0; x--);

Most loops have a start, end, and an increment. (I won't say all loops because someone will come up with an obscure example to prove me wrong).

With for loops there are two cases to consider.

  1. for (x = start; x <= end; x+=inc); // I refer to this as closed

  2. for (x = start; x < end; x+inc); // I refer to this as open

For the closed loop, the number of times is computed as:

(end-start)/inc + 1

The open loop is more complicated in that 1 must be subtracted fromend to force it to be a closed loop. That can be computed as

(end-1-start)/inc + 1

This also works if you change the positions of start and end and do a decrement of the increment.

In your case it would be (10 - 1 - 0)/1 + 1 = 10.

And here is some test code to play with to check out each loop type.

public static void main(String[] args) {Random r = new Random();for (int t = 0; t < 10_000; t++) {int realCountClosed = 0;int realCountOpen = 0;int start = r.nextInt(10);int end = r.nextInt(30) + 11;int inc = r.nextInt(4) + 1;for (int i = start; i <= end; i += inc) {realCountClosed++;}for (int i = start; i < end; i += inc) {realCountOpen++;}int computedCountClosed = (end - start) / inc + 1;int computedCountOpen = ((end - 1) - start) / inc + 1;if (realCountClosed != computedCountClosed) {System.out.println("Closed: " + realCountClosed + " " + computedCountClosed);}if (realCountOpen != computedCountOpen) {System.out.println("Open: " + realCountOpen + " " + computedCountOpen);}}}

One final note. In for loops pre or post increment (i.e. -- or ++) of values doesn't affect the loop. This is not the case of while loops if the increment is done in the while portion of the loop.

The following loop iterates exactly 10 times, printing the value of x from 10 to 1. The loop stops looping when x = 0 because 0 is not bigger than 0. This decrementing process happens in x-- after the program have looped 10 times. Because the loop iterates exactly 10 times, the value of x is printed first then it is decremented by 1, 10 times. So in the end, the final value of x is 0 but the last value of x that is being printed is 1.