Java Reference
In-Depth Information
Comparing the Looping Control Structures
I want to make a general observation about while loops, do/while loops, and for loops. The
number of times that a loop repeats does not need to be predetermined. For example,
how many times does the do/while loop repeat in the RandomLoop program? Statistically,
assuming that the random number generator is truly random, the loop should only have to
repeat itself three or four times at the most.
However, it is possible for the loop to have to repeat 10 times or more until a second
random number is finally generated that is different from the first random number. So, to
answer my own question, the loop will repeat an indeterminate number of times. You have
to run the program to see how many times through it takes to generate a second, unique
random number.
What if you knew exactly how many times you needed to repeat something? For exam-
ple, suppose that I have 20 students in a calculus class and I need to compute the exam
score for each student. I will need to repeat a task 20 times. I can use a while loop or a
do/while loop, but my preferred choice in this situation would be a for loop.
You can write a for loop that executes an indeterminate number of times, and you can
write a while or do/while loop that executes a predetermined number of times. In general,
however, when you know ahead of time exactly how many times you need to repeat a task,
a for loop is the control structure of choice. Otherwise, if you need to repeat a task in inde-
terminate number of times, a while loop or do/while loop is your best bet.
The following ForDemo program contains three for loops. Study the pro-
gram and try to determine what the output of the program will be. By the way,
I added one statement in the program that does not compile. See if you can
guess which line of code it is.
public class ForDemo
{
public static void main(String [] args)
{
//Loop #1
int x = Integer.parseInt(args[0]);
long f = 1;
for(int i = 1; i <= x; i++)
{
f = f * i;
}
System.out.println(“f = “ + f);
System.out.println(“i = “ + i);
//Loop #2
for(int k = 1; k <= 100; k++)
{
if(k % 7 == 0)
{
System.out.println(k);
Search WWH ::




Custom Search