Welcome to Lesson 12!

Learning Objectives
By the end of today's class, you should know...
  • What are 4 common uses of while loops?
    • Give an example of each one.
  • What are some other common mistakes people make when writing loops?
  • What is a counting loop?
  • What are the three important components of a counting loop?
  • What is a for loop and why was it designed?
  • How does a for loop differ from a while loop?

Announcements

  • Midterm 1 Graded:
    • As: 24 (1 100% score)
    • Bs: 8
    • Cs: 5
    • Ds: 3
    • Fs: 2
    • Absent: 1
  • Return midterms at the end of class
  • Don't forget Lab 6 due Friday!
  • Quiz 4 on Thursday


Pre-Assessment Activity


Review of Switch Statements:
  • Rewrite the following series of if statements as a switch statement:

if (choice.equals("Ice Cream")) {

    System.out.println("Good choice!");

} else if (choice.equals("Cake")) {

    System.out.println("Okay choice!");

} else {

    System.out.println("What kind of a dessert is that?");

}



Review of While Loops:

  • Label the different parts of the following while loop as: update statement, initialization or test condition.

int count = 1;

while (count <= 10) {

    System.out.println(count);

    count++;

        } 
  • Correct the loops below. What will happen if you run the code BEFORE making the corrections?

Loop 1:

String repeat = "y";

while (repeat.equals("y")) {

    System.out.println("Playing an exciting game!\n");

    System.out.println("Want to play again? (y/n): ");

        }

Loop 2:

    int counter = 1;

  while (counter <= 10) {

      System.out.println(counter);

      } 

Applications of Loops
  • Let's look at 4 common loop applications:

1. Indefinite Loops

Recall our looping application that simulated the play of an exciting game


    public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String repeat = "y";
while (repeat.equals("y"))
{
System.out.println("\nPlaying an exciting game!");
System.out.println("Do you want to play again? (y/n) ");
repeat = input.next();
}
System.out.println("\nThanks for playing!");
}
  • Loops of this type are called indefinite loops because you do not know in advance how many time the loop will execute
  • This behavior is different from a counting loop where you know how many times the loop will execute before the loop starts
  • With an indefinite loop we can solve a new set of problems
  • Most problems solved with indefinite loops make use of while statements


2. Processing a Sequence of Inputs
  • Another common use for indefinite loops is to process a sequence of inputs
  • As an example, let us add up (sum) a series of numbers
  • Every number is added to the sum
  • We use a loop to repeat the input until the user decides to stop
  • Since we do not know how many number the user will enter, we use an indefinite loop as shown below


public static void main(String[] args) {
    double number = 1;
    double sum = 0;
    String repeat = "y";
    Scanner input = new Scanner(System.in);

    System.out.println("I will add up numbers for you\n"); while (repeat.equals("y")) { System.out.println("So far, sum = " + sum); System.out.print("Enter a number: "); number = input.nextDouble(); sum = sum + number; System.out.print("Another number? (y/n) "); repeat = input.next(); } System.out.println("Ending sum: " + sum); }

3. Terminating the Input with a Sentinel

  • Whenever we read a sequence of input values, we need to have some way of terminating the input loop
  • We could use a separate variable and input statement as we have done before:
    String repeat = "y";
    while (repeat.equals("y")) {
        // ... statements to repeat
        repeat = input.next();
    }
    
  • However, when entering numbers (or other data) repeatedly, answering an extra question each time through the loop becomes annoying
  • One way to avoid asking an extra question is to use a sentinel value
  • sentinel is guard who watches for something to happen
  • Similarly, a sentinel in a program watches for a specific sentinel value that signals termination of a loop
  • To use a sentinel value, we must have a special value in the input
  • Some commonly used sentinel values for numeric input are 0 or -1
  • However, if our application suggests another value, then we should use that value
  • The following program is an update of the previous program to use a sentinel value to end the loop

Example Application Using a Sentinel Value for the Loop Test

public static void main(String[] args) {
    double number = 1;
    double sum = 0;
    Scanner input = new Scanner(System.in);    

    System.out.println("I will add up numbers for you\n"); while (number != 0) { System.out.println("So far, sum = " + sum); System.out.print("Enter a number or 0 to exit: "); number = input.nextDouble(); sum = sum + number; } System.out.println("\nEnding sum: " + sum); }

