Home CPSC 220

Loops

Introduction

Most programs need repetition of some kind. For example:

For these cases, we need loops in Java. There are three different loops in Java, and we'll look at each of them.


While Loops

The simplest loop in Java is the while loop which has this form:


while (condition) {
    body
}

This code will test the condition. If it is true, it will execute the body. Then, it will test the condition again. If it's still true, it will execute the body again. It will continue doing this until the condition is false.


Example: Input Validation

One way we could use a while loop is to do input validation. The following program reads in a user's name and age.


import java.util.Scanner;

public class Greeting {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter your name and age: ");
        String name = in.nextLine();
        int age = in.nextInt();
        
        System.out.println("Hello " + name + ", you are " + age + " years old.");
    }
}

How could we change it so that, when the user enters a negative age, it continues to ask for their age until they enter a positive value?





Example: Guess the Number

Now that we have the while loop, we have enough to implement the guess the number algorithms. How could we write a Java program for this simple algorithm:

  1. Set g = 1
  2. Guess g
  3. If correct, we're done
  4. Otherwise, set g = g + 1, and go back to step 2



How about this algorithm for when we know when the guess was too low or too high?
  1. Set min = 0
  2. Set max = 1000
  3. Set g = (min + max) / 2
  4. Guess g
  5. If correct, we're done
  6. If too low, set min = g + 1
  7. If too high, set max = g - 1
  8. Go back to step 3




For Loops

A common type of loop is one that runs a set number of times. We could write a while loop that runs 10 times like so:


public class Counting { 
    public static void main(String args[]) {
        int i = 0;
        while (i < 10) {
            System.out.println("i = " + i);
            i++;
        }
    }
}

This is so common that there is a special loop, the for loop, that does this. The previous program can be re-written using a for loop as follows:


public class Counting { 
    public static void main(String args[]) {
        for (int i = 0; i < 10; i++) {
            System.out.println("i = " + i);
        }
    }
} 

For loops contain three parts, separated by semi-colons:

  1. The initialization portion, which initializes a counter variable and is executed at the start of the loop.
  2. The condition which is tested each time through the loop.
  3. The update which is executed at the end of each iteration of the loop.

Example: Factorials

The factorial of an integer x is defined as:

$x! = x \times (x - 1) \times (x - 2) ... \times 3 \times 2 \times 1$

How could we write a program that computes factorials using a for loop?





Break & Continue

Sometimes we want to be able to break out of a loop in the middle of it. This can be done with the "break" statement:


public class Break { 
    public static void main(String args[]) {
        for (int i = 0; i < 10; i++) {
            // stop the loop when i is 5
            if (i == 5) {
                break;
            }
            System.out.println("i = " + i);
        }
    }
}

Break is rarely needed, but can be useful in some instances. For example, if there are multiple cases where you want the loop to end, you could use if/else statements with breaks instead of having a huge loop condition.

Another statement that changes the way a loop works is "continue". With continue, we skip over one iteration of the loop and move to the next one:


public class Continue { 
    public static void main(String args[]) {
        for (int i = 0; i < 10; i++) {
            // skip iteration when i equals 5
            if (i == 5) {
                continue;
            }
            System.out.println("i = " + i);
        }
    }
}

continue should also be rarely used. It can be useful when you want to skip over some iterations of a loop.


Do While Loops

The last type of loop we have is the "do-while" loop. This loop is very similar to the while loop except that it tests the condition at the end of the loop instead of the beginning.


do {
    body
} while (condition);

do-while loops are less common than while loops and for loops. They are best used when we always want to do the loop body at least once.


Example: Repeating a Program

One case where we always want to do the loop at least once is when we want to repeat the execution of a program. Below is the leap year calculator:


import java.util.Scanner;

public class Test { 
    public static void main(String args[]) {
        System.out.print("Enter year: ");
        Scanner in = new Scanner(System.in);
        int year = in.nextInt();

        boolean leapyear;
        if ((year % 400) == 0) {
            leapyear = true;
        } else if ((year % 100) == 0) {
            leapyear = false;
        } else if ((year % 4) == 0) {
            leapyear = true;
        } else {
            leapyear = false;
        }

        if (leapyear) {
            System.out.println(year + " is a leap year!");
        } else {
            System.out.println(year + " is NOT a leap year!");
        }
    }
}

How could we make it so this program asks the user if they want to run it again at the end?




Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.