Java Reference
In-Depth Information
In Chapter 4, you learned how decisions are incorporated in programs. In this chapter,
you will learn how repetitions are incorporated in programs.
Why Is Repetition Needed?
Suppose you want to add five integers to find their average. From what you have learned
so far, you know that you could proceed as follows (assume that all the variables are
properly declared):
num1 = console.nextInt();
//get the first number
num2 = console.nextInt();
//get the second number
num3 = console.nextInt();
//get the third number
num4 = console.nextInt();
//get the fourth number
num5 = console.nextInt();
//get the fifth number
sum = num1 + num2 + num3 + num4 + num5; //add the numbers
average = sum / 5; //find the average
But suppose you want to add and average 1000 or more numbers. You would have to
declare that many variables, and list them again in the input statements, and perhaps again
in the output statements. This would take an exorbitant amount of typing as well as time.
Also, if you wanted to run this program again with a different number of values, you
would have to rewrite the program.
Suppose you want to add the following numbers:
5 3 7 9 4
Assume that the input is these five numbers. Consider the following statements, in which
sum and num are variables of type int :
sum = 0; //Line 1
num = console.nextInt(); //Line 2
sum = sum + num; //Line 3
The statement in Line 1 initializes sum to 0 . Let's execute the statements in Lines 2 and 3.
The statement in Line 2 stores 5 in num ; the statement in Line 3 updates the value of sum
by adding num to it. After Line 3 executes, the value of sum is 5 .
Let's repeat the statements in Lines 2 and 3. After the statement in Line 2 executes (after
the programming code reads the next number):
num = 3
After the statement in Line 3 executes:
sum = sum + num = 5 + 3 = 8
 
Search WWH ::




Custom Search