4. Input Validation

  • Another common use for indefinite loops is input validation
  • Input validation combines a loop with one or more if statements
  • The input statement is placed inside the loop
  • The if-statement tests for an incorrect input value
  • The loop repeats while the user's input contains an error
  • Since we do not know how many times the loop must execute ahead of time, the loop is indefinite
  • For example, the following program uses a loop to ensure a user enters a positive number
  • The if statement is used to decide when to output an error message

Example of Input Validation Using a Loop


public static void main(String[] args) {
    double number = 0.0; // initialize value
    Scanner input = new Scanner(System.in);    

    while (number <= 0) { System.out.print("Enter a positive number: "); number = input.nextDouble(); if (number <= 0.0) { System.out.println("You must enter a positive number\n"); } } System.out.println("\nYou entered: " + number); }
  • We will explore all of these applications in our programs as we continue to write loops.

Activity 12.1: Guessing Game The Final Round (10 pts)

  • Copy the following program into an Eclipse project named Loopy and then compile and run the starter program to make sure you copied it correctly.
    import java.util.Scanner;
    
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("I'm thinking of a number between"
             + " 1 and 10.\nCan you guess it?\n\n"
             + "Enter your guess: ");
        int guess = input.nextInt();
        
        if (7 == guess)
        {
            System.out.println("*** Correct! ***\n");
        }
        else
        {
            System.out.println("Sorry, that is not correct.");
            System.out.println("Try again.");
        }
        
    }
    
  • Add the following code after the statement where int guess; is declared:
    String repeat = "y";
    

    This is the initialization code that we will use for the test condition that comes next.

  • We want to repeat all the rest of the code in our program. For this we need to add a while statement such as:
    while (repeat.equalsIgnoreCase("y")) {
        // Place the rest of the code after the initialization
        // and before the end of main between these curly braces.
    }
    

    Statements inside the curly braces repeat while the test condition in the parenthesis, (repeat.equalsIgnoreCase("y")), evaluates to true. 

  • Inside the while loop we need some way to change the test condition. We change the test condition by letting the user enter a value for the repeat variable by adding the following code at the end of the loop just before the closing curly brace:
    System.out.print("\nDo you want to play again? (y/n) ");
    repeat = input.next();
    

    Without these two statements our loop would have no way to exit. A loop with no way to exit is known as an infinite loop

  • Formatting a loop is important. Indent all the code within the curly braces of the while loop. 
  • As a final part of our program, we add the infamous phrase: "Game Over". Add the following statement after the closing curly brace of the while loop:
    System.out.println("Game over");
    
  • Compile and run your program again and verify the output looks like:
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess: 3
    Sorry, that is not correct.
    Try again.
    
    Do you want to play again? (y/n) y
    I'm thinking of a number between 1 and 10.
    Can you guess it?
    
    Enter your guess: 7
    *** Correct! ***
    
    Do you want to play again? (y/n) n
    Game over
    
  • Submit your program source code to Catalyst.
  • If you finish early, find someone to help! Remember, you learn by teaching others.

Completed Program

When finished, your application should look like the following. Note especially the extra indentation within the curly braces of the while loop.



Common Loop Pitfalls

  • Loops have many pitfalls for the unwary
  • The following are the most common problems you should look out for

Infinite Loops

  • Common error: unintentional infinite loop
  • For example, what is wrong with the following code?
1
2
3
4
5
6
7
8
9
10
11
12

    public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String repeat = "y";
while (repeat.equals("y"))
{
System.out.println("\nPlaying an exciting game!");
System.out.println("Do you want to play again? (y/n) ");

}
System.out.println("\nThanks for playing!");
}

Missing Curly Braces

  • The curly braces of a while loop let us associate multiple statements with a while loop
  • However, if we leave off the curly braces, only the first line of code after the while statement is interpreted to be part of the loop.
  • For example, what is wrong with the following code?
1
2
3
4
5
6
7
8
9
10
11
12
13

public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String repeat = "y";
while (repeat.equals("y"))

System.out.println("\nPlaying an exciting game!");
System.out.println("Do you want to play again? (y/n) ");
repeat = input.next();

System.out.println("\nThanks for playing!");
}


Empty Statements

  • Remember that statements are terminated by a semicolon
  • Is the following a legal statement?
    ;
  • This is known as an empty or null statement
  • Empty statements are a common source of infinite loops
  • For example, what is wrong with the following code?


public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String repeat = "y";
while (repeat.equals("y")) ;
System.out.println("\nPlaying an exciting game!");
System.out.println("Do you want to play again? (y/n) ");
repeat = input.next();

System.out.println("\nThanks for playing!");
}
}

