book
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
3.3.1 while Loop<br />
The syntax of a while loop is<br />
while (boolean expression) {<br />
one or more statements;<br />
}<br />
The block of statements is repeatedly executed while the boolean expression evaluates to<br />
true. As an example, we can rewrite the OutputArray program of Section 2.5.6 and<br />
assign values to array elements intArray[0] and intArray[1] using a while loop.<br />
OutputArray<br />
1 public class OutputArray {<br />
2<br />
3 public static void main(String[] args) {<br />
4 int i=0;<br />
5 int intArray [];<br />
6<br />
7 intArray = new int [2];<br />
8 while (i < intArray.length) {<br />
9 intArray[i] = i + 1;<br />
10 i++;<br />
11 }<br />
12 System.out.println(''Values of intArray are " +<br />
13 intArray[0] + " and " + intArray[1]);<br />
14 }<br />
15 }<br />
3.3.2 do while Loop<br />
The syntax of a do while loop is<br />
do {<br />
one or more statements;<br />
} while (boolean expression) ;<br />
OutputArray<br />
Unlike a while loop, a do while loop is guaranteed to execute at least once. In the<br />
OutputArray example of the previous section, the while loop (lines 8–11) can be<br />
replaced by the following do while loop:<br />
do {<br />
intArray[i] = i + 1;<br />
i++;<br />
} while (i < intArray.length);