Page 165 - Introduction to Programming with Java: A Problem Solving Approach
P. 165
4.10 for Loop 131
1 Scanner stdIn = new Scanner(System.in);
2
int number;
double factorial = 1.0;
System.out.print("Enter a whole number: ");
number = stdIn.nextInt();
for (int i=2; i<=number; i++)
3
4
5
10
factorial *= i;
11
}
12
13
System.out.println(number + "! = " + factorial);
6
7
8
9{
input
4
Declare for loop index variables within the for loop header.
line#
number
factorial
i
output
2
?
3
1.0
5
Enter a whole number:
6
4
8
Apag2o PDF Enha
10
2.0
8
3
10
6.0
8
4
10
24.0
8
5
13
4! 24.0
ncer
Figure 4.15 Code fragment that illustrates factorial calculation plus its associated trace Scope of for Loop Index
In the for loop examples presented so far, the loop’s index variable (i) is initialized (declared and given an initial value) in the for loop header. This limits the scope or recognizable range of the index variable to the for loop itself. In other words, whenever a variable is declared in the for loop header, it exists and can be recognized and used only by code that is within the body of that for loop. For example, if you tried to use the value of the i index variable in the print statement that followed the final brace of the for loop in Figure 4.15, the compiler would say “cannot find symbol. . . variable i.”
Sometimes, variables used in a loop need to have a scope beyond the loop’s scope. The above Factorial program illustrates what we’re talking about. The factorial variable must be available for the print state- ment after the end of the loop, so it must be declared outside the loop. Since it is also needed in the loop, it must be declared before the loop, so we declare it at the beginning of the method with the other variables whose scopes extend throughout the method.