03 Flow Control, Loop
03 Flow Control, Loop
switch statements
To explain the three Java looping mechanisms
for
while
do while
evaluate to true.
For A or B, either A or B can be true and the expression will
evaluate to true.
AND OR
A false true A false true
B B
false false false false false true
true false true true true true
NOT
A
false true
true false
Because of the nature of the truth table for AND, if any of the
operands are false, the whole expression evaluates to false.
Sub expressions need not be evaluated
if (boolean-expression)
statement1;
else
statement2;
if (boolean-expression)
{
statement1;
statement2;
statement3;
}
else
{
statement4;
statement5;
statement6;
}
if (x == 1)
statement1;
else if (x == 2)
statement2;
else if (x == 3)
statement3;
else if (x == 4)
statement4;
[ ... ]
while (boolean-expression)
{
statement1;
[...]
}
The do-while loop is identical to the while loop except that the
test is evaluated at the end of the loop.
do
{
statement1;
[...]
} while (boolean-expression);
int x = 0; int x = 0;
while(x<10) while(x<10)
{ {
System.out.println(x++); System.out.println(++x);
} }
int x = 0;
do
{
System.out.println(x);
x = x+1;
} while(x<10);
endless loop
int x = 0;
while(x<10);
{
System.out.println(x++);
}
endless loop
int x = 0;
do
{
System.out.println(x);
} while(x<10);
The syntax of the for loop makes the 4 parts of the loop
explicit.
The test condition on the for loop is the same as the while
loop. The loop body is executed while the condition is true.
The initialization and increment portions of the for loop
are optional. However, the semicolons must be present.
If the test condition is omitted, the test is always true.
for loops are generally used when the number of times the
loop is to be executed is known.
Do not adjust the looping variable within the loop
while and do-while loops are used when the number of times
the loop is to be executed is not known.
The focus is "while" this condition is true.
int x = 0;
design.
Re-design and re-write is usually the best solution.