Q Should the counter variable used in a for loop be created inside the for statement or before the loop begins?
A The only time the counter should be created outside of the for loop, or any other loop for that matter, is when it needs to be used in another part of the program. A variable that is created in a loop or other kind of block statement only exists inside that block. You can't use the value in any other part of the program. This is good programming practice because it makes it harder to misuse variables--you can't set their value in one part of the program and use them somewhere else incorrectly. The concept of a variable existing in one part of a program and not existing anywhere else is called scope, and it's covered fully during Hour 11, "Describing What Your Object Is Like."
Q The term initialization has been used in several places. What does it mean?
A It means to give something an initial value and set it up. When you create a variable and assign a starting value to it, you are initializing the variable.
Q If a loop never ends, how does the program stop running?
A Usually in a program where a loop does not end, something else in the program is set up to stop execution in some way. For example, a loop could continue indefinitely while the program waits for the user to click a button labeled Quit. However, if a program isn't working correctly, one bug you'll run into during testing is a loop that cannot be stopped. This bug is called an infinite loop because the program will loop happily forever. If one of the Java programs you run from the command line is stuck in an infinite loop, press Ctrl + C.
The following questions will test your knowledge of loops. In the spirit of the subject matter, repeat each of these until you get them right.
1. What must be used to separate each section of a for statement?
(c) Off-duty police officers
2. Which statement causes a program to go back to the statement that began a loop and then keep going from there?
3. When it comes to borrowing a car from your father, what lesson did you learn during this hour?
(a) Don't even think about it.
(b) Speak softly and carry a big stick.
(c) It's better to beg forgiveness than to ask permission.
1. b. Commas are used to separate things within a section, but semicolons separate sections.
2. a. The break statement ends a loop entirely, and continue skips to the next go-around of the loop.
If your head isn't going in circles from all this looping, review the topics of this hour with the following activities:
· Modify the Repeat program so that it uses a for loop instead of a while loop and compare the efficiency of each approach.
· Write a short program using loops that finds the first 400 prime numbers.