Chapter 8

Loops

A loop is a block of code that executes repeatedly as long as a given condition is true. For example, a quiz application might present a question, accept user input, then ask the user if they want to try another question-- continuing to present questions until the user chooses to stop.

The important distinction between an “if” statement and a loop is that an if statement only checks a condition once; a loop keeps checking until it is no longer true.

While loops

A while loop executes a block of code repeatedly as long as a given condition is true (or until the condition becomes false).

The syntax is:

      while (condition)
      {
        [code to execute]
      }
      

A counter-controlled loop (or definite repitition loop) is one that runs a fixed number of times. It is created by first initializing a control variable to a certain value, then repeatedly testing the control variable against another value. Within the body of the loop, the value of the control variable is incremented (increased) or decremented (decreased).

Counter-controlled Loop Example: this will display all the integers from 1 to 10.

      int x=1; //the control variable
      while (x <= 10)
      {
        System.out.println(x);
        //increase x by 1 (add 1 and store back into x)
        x = x+1; 
      }
      
  1. It is essential to change (or give the user the ability to change) the value of the control variable inside the loop body; otherwise, it will run forever!
  2. x++ is a frequently used shortand way of writing x = x+1. See the section below on Assignment Operators for more on this.

A sentinel-controlled loop (or indefinite repitition loop) uses a value called a sentinel to determine when to exit the loop. It is not known in advance how many times the loop will run. Often the sentinel value comes from the user.

