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 is a loop that is executed a specific or definite number of times. In Python, the easiest way to write a definite loop is using the
for loop in conjunction with the range function. For example:
In Java, we would write this as:
Recall that the
range function provides you with a wide variety of options for controlling the value of the loop variable.
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. You can think of it this way:
for (start clause; stop clause; step clause) {
statement1
statement2
...
}
If you want to start at 100, stop at 0 and count backward by 5, the Python loop would be written as:
In Java, we would write this as:
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.
In Python, we can iterate over a list as follows:
In Java we can iterate over an
ArrayList of integers too. Note that this requires importing the ArrayList class.
This example 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. In fact, all primitive arrays can be used in a for each loop.
To iterate over the characters in a string in Java do the following:
You have attempted of activities on this page.
