The for loop
The statements in the for loop repeat continuously for a specific number of times.  The while  and  do-while  loops repeat until a certain condition is met.  The for loop repeats until a specific count is met.  Use a for loop when the number of repetitions is known, or can be supplied by the user.  The coding format is:

for(startExpression; testExpression; countExpression)
{
    block of code;
}

The startExpression is evaluated before the loop begins.  It is acceptable to declare and assign in the startExpression (such as int x = 1;).  Java evaluates the startExpression only once, at the beginning of the loop.

beware
 When the following code is written:

    for (int x= 1; x<=10; x++)
    {
             some code here;
    }

x is being declared inside the loop and will not be recognized as a variable for future use in the program outside of the loop.  If x is to be used beyond the scope of the loop, be sure to declare x prior to entering the loop.

 

The countExpression executes after each trip through the loop.  The count may increase/decrease by an increment of 1 or of some other value.  The testExpression evaluates to TRUE or FALSE.  While TRUE, the body of the loop repeats.  When the testExpression becomes FALSE, Java stops looping and the program continues with the statement immediately following the for loop in the body of the program.

Braces are not required if the body of the for loop consists of only ONE statement.  Please indent the body of the loop for readability.

beware Be aware that when a for loop terminates, the value stored in the computer's memory under the looping variable will be "beyond" the testExpression in the loop.  It must be sufficiently large (or small) to cause a false condition.

for(x = 0; x <= 15; x++)
    System.out.println("Patty");
When this loop
is finished, the value 16 is
stored in
x.

The following program fragment prints the numbers from 1 to 20.

for:
int ctr;
for(ctr=1;ctr<=20; ctr++)
{
  System.out.println(ctr);

 


Common Error: 
If you wish the body of a for loop to be executed, DO NOT put a semicolon after the for's parentheses.  Doing so will cause the for statement to execute only the counting portion of the loop, creating the illusion of a timing loop.  The body of the loop will never be executed.


Semicolons are required inside the parenthesis of the for loop.  The for loop is the only statement that requires such semicolon placement.


Infinite Loop: 
Within the parentheses of the for loop, the 3 expressions are optional. Consequently, an infinite loop can be created by including the semi-colons without any coding between them. But why would you want to!!!!

forglare

divider
Return to Unit Menu |  JavaBitsNotebook.com | MathBits.com | Terms of Use  | JavaMathBits.com