• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Loop Qestion Head First pg 63

 
Tariq Ab
Greenhorn
Posts: 14
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question is, why did we initializae the value of z to -1?
Couldn't we just set it to 0 and get it to loop 0 through 2?

Another question, is using the 2 IF statements effecient here? couldn't we just stayed with the while loop statement for the rest array values?

hope my questions make sense and appreciate your help

 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is different code from page 63 in my copy of HFJ. My copy has int z = 0;
The answer is not actually correct for the question asked. Both code snippets will compile correctly, but both will suffer an Exception, different in each case. The reason for the -1 is so entering the loop, the index used will be 0. You also have to change the < 4 to < 2 so you never have an index of 3 or greater.

If you cannot see why you need -1, get a pencil and paper. Starting at the line starting "while", write down the value of z, and which element in the array you are dealing with, as you go through the loop.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tariq Ab wrote:. . . Couldn't we just set it to 0 and get it to loop 0 through 2? . . .
Yes, but that would make the exercise too easy. It is supposed to mimic the sort of question you get in certification exams.
The correct form of a for loop to initialise array elements is like this;Notice the only number literal you use is 0.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic