Control Structures

Chapter 4

Control structures--statements that control the flow of execution

      All programs can be written in terms of three control structures

   Sequence structure

   Executing statements sequentially

   if  (condition)-- selection structure

   Condition is either true or false

   Select between paths of execution

   Loops -- repetition structures

   Execute a block of statements over and over

for loops

      Executes a section of code a fixed number of times

      for(count=0;count<10;count++)
 {
    statements
 }

      Note the three parts to the control statement

   Initial value of the counter

   Test for the final value; this is the terminating condition

   The modify the counter; here we use the increment operator

 

Loops

             ALL loops must have three things that control how many times to go through the loop

         Initialize the control variable

         Tell what the terminating condition is

         Change the control variable so that at some point the terminating condition is reached.

             The while loop does these three things differently than the for loop

for loops

      All three things are done within the for parentheses

      for(count=0;count<10;count++)
 {
    statements
 }

      Note that there are really three statement within the parentheses

   A semicolon terminates a statement

 

while loop

           The programmer must do all three things separately in the while loop

        The control variable must be initialized before going into the loop

        The terminating condition is in parentheses

        The change to the control variable must be done inside the loop block

           while (condition)
 {
    statement block
 }

           The statements inside the while loop block will be executed until the condition becomes false

           Note that if the condition is not true, none of the statements in the while loop will ever be executed

 

Writing a while loop

             Suppose we want to find the sum of the first 5 integers

             Pseudocode to write the while loop

          Declare and initialize two int variables: one to hold the total, the other to hold the control variable

          Decide on the terminating condition

          Write the block of the while statement

          Write the statement to sum the numbers

          Change the control variable

 

The while loop

public static void main(String[ ] args)
{   
     int sum = 0, num =1; 

            while (num < 11)

               {        sum = sum + num;

                     num++;

             }

         System.out.println(sum);

     }

 

Comparing the while loop and for loop

public static void main(String[ ] args)
{   
        int num = 5, sum=0; 

             for (int i=1; i<=num; i++)

               {       
                  sum = sum + i;

                }

         System.out.println(sum);

     }

 

public static void main(String[ ] args)
{   
     int sum = 0, num =1; 

            while (num < 6)

               {
                sum = sum + num;

                     num++; 

                 }

         System.out.println(sum);

     }

 

Note about the while loop

      while (condition)
 {
    statements
 }

      The statements inside the while loop block will be executed until the condition becomes false

      Note that if the condition is not true, none of the statements in the while loop will ever be executed

      You may want the loop to execute at least once, regardless of the truth of the condition

      Then you use a do while loop

 

The do while loop

   do
 {
   statements
 
}
while (condition)

      Note that you always execute the statements in a do loop at least once

      The condition is checked at the end of the loop

Walk through this program

public static void main(String[ ] args)            
{  
       final int LIMIT = 20;

            int next=0, last=1, sum;

 

           while (next < LIMIT)

             {          System.out.print(last +  "   "); 

                        sum = next + last;

                        next = last;
       last = sum;

             }

         System.out.println("done");

     }

      We looked at code to print out the Fibonacci series

   Each term is the sum of the previous two term

   1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ….

   You should do a walkthrough of this program

   In a walkthrough the person simulates the computer

   You keep a chart of the variables, and how they change as each statement executes

 

Sentinel values

      Example:  You want to develop a class averaging program that will process an arbitrary number of grades

      Ask the user to enter the grades to process, then enter a sentinel value when all the grades have been entered

      The sentinel must be be confused with a grade

    Negative one would be good in this case

    Zz is sometimes used when entering strings

      You must keep in mind the sentinel must be of the same type as the other data that is being entered

 

Example using a sentinel value

public static void main(String[] args) throws Exception

     {  int count = 0;

            double avg, grade=0.0, sum = 0.0;

            System.out.println("This program will find the average of the
                                                                    grades you enter");

            System.out.println("Please enter the grades separated by a
                                            return.  Enter -1 when finished");

            grade = BasicIo.readInteger();

            while (grade != -1)

                        {   sum = sum + grade;

                             count++;

                             grade = BasicIo.readInteger();

                        }

            avg =  sum/count;

            System.out.println("The average of " + count + " grades is " +
                                                                                            avg);   
}