Iteration Statements
Introduction to Loops
In general, statements are executed sequentially – the first statement in a method is executed first, followed by the second, the third, and so on.
There are times when you need to execute a block of code multiple times; often with variations in each execution.
Programming languages provide flow-control structures that allow more complicated execution paths.
Loop statements allow for executing a single statement or group of statements multiple times.
A loop is typically controlled by an index or counter variable.
Why Loops?
Repeated Actions:
Suppose we need to print a string (e.g., "Welcome to Java World!") 100 times. It would be tedious to have to write the following statement a hundred times:
How do you solve this problem?
Opening Problem
Suppose you want to print "Welcome to Java World!" 100 times. You could write the following code:
This would be very tedious and time-consuming. However, there is an easier way to accomplish this task using loops.
Loop Statement Flowchart
The diagram illustrates a loop statement:
Types of Loops in Java
Java supports three loop statements:
for loop
Executes a sequence of statements multiple times over a range of values, and abbreviates the code that manages the loop variable.
while loop
Repeats a statement or group of statements while a given condition is true.
Evaluates the condition before executing the loop body.
do-while loop
Similar to while loop, except that the condition is evaluated after the statements are executed.
Guarantees that the loop executes at least once.
Introduction to for Loops
A for loop in Java iterates over the items in any sequence:
The statement(s) within the for loop will repeat until the entire sequence has been visited.
For loops are often used to iterate through all elements in a collection.
A for loop has three parts:
Initialization.
Continuation condition.
Action-after-each-iteration.
General Syntax:
Nested Loops
The placement of one loop inside the body of another loop is called nesting.
When we nest two loops, the outer loop takes control of the number of complete repetitions of the inner loop.
Any type of loop may be nested.
Following is the basic Syntax for the "Nested for loop”:
Nested Loop Example
Nested Loop Example
Here is an example of a nested loop in Java:
The expected output is:
Enhanced for Loops
The for statement has another form designed to iterate through arrays and collections.
The syntax of the Java enhanced loop is that it can be applied to arrays, various collection classes, and any class implementing the Iterable interface.
Example usage:
In the example above:
array
- an array or a collection.item
- a variable array/collection assigned.dataType
- the data type of the array/collection.
Introduction to while Loops
As the name suggests, while loop will continually process a statement or given code block while its evaluation condition is true.
Syntax:
while Loop Flowchart
while Loop Flowchart Example
Trace for Loop
It is also valid to declare i before the loop, giving i greater scope:
Trace for Loop - Iteration #1 Test for Continuation #1
Trace for Loop: Iteration #2 Test for Continuation #2
A Misplaced Semicolon
Adding a semicolon at the end of the for clause before the loop body is a common mistake — a logic error:
Nested Loops
The placement of one loop inside the body of another loop is called nesting.
When we nest two loops, the outer loop takes control of the number of complete repetitions of the inner loop.
Any type of loop may be nested.
Following is the basic Syntax for the "Nested for loop”:
Nested Loop Example
Topic 1b: Enhanced for Loops
The for statement has another form designed to iterate through arrays and collections. The syntax of the Java enhanced loop is that it can be applied to arrays, various collection classes, and any class implementing the Iterable interface.
In the example above:
array - an array or a collection.
item - a variable array/collection assigned.
dataType - the data type of the array/collection.
Hands-On Lab - for loop
Complete this lab GLAB- 303.5.1- For Loop. You can find this lab on Canvas under the Assignment section. Use your office hours to complete this Lab. If you have technical questions while performing the Lab activity, ask your instructors for assistance.
Topic 1c: Introduction to while Loops
As the name suggests, while loop will continually process a statement or given code block while its evaluation condition is true.
while Loop Flowchart
The condition must evaluate to true for the body of the while loop to execute (just like the if statement and for loop).
while Loop Flowchart Example
Trace while Loop
Initialize count. (count < 2) is true.
Omitting the Loop-Continuation-Condition
If the loop-continuation-condition in a for loop is omitted, it is implicitly true. The statement (a) is valid Java. It is an infinite loop. The statement (b) is preferred just to avoid confusion.
Ending a Loop With a Sentinel Value
Often, the number of times a loop is executed is not known ahead of time. You may use a special input value to signify the end of the loop. Such a value is called a sentinel value.
Example: While loop
Make a new class and call it whileloop example. Inside, write the code shown below:
Output:
Hands-On Lab - While loop
Complete GLAB- 303.5.2 - While Loop. You can find this lab on Canvas under the Assignment section. Use your office hours to complete this Lab. If you have technical questions while performing the lab activity, ask your instructors for assistance.
Topic 1d: Introduction to do-while Loops
The do-while and while loop are similar, and work in a similar way, except that in a do-while loop, an expression is evaluated at the bottom as compared to the while loop. To put it in another way, the do-while loop guarantees that the loop body will execute at least once.
do-while Loop Examples
Finite do-while loop:
Looping while true:
Topic 1e: Use Which Loop?
Use the loop that is most intuitive and most comfortable for you.
In general, a for loop may be used if the number of repetitions is known. For example, you may need to print a message 100 times, or it can be supplied by the user.
A while loop may be used if the number of repetitions is not known. For example, it may read numbers until the input is 0 or it may read data from a database.
A do-while loop is a good choice when you are asking a question that will answer whether or not the loop is repeated.
Topic 2: Loop Control Statements
In this section, we will discuss the break and continue keywords.
Loop control statements
Loop control statements — sometimes referred to as jump statements — change loop execution from its normal sequence. Java supports the following loop control statements:
break – terminates the loop statement and transfers execution to the statement immediately following the loop.
continue – causes the loop to skip the remainder of its body and immediately jump to the top of the loop.
In while loops and for loops, the loop-continuation-condition will be evaluated.
Example: Using break keyword in a Loop
This program adds the integers from 1 to 20, in this order, to sum until the sum is greater than or equal to 100.
Output:
Without the if statement, the program calculates the sum of the numbers from 1 to 20. Output:
Last updated