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

 

Selection statements in Java

•      Two forms of the if statement

•      if (condition)  do something;

–   The condition must return either true or false

–   if the condition is false, do nothing

•      OR select between two different actions

    if (condition)  do something;
else  do something different;

•      The switch statement selects between multiple options

 

 

Pseudocode

•      Thinking in English is easier than thinking in Java

•      Suppose we want to write a program to ask the user to enter a student grade, then have the program respond passed or failed

–   If the grade is greater than 60 the student passes, otherwise they fail

•      Think about the different steps that are necessary to write this program

 

Translate pseudocode to Java

public static void main(String[ ] args
{      Scanner in = new Scanner(System.in);

           System.out.println(“Please enter the grade”);

           double grade = in.nextDouble();

            if(grade > 60)
                System.out.println(“Pass”);

           else System.out.println(“Fail”);

    }

Nested if statements

•      If there is more than one decision to be made, the if statements can be nested.

if (grade > 90)           
    { System.out.println("you get an A");  }           

else if (grade > 80)
          { System.out.println("you get a B");  }       

         else if (grade > 70)     
                { System.out.println("you get a C");  }

                 else    { System.out.println("you get an F"); }

•      One or the other of an if/else statement is executed, never both.

 

Formatting nested if statements

•      Often the nested if is not further indented

 

if (grade > 90)           
    { System.out.println("you get an A");  }           

else if (grade > 80)
          { System.out.println("you get a B");  }       

else if (grade > 70)  
                { System.out.println("you get a C");  }

 else    { System.out.println("you get an F"); }

 

Dangling else problem

•      The compiler always associates an else with the immediately preceding if

if (x > 90)       
      if (y > 90)
            System.out.println(“x and y are > 90");              

    else
        System.out.println(“x is <= 90");


•      The compiler pays no attention to white space, so it thinks the else goes with the second if;  braces will tell it otherwise

     if (x > 90)   
{      if (y > 90)
            System.out.println(“x and y are > 90");  

      }    

    else
        System.out.println(“x is <= 90");


When to use braces

•      Often only one statement follows an if condition

–    In this case no braces are necessary

•      If several statements follow either an if or else statement, you must use braces to indicate that the belong to one block

    if (grade > 90)       
 {    System.out.println(“Grade is an A"); 
      System.out.println(“Good Job!");

       }   

    else
 {        System.out.println(“Not an A this time.");
         System.out.println(“Maybe next time.");
 }

   

 

Second control Structure:  Loops

•      Loops are also controlled by a conditional statement

•      The statements within the loop are repeated until the condition becomes false

•      Types of loops

–  for loops

–  while  loops

–  do  while loops

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

 

For loops

•      For loops are used when you know ahead of time how many times you want to repeat the statements in the loop body

•      Suppose we want to write Java code to find the sum of the first ten integers

•      We put it inside a main method, since it is not really part of a class

 

Example: sum the first ten integers

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

            int i, sum=0;

            for (i=1; i<=LIMIT; i++)

               {        sum = sum + i;          

             }

         System.out.println(sum);

     }

Note the three parts to the control statement

–    Initial value of the counter

–    Test for the final value

–    Modify the counter

 

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