Sentinel-controlled Loop Example: this will keep multiplying x by 5 as long as the user enters yes.

      String answer = "yes"; //the sentinel
      while (answer.equals("yes")) //note the use of .equals (rather than ==) for String
      {
        x = 5*x;
        System.out.print("Again? Enter yes or no:);
        answer = kbd.nextLine();
      }  //at this point, we go back to the beginning of the loop and check if answer is still “yes”
      

Nested Loops

Just as with if statements, loops can be nested inside one another. Here’s an example:

      int i = 0;
      while (i < 5)
      {
        int j = 3;

        while (j >= 0)
        {
          System.out.println("i is " + i + " and j is " + j);
          j--;
        }

        i++; 
      }
      

Output:

i is 0 and j is 3

i is 0 and j is 2

i is 0 and j is 1

i is 0 and j is 0 (note that i stays at 0 until the inner loop completes execution)

i is 1 and j is 3

i is 1 and j is 2

i is 1 and j is 1

i is 1 and j is 0

i is 2 and j is 3

i is 2 and j is 2

i is 2 and j is 1

…[skipping some]...

i is 4 and j is 2

i is 4 and j is 1

i is 4 and j is 0

You might wonder why the second line of output isn’t “i is 1 and j is 2.” This is because the loop on the inside (the one involving the variable j) runs through its entire course for each iteration of the outer loop (with the variable i).

For Loop

The for keyword provides another way to create a loop. It combines the elements of a while loop into a single line. Here is Example 2 from above rewritten as a for loop.

      int x=1;
      while (x <= 10)

      {
        System.out.println(x);
        x= x+1;  // could also write x++ here.
      }
      

...becomes...

      for(int x = 1; x<=10; x=x+1) // or for(int x=1; x<=10; x++)
      {
        System.out.println(x);
      /*
      Do NOT change the value of the counter variable inside the loop--it's already done in the parentheses!
      */
      }
      

Note how lines 1, 2, and 5 from the while example are all combined into line line 1 in the for syntax. Here’s how for loop are set up (written on separate lines for ease of reading):

for([set a (controlling) variable equal to a starting value];

[give the condition to test each time the loop runs];

[change the value of the variable after each execution of the loop])

The controlling variable can be used purely to count how many times the loop has executed, or it can be used within the body of the loop, as shown in these examples:

      //A for loop that uses the controlling variable (count) within the loop body
      for(int count = 1; count <=10; count=count+1){
        System.out.println("This is round number " + round);
      }
      //A for loop that does not use the controlling variable (day) within the loop body
      for(int day = 20; day>0; day = day-1){
        savings = savings - 10;
        System.out.println("You now have " + savings);
      }
      

Each part of the condition is optional, however you will typically use all three. For example, for(int a = 15;;) is valid. In this case, the variable would be set to 15 initially, and we would expect that the "missing" parts are handled in the code block.

10.3 When to use While Vs. For

For loops work better when you know how many times the loop will run and/or there is a fixed pattern (involving numbers or counters). For example, a for loop would be appropriate for running a block of code exactly 5 times, or for working with every even number from 10 to 20. These situations are referred to as counter controlled loops. Sometimes the "counter variable" is used only for the purpose of counting (for example, repeating code 10 times); other times the variable is also used inside the loop (as in the example below on line 3).

      //A counter controlled loop
      System.out.println("Printing the square roots of the numbers 1 - 100");
      System.out.println("x \t sqrt(x)"); // use \t for tab between the numbers
      for(int num=1; num<=100; num=num+1){
        System.out.print(num + "\t: " + Math.sqrt(num));
      }
      

while loops are better when you’re waiting for some condition to be met, but don’t have any other information about when that will happen. For example, a while loop can be used to read in data from a file one line at a time (until a blank line is reached) or for validating user input (running until the user enters a valid value). These situations are referred to as sentinel controlled loops (think of a sentinel like a guard or watchout waiting for something to occur).

      //A sentinel controlled loop
      System.out.println("Enter a number between 100 and 200");
      int entry = kbd.nextInt();
      kbd.nextLine();
      //This loop will (repeatedly) execute if the user enters bad input.
      while(entry < 100 || enter >200){
        System.out.println("Invalid entry. Please try again.");
      }
      

Do while Loops

If you want to be sure that a loop executes at least once, use a do-while loop. The loop body will run once and then the condition will be checked to determine if it should repeat. The syntax is:

      do
      {
        [execute some code]
      } while([condition to test]); //note the semicolon here
      

Note the semicolon after the while statement in a do-while loop.

Break and Continue

You can add code to break out of a loop if a certain condition is met within the loop body. The keyword break exits the loop completely and moves onto the code following the loop. The continue keyword breaks out of the current iteration of the loop and starts the next iteration (i.e., ignores any remaining statements in the loop body and starts the loop again).

break and continue can be used with any type of loop. Here is how each might be used:

      //Using continue
      Scanner scan = new Scanner(System.in);
      double weight = 50;
      while (weight > 0){
        System.out.println("Enter weight to purchase");
        desiredWeight = scan.nextDouble();
        scan.nextLine();
        if(desiredWeight < 0){
          continue; //go to beginning of loop body- skip line 11
        }
        weight = weight - desiredWeight;
      }
      
      //Using break
      Scanner scan = new Scanner(System.in);
      double weight = 50;
      while (weight > 0){
        System.out.println("Enter weight to purchase or a negative number to exit");
        desiredWeight = scan.nextDouble();
        scan.nextLine();
        if(desiredWeight < 0){
          break; //exit the loop. Go to line 13
        }
        weight = weight - desiredWeight;
        }
      //code to execute immediately after break or after the loop terminates
      

Assignment Operators

In the previous sections, we’ve seen the use of ++ to add 1 to a variable. This is called incrementing. Here are a few more shortcuts. Note that these are never required (you can always write them the longer way), but you will encounter them frequently when reading code, so it is good to know them.

a++ is the same as a=a+1

a-- is the same as a=a-1

______________________________

a+=b is the same as a=a+b

a-=b is the same as a=a-b

This notation also works with the *, /, and % operators.

You can also write ++x in place of x++. In both cases, x will increase by 1. In the case of ++x, the program will first increment x, then use the value, whereas with x++, it will first use the value, then increment.

For example, this code snippet:

      int x=12, y=25;

      System.out.println(x++);
      System.out.println(++y);
      System.out.println(x);
      System.out.println(y);
      

produces the output:

12

26 (y is first incremented, then printed)

13 (x was incremented after being printed)

26