(syllabus and calendar)

Ch. 3 Program Control Statements
pp. 71-114

zip3 of examples

Session 3

if

if   else if   else

switch

Loops

break

continue

nested loops


Quiz

Computers are useful because we can harness their speed (particulary in loops of many iterations), and rely on their consistent behavior in program control statements. Unlike human beings, they do not get tired, bored, go on strike, form their own opinions, lose their focus on the task at hand, or make errors without a specific reason. If computers are like a fast vehicle, control statements are the steering wheel. Computers are like good soldiers that do exactly as instructed, but we, the Generals, have to give them clear, logical orders. In this sense, we direct the power of the computer through control statements.

if Statement

The most basic control statement is the if test.
The syntax involves a check that the if expression evaluates to a Boolean true (or at least does not return false):

if(condition) statement;

int myNum1 = 2;
int myNum2 = 4;
if (myNum1 + myNum1 == myNum2); // returns true

If condition without ==

What is the difference between (a) and (b)?

(a)
  if (isLeapYear == true)
(b)
  if (isLeapYear)
Answer: (a) is redundant because the statement after the condition only executes if the condition evaluates to true. 
It is better to write (b).

Format options for if statements

The three statements below are equivalent to each other.

  1. if(n==1) return 1; // one-line if statement - quickest to write
  2. // 2-line if statement is the most bug-prone if not read with care
    if(n==1)
    return 1; 
  3. // 4-line simple if statement - this is the most clear
    if(n==1)
    {
       return 1;
    }
which means three syntactic forms are possible:

If, else if, else

More complex logic can be implemented in a ladder or sequence:  if, else if, else if, else if, else sequence. There can be any number of else if statements. The beginning statement is if and the final statement is else.

Another example:


Switch

The series of else if statements becomes awkward if it is long. A more elegant and concise way to express the same logic is the switch with a series of case statements.

It is difficult to think of a use case that never uses break.

You can group adjacent case values, and here it can make sense to omit break for some adjacent values. Because booleans are not allowed, you cannot specify if i < 3.

Control statements (if, loop, case in switch) permit nesting.


Loops

Loops allow you to take advantage of the primary strength of the computer, SPEED, tireless speed, even to point of willingness to do infinite loops without complaint.

Looping and initialization of a Variable

While Loop

The most straightforward loop syntax is that of the while loop, which has three distinct expressions.

Two disadvantages of the while loop syntax:

for loop

The most common loop is a for loop. The syntax is combines and compacts the three statements of the while loop into a single, three-expression line:

 for (initialization; condition; increment) statement;

Example:

The output of the while loop and the for loop is the same:

Looping with char to process the letters of the alphabet


For Loop to process command-line args

The follow is a standard for loop to process the array of command-line arguments.

http://www.cafeaulait.org/course/week2/30.html


For Loop with relational and logical operators


Equivalence: a while loop and a for loop are equivalent to each other

Notes:


Do While Loop

Discussion: let's compare Do and Do While loops by looking at http://java.sun.com/docs/books/tutorial/java/nutsandbolts/while.html

A do while loop always executes at least once because it checks its condition after the executing an iteration of the statements it contains. (Fire the gun, then aim the gun?)

This do while loop uses escape sequences for carriage return (\r) and line feed (\n).


Multiple Initializers and Incrementers

Sometimes it's necessary to initialize several variables before beginning a for loop. Similarly you may want to increment more than one variable. Java lets you do this by placing a comma between the different initializers and incrementers:

for (int i = 1,  j = 100;  i < 100;  i = i+1, j = j-1)  {    
    System.out.println(i + j); 
}

You can't, however, include multiple test conditions, at least not with commas. The following line is illegal and will generate a compiler error.

