5 Adding Loops

 

After reading lesson 5, you will be able to:

  • Understand the syntax of loops in Java
  • Choose the appropriate type of loop for your program
  • Use the for-each loop (or enhanced for loop) to iterate over a series of values

A loop allows us to repeat a block of code until some condition is met.  In Java, the types of loops include:

for loop – used when you know how many times the loop needs to execute

while loop – most common and flexible loop, continues while a condition is true

do…while loop – same as a while loop, but the test condition is executed at the end of the loop, therefore the code is always executed at least once

for-each – iterates over a series of values without any counter or sentinel value

This lesson reviews each type of loop and examples of each loop. Each type of loop has some common errors that can cause an endless loop.  This is referred to as an infinite loop and sometimes the cause is hard to find. So, for each loop I will review some common errors that can cause an infinite loop.

5.1   Adding a Count Controlled Loop

5.2   The While Loop

5.3   The Do…While Loop

5.4   The for-each Loop

5.5   Summary