Beruflich Dokumente
Kultur Dokumente
while loop
Objectives
Describe the advantages of looping Draw the flowchart for a loop Define:
loop control variable loop body loop condition accumulators counters
Looping
If making decisions is what makes computers seem intelligent, its looping that makes computers worthwhile. The beauty of having a computer is that a series of instructions that will be performed over and over again need to be written only once.
Loop Flowchart
Initialize variable to control loop Compare variable to a value that stops the loop Alter the variable so it can again be compared for stopping the loop
Example:
Parts of a loop
Loop control variable -
determines whether the loop should be continued (REP) Sentinel value value to compare to stop loop (5) Loop body statements inside the loop
public static void main(String args[]) { int rep = 1; while (rep < 5) { System.out.println(Warning); rep = rep + 1; } }
While the condition is true, the statements will execute repeatedly. The while loop is a pretest loop, which means that it will test the value of the condition prior to executing the loop.
Syntax of while()
while (condition) {
loop body;
} No semicolon after condition in the while while condition surrounded by ( ) while NOT While braces surround loop body
Infinite Loops
In order for a while loop to end, the condition must become false. The following loop will not end:
int x = 20; while(x > 0) { System.out.println("x is greater than 0"); }
Infinite Loops
This version of the loop decrements x during each iteration:
int x = 20; while(x > 0) {
Questions
On the previous slide identify:
What this program does Loop control variable
initialization update testing
Problems:
Draw the flowchart to display the numbers 1-10. Write the corresponding Java Code Identify the:
loop control variable
where it is initialized where it is updated
Problems
Draw the flowchart to display even numbers only between 1 and 100. At the end display the sum of the even numbers and an average of the even numbers. Write the corresponding Java Code Identify the loop control variable where it is initialized where it is updated body of the loop condition accumulator counters Where do you calculate the average -- inside or outside the loop? Why?
Java Code
Accumulators/Counters
Accumulators An accumulator is a numeric variable used for accumulating (adding together) somethingsuch as the total dollar amount of a weeks payroll
They must be initialized to a value (usually 0)
Accumulators/Counters
Counters A counter is a numeric variable used for counting somethingsuch as the number of employees paid in a week
They must be initialized to a value (usually 0)
The counter in the previous example is the variable count. This variable is also the loop control variable.
Review
Terminology:
loop control variable loop body loop condition accumulators counters
Skill:
Be able to write a loop construct with the Java while statement.