for (int i = 1,  j = 100;  i <= 100, j > 0;  i = i-1, j = j-1) {    

To include multiple tests, use one or more the logical operators. This means that the condition can be simple or complex, yet still evaluate to a single boolean value.

 for (initialization; condition; increment) statement;

Another example, this time in an if statement.


Infinite Loop

An infinite loop is one in which the condition never evaluates to a boolean false. The crudest way to do this, is to hard-code the value true.

But a more elegant way is to leave the condition blank, such that is never can return false. (This short-cut for convenience might seem to run counter to the general philosophy of the explicit declarations of a strongly-typed language, but the condition is always implicit about its type, and only optional in regard to the value being explicit or implicit. We never formally declare the type of the condition as boolean.)

The shortest, clearest way to write an infinite loop is:
for( ; ; )

What is different now?

Why doe this application fail to compile?

What does the error message mean?

InfiniteLoop2.java:9: unreachable statement
System.out.println(); // Finish the line

What are typical use cases for an infinite loop?
The answer is embedded systems or daemon services, such as:

Infinite loop that tests for a particular character.



Break - a keyword that controls execution flow (p. 100)

The break keyword causes execution to exit the current code block, such as the current iteration of a loop. The keyword can be on the same line, the next line, or within its own code block.

Let discuss this example with break:

Break with label

This example has a label, search, for an outer for loop.
(This example involves a two-dimensional array that is 4 by 3, that is, four elements in three separate arrays.)

class BreakWithLabelDemo {
    public static void main(String[] args) {

        int[][] arrayOfInts = { { 32, 87, 3, 589 },
                                { 12, 1076, 2000, 8 },
                                { 622, 127, 77, 955 }
                              };
        int searchfor = 955; // to be found at 2, 3

        int i;
        int j = 0;
        boolean foundIt = false;

    search: // search is the label
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length; j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search; // exit the code block for search
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor +
                               " at " + i + ", " + j);
        } else {
            System.out.println(searchfor
                               + " not in the array");
        }
    }
}

Continue - related to break (p. 106)

Both break and continue interrupt the "normal" flow of execution. Whereas break forces the loop to exit, continue forces the loop to start a new interation.


Examples to Discuss

Just as the System.out object has a method for printing to the screen, so the System.in object has a method for reading keyboard input.
Note: 13 is the integer value of the Enter key. Line 15 casts the byte value of the key to a char value.


In the program that follows this chart, using continue in an infinite loop (line 21 goes to line 12) to force another iteration of the loop while ignoring the following statements inside the loop. The ASCII table specifies the character values.

Using break with a nested loop.

A case statement with break and a default value.

This for loop uses a double instead of an integer (which is unusual). Note that num++ involves a compound assignment operator and is equivalent to writing num = num + 1;

The loop decrements instead of incrementing, again with a compound assignment operator.

Monitoring two counters in a for loop

What is another way to write the following?   sum += i++;
(assuming we did not want to use a compound assignment operator)

The keyword continue forces execution to go to the end of the current loop.

class ContinueDemoNoLabel {
    public static void main(String[] args) {

        String searchMe = "peter piper picked a peck of pickled peppers";
        int max = searchMe.length();
        int numPs = 0;

        for (int i = 0; i < max; i++) {
            //increment numPs++ only if the char is 'p'
            if (searchMe.charAt(i) != 'p')
                continue; // go to end of loop

            //process p's whenever they occurred
            numPs++;
        }
        System.out.println("Found " + numPs + " p's in the string.");
    }
}

The keyword continue when followed by the identifier for a label forces execution to go to the specified label.

A Help system with an infinite loop

A lot of work done with only a few lines of code.

Let's rewrite this while loop as a for loop.

Use a while loop nested inside a for loop


Nested loops


Quiz - Session 3

  1. An if statement must present a test that evaluates to which data type?

  2. What statement can you add after if and else if to handle any cases they do not catch?

  3. True or false: A case in a switch expression can check for a floating-point value.

  4. The following is an ______________ loop: for(;;) { }

  5. Which type of loop is guaranteed to run at least once?

  6. Rewrite the following as a for loop:
    int i = 0;
    while(i < 5)
    { System.out.println(i);
      i++;
    }

  7. Write the keyword that causes a loop to terminate.

  8. Write the keyword that causes a loop to go to its next iteration.

  9. If the awaited condition of a switch does not occur, execution goes to the optional  __________ statement.

  10. True or false: if you write a switch in which two cases test for the same constant value, a runtime error will result.