Header Ads

Breaking News
recent

Why Repitition is Needed; While Looping (Repetition) Structure

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
At this point, sum contains the sum of the first two numbers. Let’s repeat the statements in Lines 2 and 3 a third time. After the statement in Line 2 executes (after the programming code reads the next number): num = 7
After the statement in Line 3 executes:
sum = sum + num = 8 + 7 = 15
Now, sum contains the sum of the first three numbers. If you repeat the statements in Lines 2 and 3 two more times, sum will contain the sum of all five numbers. If you want to add 10 integers, you can repeat the statements in Lines 2 and 3 ten times. And if you want to add 100 numbers, you can repeat the statements 100 times.

In either case, you do not have to declare any additional variables as you did in the code shown previously. By repeating the statements in Lines 2 and 3 you can add any set of integers, whereas the earlier code requires that you drastically change the code. There are many situations in which it is necessary to repeat a set of statements. For example, for each student in a class, the formula to determine the course grade is the same. Java has three repetition, or looping, structures that let you repeat statements over and over until certain conditions are met: while, for, and do...while. The following sections discuss these three looping (repetition) structures.

In the previous section, you saw that sometimes it is necessary to repeat a set of statements several times. One way to do this is to type the set of statements in the program over and over. For example, if you want to repeat a set of statements 100 times, you type the set of statements 100 times in the program. However, this way of repeating a set of statements is impractical, if not impossible. Fortunately, there is a simpler approach. As noted earlier, Java has three repetition, or looping, structures that allow you to repeat a set of statements until certain conditions are met. This section discusses the first looping structure, a while loop.
The general form of the while statement is:
In Java, while is a reserved word. The logical expression is called a loop condition or simply a condition. The statement is called the body of the loop. Moreover, the statement can be either a simple or compound statement. Also, note that the parentheses around the logical expression are part of the syntax. Figure 5-1 shows the flow of execution of a while loop.
The logical expression provides an entry condition. If it initially evaluates to true, the statement executes. The loop condition—the logical expression—is then reevaluated. If it again evaluates to true, the statement executes again. The statement (body of the loop) continues to execute until the logical expression is no longer true. A loop that continues to execute endlessly is called an infinite loop. To avoid an infinite loop, make sure that the loop’s body contains one or more statements that ensure that the loop condition—the logical expression in the while statement—will eventually be false.

EXAMPLE 5-1
Consider the following Java program segment:
int i = 0; //Line 1
while (i <= 20) //Line 2
{
System.out.print(i + " "); //Line 3
i = i + 5; //Line 4
}
System.out.println(); //Line 5
Sample Run:
0 5 10 15 20
In Line 1, the variable i is set to 0. The logical expression in the while statement (in Line 2), i <= 20, is then evaluated. Because the expression i <= 20 evaluates to true, the body of the while loop executes next. The body of the while loop consists of the statements in Lines 3 and 4. The statement in Line 3 outputs the value of i, which is 0; the statement in Line 4 changes the value of i to 5. After executing the statements in Lines 3 and 4, the logical expression in the while loop (Line 2) is evaluated again. Because i is 5, the expression i <= 20 evaluates to true and the body of the while loop executes again. This process of evaluating the logical expression and executing the body of the while loop continues until the expression i <= 20 (Line 2) no longer evaluates to true.

The variable i (Line 2) in the expression is called the loop control variable.
Note the following from the preceding example:

1. Eventually, within the loop, i becomes 25, but is not printed because the entry condition is false.

2. If you omit the statement: i = i + 5; from the body of the loop, you will have an infinite loop, continually printing rows of zeros.

3. You must initialize the loop control variable i before you execute the loop. If the statement: i = 0; (in Line 1) is omitted, either the compiler will generate an error or the loop might not execute at all. (Recall that not all variables in Java are automatically initialized.)

4. In the previous program segment, if the two statements in the body of the loop are interchanged, the result may be altered. For example, consider the following statements:
int i = 0;
while (i <= 20)
{
i = i + 5;
System.out.print(i + " ");
}
System.out.println();
Here, the output is:
5 10 15 20 25
Typically, this would be a semantic error because you rarely want a condition to be true for i <= 20, and yet produce results for i > 20.

Designing while Loops
As shown in Example 5-1, the body of a while loop executes only when the expression in the while statement evaluates to true. Typically, the expression checks whether a variable(s), called the loop control variable (LCV), satisfies certain conditions. For example, in Example 5-1, the expression in the while statement checks whether i <= 20. (Recall that in Java, when variables are declared, they are not automatically initialized.) The LCV must be properly initialized before the while loop, and its value should eventually make the logical expression evaluate to false. We do this by updating the LCV in the body of the while loop. Therefore, while loops are typically written in the following form:
//initialize the loop control variable(s)
while (logical expression) //expression tests the LCV
{
.
.
.
//update the loop control variable(s)
.
.
.
}
For instance, in Example 5-1, the statement in Line 1 initializes the LCV i to 0. The expression i <= 20 in Line 2 checks whether i is less than or equal to 20, and the statement in Line 4 updates the value of i.

No comments:

Powered by Blogger.