Search

Friday, December 21, 2018

The while Repetition Structure

A repetition structure allows the programmer to specify that an action is to be repeated while some condition remains true. The pseudo-code statement While there are more items on my shopping list Purchase next item and cross it off my list describes the repetition that occurs during a shopping trip. The condition “there are more items on my shopping list” may be true or false. If it is true, then the action “Purchase next item and cross it off my list” is performed. This action will be performed repeatedly while the condition remains true. The statement(s) contained in the while repetition structure constitute the body of the while structure.The body of the while structure may be a single statement or a block. Eventually, the condition will become false (when the last item on the shopping list has been purchased and crossed off the list). At this point, the repetition terminates, and the first pseudo-code statement after the repetition structure is executed.

          Common Programming Error 
Not providing in the body of a while structure an action that eventually causes the condition in the while to become false is a logic error. Normally, such a repetition structure will never terminate—an error called an infinite loop.Spelling the keyword while with an uppercase W, as in While, is a syntax error. (Remember that Java is a case-sensitive language.) All of Java’s reserved keywords, such as while, if and else, contain only lowercase letters.

As an example of a while structure, consider a program segment designed to find the first power of 2 larger than 1000. Suppose that the int variable product has been initialized to 2. When the following while structure finishes executing, product contains the result:
int product = 2;
while ( product <= 1000 )   
product = 2 * product;
The flowchart illustrates the flow of control of the preceding while repetition structure. Once again, note that, besides small circles and arrows, the flowchart contains only a rectangle symbol and a diamond symbol. Imagine, again, a deep bin of empty while structures that may be stacked and nested with other control structures to form a structured implementation of an algorithm’s flow of control. The empty rectangles and diamonds are then filled in with appropriate actions and decisions. The flowchart clearly shows the repetition. The flow line emerging from the rectangle wraps back to the decision, which is tested each time through the loop until the decision eventually becomes false. At this point, the while structure is exited, and control passes to the next statement in the program. When the while structure is entered, product is 2. Variable product is repeatedly multiplied by 2, taking on the values 4, 8, 16, 32, 64, 128, 256, 512 and 1024 successively. When product becomes 1024, the condition product <= 1000 in the while structure becomes false. This result terminates the repetition, with 1024 as product’s final value. Execution continues with the next statement after the while. 
[Note: If a while structure’s condition is  initially false, the body statement(s) will never be performed.]
To illustrate how algorithms are developed, we solve several variations of a class-averaging problem. Consider the following problem statement: A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz. The class average is equal to the sum of the grades divided by the number of students. The algorithm for solving this problem on a computer must input each of the grades, perform the averaging calculation and print the result.
Let us use pseudo-code to list the actions to be executed and specify the order in which these actions should be executed. We use counter-controlled repetition to input the grades one at a time. This technique uses a variable called a counter to control the number of times a set of statements will execute. In this example, repetition terminates when the counter exceeds 10. In this section, we present a pseudo-code algorithm and the corresponding program to solve this problem using counter-controlled repetition. In the next section, we show how pseudo-code algorithms are developed. Counter-controlled repetition is often called definite repetition, because the number of repetitions is known before the loop begins executing. Note the references in the algorithm to a total and a counter. A total is a variable used to accumulate the sum of a series of values. A counter is a variable used to count—in this case, to count the number of grades entered. Variables used to store totals should normally be initialized to zero before being used in a program; otherwise, the sum would include the previous value stored in the total’s memory location. 

Class average program with counter-controlled repetition. 

    // Java extension packages 5 import 
javax.swing.JOptionPane;
 public class Average 
{      
// main method begins execution of Java application 
public static void main( String args[] ) 
{
int total,                   
// sum of grades input by user 
gradeCounter,          
// number of grades entered 
gradeValue,              
// grade value 
average;
// average of all grades    
String grade;
// grade typed by user 
// Initialization Phase 
total = 0;
// clear total      
gradeCounter = 1;
// prepare to loop     
// Processing Phase     
 while ( gradeCounter <= 10 ) 
{
// loop 10 times         
// prompt for input and read grade from user         
grade = JOptionPane.showInputDialog("Enter integer grade: " );      
// convert grade from a String to an integer         
gradeValue = Integer.parseInt( grade );
// add gradeValue to total         
total = total + gradeValue;         
// add 1 to gradeCounter      
gradeCounter = gradeCounter + 1;    }  
// end while structure     
// Termination Phase      
average = total / 10; 
// perform integer division     
// display average of exam grades     
JOptionPane.showMessageDialog( null,"Class average is " + average, "Class Average",         JOptionPane.INFORMATION_MESSAGE );   
System.exit( 0 ); 
// terminate the program } 
// end method main  
// end class Average1

         OUTPUT



0 comments:

Post a Comment