Counting Loops

  • Counting is a common task in our lives.
  • In programming, counting is also very common.
  • In our last activity, we saw an example of counting, where we used a while loop to count sheep.
  • In programming we often use loops to count when we know exactly how many times we want a specific piece of code to repeat.
  • In fact, counting is such a common programming task, that a special type of loop was designed specifically for counting.
  • This loop is called a for loop, and we will be learning more about it in class today.

For Statements
  • As previously mentioned, counting is a very common use for loops.
  • Loops that are controlled by a counter variable are called counter-controlled loops.
  • We can visualize a counter-controlled loop as a series of steps to reach a goal.

small picture of someone climbing numbered steps of a stair

Image source.

  • A counter-controlled while loop has the form:
    int i = start;
    while (i < end) {
        ...
        i++;
    }
    
  • Where:
    • i: the name of a counter variable
    • start: the initial starting value
    • end: the final ending value

  • We can write this same counting loop as a for loop:
    for (int i = start; i < end; i++) {
        ...
    }
  • The for loop was especially designed for counting tasks.
    • Notice its compact syntax compared to the while loop.
    • All the conditions which define the loop are on a single line.

  • When writing a counting loop, we often have a choice of using either a for or a while loop, as both will accomplish the same task.
    • However the compact syntax of the for loop makes it preferable.
  • The following example shows the same loop written as both a while loop and a for loop:
//counting from 10 to 20 using a while loop
int i = 10; 
while (i <= 20)
{
    System.out.println(i);
    i++;
}

//counting from 10 to 20 using a for loop
for (int i = 10; i <= 20; i++)
{
    System.out.println(i);
}
  • What differences do you notice in the two loops above?
  • What are the starting values for the loops? Where are they located?
  • Test conditions?
  • Update statements?
  • Notice the use of the semi-colons in the for loop. Which statements end with semi-colon and which do not?

Another For Loop Example


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

    System.out.println("This program uses a loop to count!");
    System.out.println("Enter the maximum number: ");
    max = input.nextInt();

    for (int i = 1; i <= max; i++)
    {
        System.out.println(i);
    }
}

Anatomy of the For Loop

  1. When for loop is reached, execute the initialize statement (starting point).
    1. This initialization step occurs only once.
    2. Note that i is the most common choice for our counting variable.
    3. Ex above: int i = 1;
  2. Check if condition is true.
    1. This occurs right after initialization, and after every iteration. 
    2. Ex above: i <= max;
    3. if true then continue with Step 3
    4. Otherwise it is false  continue with Step 6
  3. Execute the block containing the statements to repeat (body)
  4. When the end of each iteration of the loop body is reached, execute the update statement.
    1. This occurs at the end of every completed iteration.
    2. Ex above: i++;
  5. Return to Step 2
  6. The loop is finished when the test condition becomes false
    1. Continue with statements after the loop


Diagram of for Loop Operation

C++ for loop

Image source.


Group Activity: Altering a For Loop

  • With your partner: Copy and paste the below for loop into an Eclipse project called Loopy
  • Now, try altering the for loop to see if you can achieve the following results:
    • Can you make the loop print out the numbers from 0 up to and including the max?
    • Can you make it print out the numbers from 0, up to, but not including, the max?
    • Can you make it count up by 2s to the max?
    • Can you make the loop count down from the max to 0?

/**
 *
 * @author
 */
import java.util.Scanner;

public class Loopy {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int max = 0;
       
        Scanner input = new Scanner(System.in);
        System.out.println("This program uses a loop to count!\n");
        System.out.print("Enter the maximum number: ");
        max = input.nextInt();
        System.out.println();

        for (int i = 1; i <= max; i++)
        {
            System.out.println(i);
        }
    }
   
}



Activity 12.2: Counting Down Part 3 (10 pts)
  • Find a partner for pair programming
  • Open up your Countdown.java file from last class in Eclipse.
  • Locate the while loop in your code.
  • Alter this while loop to be a for loop.
  • Hint: Make sure that your for loop has 3 parts:
    • initialization (where do you want to start counting)
    • test condition (when should the loop fail?)
    • update statement (are you counting up or down here?)
  • Compile and run your program and verify that you still get the following output:
NASA Mission Control readying for liftoff.
Initializing countdown from 10...
10
9
8
7
6
5
4
3
2
1
We have liftoff!
  • Submit your program to Canvas when you are finished.

Wrap Up
  • With your partner, answer the questions from today's learning objectives


Upcoming Assignments


~See You Thursday!~