Skip to main content

Section 5.1 Definite Loop

You have already seen a couple of examples of iteration and looping in Java. So this section will just serve as a reference for the differences in syntax.
A definite loop, also known as a for loop, is a loop that is executed for a specific or definite number of times. In Python, the easiest way to write a definite loop is using the for loop structure in conjunction with the range function. Listing 5.1.3 shows the syntax for the range function.
Listing 5.1.1.
Listing 5.1.2 shows how the for loop is written in Java.
Listing 5.1.2.
Recall that the range function provides you with a wide variety of options for controlling the value of the loop variable as shown in Listing 5.1.3.
Listing 5.1.3.
range(stop)
range(start,stop)
range(start,stop,step)
The Java for loop is really analogous to the last option giving you explicit control over the starting, stopping, and stepping in the three clauses inside the parenthesis. Listing 5.1.4 shows how the Java for loop is written.
Listing 5.1.4.
for (start clause; stop clause; step clause) {
    statement1
    statement2
...
}
If you want to start at 100, stop at 0 and count backward by 5, Listing 5.1.5 shows how the Python for loop is written.
Listing 5.1.5.
Listing 5.1.6 shows how the for loop is written in Java.
Listing 5.1.6.
In Python, the for loop can also iterate over any sequence such as a list, a string, or a tuple. Java also provides a variation of its for loop that provides the same functionality in its so-called for each loop.
Listing 5.1.7 shows how the for loop can be used to iterate over a list in Python.
Listing 5.1.7.
Listing 5.1.8 shows how the for loop can be used to iterate over an ArrayList of integers in Java.
Listing 5.1.8.
Listing 5.1.8 stretches the imagination a bit, and in fact points out one area where Java’s primitive arrays are easier to use than an array list. Listing 5.1.9 shows how the for loop can be used to iterate over all elements in a primitive array in Java.
Listing 5.1.9.
Listing 5.1.9 shows how the for loop can be used to iterate over all elements in a string in Java.
Listing 5.1.10.

Checkpoint 5.1.11.

Rearrange the blocks to create a Java method that accepts an upper bound integer limit and calculates the sum of all even numbers from 2 up to and including limit.
You have attempted of activities on this page.