Win a copy of Serverless Applications with Node.js this week in the NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • paul wheaton
  • Junilu Lacar
  • Paul Clapham
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Ron McLeod
  • Tim Moores
  • salvin francis
  • Carey Brown
  • Tim Holloway
  • Frits Walraven
  • Vijitha Kumara

Question about 'for' loop variable  RSS feed

Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

1. Practice tests chapter 5 qstn 31

2.  Study guide Chapter 2 Review qn 9

Posts: 63843
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Posts: 23
IntelliJ IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, Anu.

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;

An example you can addapt to your case:

And then we all jump out and yell "surprise! we got you this tiny ad!"
global solutions you can do in your home or backyard
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!