I am confused about loop variables in different variations of the for loop. I'm following Scott Selikoff and Jeanne Boyarsky OCA study guide and practice tests books.
In code snippets 1 and 2 below, the loop variable is used differently. In (1), the for loop is using the updated value of i after decrementing it on line 5, whereas in (2) the for loop is not using the incremented value of i.
Can someone please explain the difference here. TIA.
Start by formatting the code correctly and indenting it correctly. I know some certification exam practice questions like to use poor formatting to confuse their readers, but missing formatting is a very good way to confuse yourself.
Can't you see the difference between the two loops? Do you know why the loop variable is never incremented in the second loop? Have you worked out why the first loop only runs once? What answers does the book give? Did you get the same output as the book says?
I'm also in the early stages of learning Java and find it often usefull to print out variables to the screen, so that I can trace what is happening -STEP-By-STEP - when a certain block of code runs. The situations you describe and the questions you are asking fit this use.
So, and starting with the need to format/indent the code pointed out by Campbell, I would suggest you add a couple of "System.out.println()" 's to you examples, outputing in each:
1 - the place in the code where you are;
2 - the value of the variables at that time;