Java Reference
In-Depth Information
Chapter
7
Loops
OBJECTIVES
• Study two repetitive statements: the while-loop and the for-loop.
• Learn how to develop and understand loops
INTRODUCTION
During execution, it is often necessary to repeat a statement many times. For
example, consider printing the integers
0
..
n
. You cannot program this without the
ability to repeat a print statement an arbitrary number of times.
Java has three “repetitive” statements, called
loops
, that call for repeating a
statement. Here, we study two of them: the while-loop and the for-loop.
Knowing how loops work is
not
the same as being able to write them effi-
ciently and correctly. Loops are a wonderful source of bugs, and you can waste a
great deal of time writing incorrect loops and trying to fix them. We present a
methodology that will reduce the overall amount of time you spend writing loops.
7.1
The while-loop
7.1.1
Syntax and semantics of while-loops
Consider a sequence of statements to print the numbers
2
2
,
3
2
, and
4
2
:
Activity 7-1.1
covers the
same material
but with a dif-
ferent loop.
System.out.println(2 * 2);
System.out.println(3 * 3);
System.out.println(4 * 4);
This task uses three statements. To print
100
squares in this manner would require
100
statements. But because of the repetitive nature of this task, it can be written
in a shorter fashion using a Java statement called the
while-loop
. Here is a Java
segment that contains a while-loop to perform this task:
Search WWH ::
Custom Search