Loops


When you play a song, you can set it to loop, which means that when it reaches the end it starts over at the beginning. A loop in programming, also called iteration or repetition, is a way to repeat one or more statements. If you didn’t have loops to allow you to repeat code, your programs would get very long very quickly!

While Loops

A while loop executes the body of the loop as long as (or while) a boolean condition is true. This is kind of like if-statements! But a while loop will run more than once.

When the condition is false, we exit the loop and continue with the statements that are after the body of the while loop. If the condition is false the first time you check it, the body of the loop will not execute at all.

while (condition) {

   // Replace with code

}

// The program would only exit the loop when the condition is false

Counter-controlled

The simplest loops are counter-controlled loops like below, where there is a loop counter variable which controls how many times to repeat the loop. There are 3 steps to writing a loop using this loop control variable as seen below in a loop that counts from 1 to 10.

Remember these 3 steps to writing a loop:

  1. Initialize the loop variable (before the while loop)
  2. Test the loop variable (in the loop header)
  3. Change the loop variable (in the while loop body at the end)

public class Main {

   public static void main(String[] args) {

      int count = 0;

      while (count < 5) {

         System.out.print(count + " ");

         count++;
     }

   }

}

0 1 2 3 4

Common errors with counter-controlled loops

One common error with loops is infinite loops. An infinite loop is one that never stops (the condition is always true).

// an infinite loop

while (true) {

   System.out.println("This is a loop that never ends");

}

The infinite loop above is pretty obvious. But, most infinite loops are accidental. They usually occur because you forget to change the loop variable in the loop (step 3 of a loop).

Another common error with loops is an off-by-one error where the loop runs one too many or one too few times. This is usually a problem with step 2 the test condition and using the incorrect relational operator < or <=.

Input-controlled

You can use a while loop to repeat the body of the loop a certain number of times as shown above. However, a while loop is typically used when you don’t know how many times the loop will execute. It is often used for an input-controlled loop where the user’s input indicates when to stop. The input, assigned by the programmer, to indicate when the loop should stop is called the sentinel value. This value should be carefully selected so that a valid input isn’t disregarded.

int number, sum = 0, count = 0;

double average;

Scanner scan = new Scanner(System.in);

System.out.print("Please enter a natural number or -1 to stop: ");

number = scan.nextInt();

while (number != -1) {

   sum += number;

   count++;

   System.out.print("Please enter a natural number or -1 to stop: ");

   number = scan.nextInt();

}

average = (double) sum/count;

System.out.println("The average is " + average);

Another common use of input-controlled loops is for rejecting invalid inputs from users.

Scanner scan = new Scanner(System.in);

System.out.print("Input your numerical grade: ");

double grade = scan.nextDouble();

while (0 > grade || grade > 100) {

   System.out.print("That is not a valid grade. Try again: ");

   grade = scan.nextDouble();

}

Do-while Loops

While loops sometimes never evaluate because the condition is checked first thing, before entering the loop. A do-while loop is very similar to a regular while loop, only the condition is evaluated at the end of the loop code, rather than the beginning. This guarantees the loop code evaluates at least one time.

do {

   // Replace with code

} while (condition)
// The program would only exit the loop when the condition is false

These can be helpful for input-controlled loops. For instance, this is the same code from above, but with a do-while loop. However, note that now, a custom message is now not given to the user if they input something invalid.

Scanner scan = new Scanner(System.in);

double grade;

do {

   System.out.print("Input your numerical grade: ");

   grade = scan.nextDouble();

} while (0 > grade || grade > 100)

For Loops

Another type of loop in Java is a for loop. This is used when you know how many times you want the loop to execute. A for-loop combines all 3 parts of writing a loop in one line. It initializes, tests, and changes the loop counter variable. The 3 parts are separated by semicolons (;).

for (initial; condition; change) {

   // Replace with code

}

Note that you can always write a while loop that does the same thing as your for loop.

The flow of a for loop is shown below.

for (int i = 1; i <= 3; i++) {

   System.out.println(i + " little pigs");

}

1 little pigs

2 little pigs

3 little pigs

Looping Strings

Remember that strings are a sequence of characters where each character is at a position or index starting at 0.

a string with the position (index) shown above each character

The first character in a Java String is at index 0 and the last characters is at length() - 1

So loops processing Strings should start at 0 and should use < as a test condition!

For-loops can also be used to process strings, especially in situations where you know you will visit every character.

String myStr = "loopy";

for (int i = 0; i < myStr.length(); i++) {

   System.out.println(myStr.charAt(i));

}

l

o

o

p

y

Nested Loops

A nested loop has one loop inside of another. When a loop is nested inside another loop, the inner loop runs many times inside the outer loop. In each iteration of the outer loop, the inner loop will be re-started. The inner loop must finish all of its iterations before the outer loop can continue to its next iteration.

for (int i = 0; i < 3 ; i++) {

   System.out.println("--------------");


  for (int j = 1; j < 4; j++) {

      System.out.println(j);
  }

}

--------------

1

2

3

--------------

1

2

3

--------------

1

2

3


Break

A break statement can be used to exit a loop. Note that if break is used within nested loops, only the inner loop would be exited. For example, the code below will check if an inputted word has at least 2 letter “e”s.

Scanner sc = new Scanner(System.in);

String word = sc.nextLine();

int count = 0;

for (int i = 0; i < word.length(); i++) {

   // Checks if the current letter is an 'e'

   if (word.toLowerCase().charAt(i) == 'e') {
     count++;

   }

   // If there have been 2 'e's, no more letters need to be checked

   if (count == 2) {

      System.out.println("There are at least 2 letter e\'s!");

      break;

   }

}

Continue

A continue statement can be used to skip to the next iteration of a loop. Note that if continue is used within nested loops, only the inner loop’s iteration would be exited. For example, the code below prints an inputted word with all letter “e”s removed.

Scanner sc = new Scanner(System.in);

String word = sc.nextLine();

for (int i = 0; i < word.length(); i++) {

   // Checks if the current letter is an 'e'

   if (word.toLowerCase().charAt(i) == 'e') {
     continue;

   }

   // If the program has made it here, the letter is not an e

   System.out.print(word.charAt(i));

}