Java Lesson 8: Loops (Iterative Statements)

0
34

Introduction

Java’s iterative looping statements are powerful constructs that permit the repetitive execution of a block of code. Programs without loops are much longer with many similar or equivalent statements repeated over and over. Consider the simple task of displaying the numbers from 1 through 8.

Is there a better way? Yes, fortunately there is – Java’s for, while, and do-while loops.

A Quick Discussion About break, continue, and return

The three jump statements break, continue, and return are often used in Java’s looping statements and in methods.

  • break prematurely exits (i.e., break out of) one or more blocks of code, and is similar to a goto statement in other programming languages. It may specify a label to identify the block of code.
  • continue forces an early iteration of a loop. It may specify a label.
  • return causes a return from a method back to the caller of the method.

We discuss these in detail later.

The for Statement

The for loop is a tool for looping through a series until some limit is reached. The loop exits when the limit is reached. The format of the for statement is:

The initialization is used to initialize an index that controls the looping action. Most commonly an int variable (such as ij, or k) is used, although it can be any valid variable name (e.g., counter).

The condition is a condition that must be satisfied for the loop to continue execution. Once the condition is satisfied then the loop exits and program execution resumes at the statement after the closing curly brace “}” at the end of the for loop. An example condition is i <= maxNumber.

The iteration is a unary expression (e.g., i++) or an assignment expression (e.g., i=i+1 or k=k+5).

When the for loop is executed, the condition is evaluated and tested before each pass through the loop, and iteration is evaluated at the end of each pass.

If only one statement is inside of the loop, then there is no need for the curly braces, although as with the if-else statement curly braces are recommended.

We now can write a program to display the numbers from 1 to 8 using a for loop.

Line 4 declares the initialization variable i for future use within the for loop.

Line 5 is the for statement. You can read it as: Start with i equal to 1. If i is less than or equal to 8 then execute the statement(s) between the curly braces, which is to print the value of i. Increment i by one (i.e., i=i+1). Check to see if i is still less than or equal to 8. If that is true, then execute the statements again. If that is false, then exit the for loop.

You can see how this is much shorter, especially if i is compared to a very large number such as all order numbers on a shopping website. The program output appears below:

Execution of Program8b

It is very common to declare and initialize the initialization variable inside the for loop:

The condition can be any arbitrarily complex expression:

The iteration can be an auto auto-increment (++) or auto-decrement ()

or an assignment of any arbitrary complexity:

The for loop is commonly used for array indexing as we will see in a future lesson.

The while Statement

The while statement is also often used to perform looping operations. The while loop checks to see whether an expression is true, and processes the statements in the body of the loop (a code block) until the expression becomes false. The general form of the while statement is:

You must change the conditions of the expression in some way within the loop, otherwise the loop will repeat forever (i.e., an infinite loop). Following is an example of an infinite loop:

In this example, the evaluation of doMore must become false at some point in the loop, perhaps with an assignment statement such as:

Just like we did with the for statement, we can write a program to display the numbers from 1 to 8 using a while loop.

Notice that the loop control variable i is initialized to 1, and then incremented on each pass through the loop. As long as i is less than or equal to 8 then the loop continues. When i is greater than 8 then the expression becomes false, and the while loop ends. The output from Program8c looks identical to the output from Program8b which used a for loop:

Execution of Program8c, displaying the numbers one through eight.

The do-while Statement

Sometimes it is desirable to have a loop with the test for continuation at the end of each pass through the loop instead of at the beginning of the loop. Java’s do-while statement accomplishes this. The do-while loop processes the statements in the body of the loop (a code block) and then evaluates an expression to see if the statements need to be processed again. The general form of the do-while statement is:

Note the semicolon (;) after the while statement.

You must change the conditions of the expression in some way within the loop, otherwise the loop will repeat forever (i.e., an infinite loop). Following is an example of an infinite loop:

In this example, the evaluation of doMore must become false at some point in the loop, perhaps with an if statement and an assignment statement such as:

Just like we did with the for statement and while statement, we can write a program to display the numbers from 1 to 8 using a do-while loop.

Notice that the loop control variable i is initialized to 1, and then incremented on each pass through the loop. Then i is evaluated at the end of the loop. As long as i is less than or equal to 8 then the loop continues. When i is greater than 8 then the expression becomes false, and the do-while loop ends. The output from Program8d looks identical to the output from Program8b and Program8c which used a for loop and while loop respectively:

Execution of Program8d, which displays the numbers one through eight.

Practical Examples Using while and do-while Loops

Recall Java Lesson 6 Console I/O where we learned how to use the Scanner class to read user input from the keyboard. Program8e.java makes use of a while loop to continuously read keyboard input until the user enters the “magic” number 8, at which point the loop will exit. Program8f.java does the same with a do-while loop. Enter these programs into your computer, compile, and run them. Then experiment and use a different magic number of your choice.

As a last example of Java’s loop statements, suppose we want a program which calculates the average of a list of numbers. We will first ask the user how many numbers will be averaged, and store this in a variable named n. Then we repeatedly get numbers from the user in a do-while loop, calculate a running total, and store that in the variable sum. We will increment a counter variable named count and compare it with n so we know when to exit the loop. Finally, we calculate the average and display it to the user.

There is one problem with this program: What if the user enters 0 or a negative number when the program prompts for how many numbers will be entered? Can you think of a way to make this program more robust to handle this possibility? (Hint: if statement) Would a different type of loop be a better choice for this application?

Summary

In this lesson we learned about Java’s three looping (iterative) statements, for, while, and do-while, which allow you to control the program’s execution by repetitively executing code blocks depending upon conditions at execution time.

Next Lesson

Loops are often used to process arrays. And curiously enough, that is the subject of our next lesson: Arrays.

Leave a Reply