Java: Loop/repetition construct

Author: Ronald S. Holland
at
Total Application Works

ronholland@sumtotalz.com





To contact us



HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2016 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)
    <html>
    <head>
    <title>Example of a link </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/Java/JAV_Loops.html">
    Loops - Iterations/repetition </a>
    </table>
    </body>
    </html>
    Source Code


Introduction

Java, as a programming language, is widespread and can be found on nearly all computers. This tutorial assumes that you have some prior programming experience. It is not intended to be a comprehensive discussion on Java or programming. As we ease into Java, we will briefly discuss the loop control structures. In this tutorial, we will focus, primarily, on the following loop control structures:

  1. while loop/repetition sequence
  2. do while loop/repetition sequence
  3. for loop/repetition sequence
A loop control structure is also known as a repetition structure. The purpose of Loops is to repeat/execute a statement(s) a certain number of times or while a boolean condition is true.

Why are repetition/loops used? Repetition/loops are used to execute a block of code several times in succession, while a boolean condition is true. Types of repetition sequences are: In the next section, we will briefly describe control structures.

Control Structures

Bohm and Jacopini demonstrated, in their Structured program theorem, that all programs could be written using just three control structures.

  • sequence structure
      Consider the following example:

      
      int a = 8 , b ;
      b = (5 + 2) * a  ;
      cout << b << endl ;
      
      Figure 1: Sequence of statements structure
      If a code snippet consists of the above three statements, then the statements will execute in the order/sequence that they are listed. This is also known as an ordered execution of statements.
  • selection structure
      In a selection statement, one of a number of statements is executed depending on the state of the program. Consider the following example:

      
      int a, b = 0;
      
      cout << "Enter a number less than 10 and greater than 0." << endl ;
      cin >> a ;
      
      if( a > 5 )
         b = (5 + 2) * a  ;
      
      cout << "The value of b is " <<  b << endl ;
      
      
      Figure 2: selection structure
  • repetition structure
      A repetition structure is used when a set of instructions need to be executed more than once.

      
      int b = 0;
      
      for( int ii = 0 ; ii < 10 ; ii++ ) {
         b = (5 + 2) * ii  ;
         cout << "The value of b is " <<  b << endl ;
      }
      
      Figure 3: repetition structure
Control Structures or constructs are described further in the next section.

Control Structures or constructs

What are Control Structures or constructs? The Control Structures constructs used in programming are:
  1. if - single selection structure
      This structure is used to determine whether a condition is true or false. If the condition evaluates to true, then some action is taken.
      
      if( condition is true ) {
         statement_1
         statement_2
         statement_3
         ...
         statement_n
      }
      
      Figure 4: if - single selection structure


  2. if/else - double selection structure
      This structure is used to determine whether a condition is true or false. If the condition evaluates to true, then some action is taken; otherwise, a different action is taken.
      
      if( condition is true ) {
         statement_1
         statement_2
         statement_3
         ...
         statement_n
      }
      else {
         statements
      }
      
      Figure 5: if/else - double selection structure


  3. switch - multiple selection structure
      This structure allows selection among multiple sections of code, depending on the value of an integral expression. It operates much like a nested if construct.
      
      switch( expression ) {
         case 1;
            do something ;
         case 2;
            do something ;
         case 3;
            do something ;
         ...
      
         default;
            do something ;
      }
      
      
      Figure 6: switch - multiple selection structure


  4. while
      In this construct, the condition is a boolean statement that is checked after the final } braces of the while statement executes. If the condition is true then the while statement executes again. If the condition is false, the statements inside the while construct do not execute again, due to the code branching out of the construct.
      while( condition is true ) {
         statement_1
         statement_2
         statement_3
         ...
         statement_n
      }
      
      • condition is true - is a boolean statement that if it tests true, statements 1-n are executed
      Figure 7: while loop structure


  5. do/while
      The do-while loop is similar to the while loop, except that the test condition occurs at the end of the loop. This construct guarantees that the body of the loop always executes at least one time. The format of the do-while loop is shown below.
      do {
         statement_1
         statement_2
         statement_3
         ...
         statement_n
      }
      while( condition is true )
      
      Figure 8: do-while loop structure


  6. for
      Executes the statements and loop-expression repeatedly until test becomes false. After the first pass, the loop counter is updated and then the test-condition is checked to determine whether it is true or false.
      
      for( initial_value, test_condition, step ) {
         statement_1
         statement_2
         statement_3
         ...
         statement_n
      }
      
      • initial_value - is the initial value of the loop counter.
      • test_condition - is the condition that is tested to see if the loop is executed again.
      • step - is the counter decrement or increment on each execution of the loop.
      Figure 9: for loop structure


For the remainder of this tutorial, we will describe loop/repetition constructs. We will begin with the while construct/loop in the next section.

The while loop/repetition construct

How do we use the while loop/repetition construct? In the real world, we often use the while loop/repetition construct, during the day. A teacher must decide at the end of the semester who gets a passing grade. What criteria is used? The criteria used is: all students achieving a grade greater than or equal to 60 will receive a passing grade.

Flowchart
 

    

               -


 
 

    


----------------------------
  
  • The Decision symbol is used when a decision needs to be made or evaluated
  • The Processing symbol is used when processing a sequence of needs to be made. In this case, while grade is greater than 60, send a passing notice.
  • The loop will continue until all papers are checked.
Pseudocode
while there are more papers to grade
   if the grade is greater than or equal to 60 
      email "passed" to the passing student
    end if
end loop
Figure 11: while construct


while loop code/examples
1- while Loop - raise a variable "x" to a power of "y"
2- while loop - obtains the class grades and then computes the class average
3- while Loop - obtains a number from the user and create a custom countdown counter
4- while Loop - adjust the car speed to the set cruise speed
5- while Loop - get integers, sum them and the calculate the average
6- while Loop - get ten numbers, determine the two largest and the smallest numbers.
7- while Loop - multiplies the number of the loop iteration by 5, 10, 100, and 1000.
8- while Loop - obtains numbers from the user and determines whether that number is positive or negative.
9- while Loop - obtains binary number from the user and then converts it to an integer.
10- while Loop this program obtains two random * numbers, a and y and then
  1. Multiplies the two numbers, x * y
  2. Adds the two numbers together, x + y
  3. Subtracts the two numbers, x - y
11- while Loop this program computes a
  1. Geometric Expression, using a while construct
  2. Geometric series, using a for construct
  3. Last value of the loop iterator, using a switch construct
12- while Loop creates a ten-by-ten multiplication table.

Without a conditional statement such as while, programs would run practically same way every time. The while statements allow the flow of a program to be altered.

The for loop structure

In this section, we descibe the The for loop structure, in terms of the following:

  1. Pseudocode
  2. The flowchart, and
  3. code


Pseudocode
 
for( initial_value, test_condition(there are more papers 
      to grade), step  )
   if the grade is greater than or equal to 60 
       email "passed" to the passing student
   else
       email "failed" to the failing student
   end if
end loop



  
  
          for( more papers to grade )            
                    |  
                    _
                   ( ) <-----------------------------+  
                    |                                | 
                    ^                                | 
for loop           / \    false                      |
decision ----->   /   \ ------------------------>+   |
                  \   /                          |   |
                   \ /                           |   |
                    |  true                      |   |
                    v                            |   |
                    _                            |   |
                   ( )                           |   |               
                    |                            |   |
+---------+         ^          +--------------+  |   |
| print   | false  /g\ true    |   print      |  |   |
|         |<----- />= \________|              |  |   |
| "failed"|       \60 /        |   'passed'   |  |   |
+---------+        \ /         +--------------+  |   |
     |              v                |           |   |
     |              |                |           |   |
     +------------->|<---------------+           |   |
                    _                            |   |
                   ( ) ------------------------- | --+ 
                                                 |   
                                                 |   
                                                 |  
                    +<---------------------------+
                    |
                    v
                    _
                   ( ) <--- end for loop
                    -


  
Code
   
for( int loopcounter = 0 ; loopcounter < papers_To_Grade ; loopcounter++ ) {
   if (grade >= 60) 
         cout << "Passed" << endl;
      else 
         cout << "Failed" << endl;
   }
}
  

When the for loop begins executing, the:

  1. loopcounter is declared and initialized to zero
  2. loopcounter is checked against papers_To_Grade and if loopcounter is less than papers_To_Grade then the loop is executed for one pass
  3. paper being graded is checked for passing or failing grade
  4. papers with a grade greater than or equal to 60 are sent a passing email
  5. papers with a grade less than 60 are sent a failing email
  6. loopcounter is incremented
  7. loopcounter is checked against papers_To_Grade until there are no papers to grade

Figure 12: for repetition structure


Examples of for repetition construct program are listed below.

for loop code/examples
1- for Loop - raise a variable "x" to a power of "y"
2- for loop - obtains the class grades and then computes the class average
3- for Loop - obtains a number from the user and create a custom countdown counter
4- for Loop - adjust the car speed to the set cruise speed
5- for Loop - get integers, sum them and the calculate the average
6- for Loop - get ten numbers, determine the two largest and the smallest numbers.
7- for Loop - multiplies the number of the loop iteration by 5, 10, 100, and 1000.
8- for Loop - obtains numbers from the user and determines whether that number is positive or negative.
9- for Loop - obtains binary number from the user and then converts it to an integer.
The do until repetition construct are descibed in the next section.

The do while iteration construct program

In the following table, we show the flowchart, pseudocode, code for an do while iteration construct program.

Pseudocode
 

  
                    _
                   ( )                       
                    |<-------------------------------------------+
                    |                                            |
                    v                                            |
+---------+         ^          +--------------+                  |
| print   | false  /g\ true    |   print      |                  |
|         |<----- />= \________|              |                  |
| "failed"|       \60 /        |   'passed'   |                  |
+---------+        \ /         +--------------+                  |
     |              v                |                           |
     |              |                |                           |
     +------------->|<---------------+                           |
                    |                                            |
                    |                                            |
                    |                                            |
                    v                                            |
                    _                                            |
                   ( )                                           |
                    |       more papers to grade                 | 
                    ^                                            | 
do while loop      / \    true                                   |
decision ----->   /   \  --------------------------------------->+ 
                  \   /                         
                   \ /  
                    _                                             
                    |                         
                    |  false                
                    v                          
                    _
                   ( ) <--- end do while loop
                    -
 
Figure 13: do while iteration control structure

  • do/while examples

    The if/else nested selection construct program

    In this section, we will show the nested if in the table below.

     
    /** **************************************************
     * While_13.java - this program 
     *    - Gets four grades from the user            
     *    - Computes the avaerage                    
     *    - Informs the user of their final grade         
     *                  
     *****************************************************/
    
    import javax.swing.JOptionPane ;
    
    class While_13  {
           String firstNum = "",      // first string entered by user
              secondNum = "" ;     // second string entered by use
    
        While_13() {
            int total = 0 ;
            calcAvg();
        }
    
       /** ************************************************** 
        * The calcAvg() function is called to create the 
        *  grade average.
        *****************************************************/
      
       void calcAvg() {
           int Score1, Score2, Score3, Score4 , n[] , i = 0;
          double average = 0.0 ;
          
          n = new int[ 4 ] ;
    
          while( i < 4 ) {
               firstNum =
                        JOptionPane.showInputDialog( 
                               "Enter a test score and it will be averaged: " ) ;
              n[ i ]  = Integer.parseInt(  firstNum  ); 
              average =   average + n[ i ] ;
               i++   ;
          }
    
          average =   average / 4.0;
    
         System.out.println( "\tGrade 1 "  + "\tGrade 2 " +  "\tGrade 3 "  +  "\tGrade 4 "  ) ;
         System.out.println( "\t    " + n[ 0 ] + "\t            " + n[ 1 ] + 
                "\t             " + n[ 2 ] +   "\t          " + n[ 3 ] + "\n" ) ;
    
          if (average == 100)
               System.out.println( "Congratulations! You've achieved a perfect score!\n"  );
          else if (average >= 90) {
               System.out.println( "Your average is " + average + "\n"  ) ;
               System.out.println( "Your grade is an A \n"  ) ;
         }
         else if (average >= 80) {
               System.out.println(  "Your average is " + average + "\n"  ) ;
               System.out.println( "Your grade is a B \n"  ) ;
        }
        else if (average >= 70) {
               System.out.println( "Your average is " + average + "\n"  ) ;
               System.out.println( "Your grade is a C  \n"  ) ;
         }
        else if (average >= 60) {
               System.out.println(  "Your average is " + average + "\n"  ) ;
               System.out.println(  "Your grade is a D  \n"  ) ;
         }
         else if (average < 60) {
               System.out.println(  "Your average is " + average  ) ;
               System.out.println(  "Your grade is \"F\" \n"  ) ;
         }
    
       }
    
       /** **************************************************
        * the main () function is the entry point that is called
        * when the While_13 program is loaded into memory.
        *****************************************************/
        public static void main( String args[] )  {
    
             While_13 app = new While_13();  
       }
    }
    
     
    Figure 14: nested if/else selection structure

    Definitions

    Böhm-Jacopini

      Computer scientists usually credit the Structured program theorem to a 1966 paper by Corrado Böhm and Giuseppe Jacopini.

    Boolean expression

      is a programming language expression that when evaluated produces a Boolean value, i.e. one that is either true or false. A Boolean expression may be composed of a combination of:
      1. the Boolean constants true or false;
      2. Boolean-typed variables;
      3. Boolean-valued operators; and
      4. Boolean-valued functions.

    conditional operator ? :

      The conditional operator ? : is a ternary operator (it takes three operands). It is of the form:
       
      (condition ? expression 1 : expression 2 ) 
       

    • If the condition evaluates to true then expression 1 is executed; otherwise, expression 2 is executed.

    control structure

      allows for a change of linear sequence/flow of program execution, based on some condition evaluating to true.

    Flowchart

      A flowchart is a method of diagraming the layout and/or flow of a program or algorith. This flow is shown using figures of various kinds, and their order by connecting them with arrows.

    Pseudocode

      is a compact and informal high-level design description (usually written in a spoken language) of a computer programming algorithm that adheres to the structural conventions of a programming language. Pseudocode is intended to be read by humans rather than by machine.




  • HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#


    To contact us

    © 2002 - 2016 All Rights Reserved Total Application Works