Java Reference
In-Depth Information
}
}
//Loop #3
for(int a = 1, b = 100; a < b; a = a + 2, b = b - 4)
{
System.out.println(“a = “ + a + “ and b = “ + b);
}
}
}
One nice feature of for loops is that you can often tell how many times they
will repeat just by looking at the for declaration. For example, the first loop in
the ForDemo program repeats x number of times, where x is a value input
from the command-line arguments. The second for loop repeats 100 times. It is
not clear how many times the third for loop executes, but I will discuss that in
detail in a moment.
The first for loop multiplies 1 * 2 * 3 * ... * x, which is the factorial of x. When
the variable i is equal to x + 1, the for loop terminates. For example, when x is
7 the output is:
f = 5040
The statement I added that does not compile is:
System.out.println(“i = “ + i);
The variable i was declared in the initialization step, and i goes out of scope
once the for loop terminates.
If you want i to have scope outside of the for loop, you need to declare it
outside of the for loop.
For example, you could change the beginning of the loop to:
int i;
for(i = 1; i <= x; i++)
Now, the variable i can be used after the for loop, and it will be the value
x + 1.
The second for loop in the ForDemo program executes 100 times and prints
all of the numbers between 1 and 100 that are divisible by 7. This for loop gen-
erates the following output:
7
14
21
28
Search WWH ::




Custom Search