Loops (For...next)

Most applications require the computer to perform repetitive tasks.
Java allows the use of For ...next , While and Do While loops.

The syntax of the For...next loop in Java is very similar to C++

for ( n = 1; n < 100; n++) will loop through any following block of code 100 times.

The loop starts out by initializing the integer variable n to equal 1.

It then executes the block of code once and returns to the loop statement.

The n++ arithmetic operator is then executed which increments n.

If n is less than 100 it will again execute the block of code.

This process repeats until the condition n < 100 is false.

 

Copy the following code into a text editor and
save it as forloop.java.

class forloop {

public static void main (String args[]){

int x;

for (x=0 ; x<20 ; x++)

System.out.println("x = " + x + " x squared = " + x*x);

}

}

Line 1 Designates that we are defining
a new class called forloop.

Line 3 declares x as an integer variable

Line 4 sets up the loop. It starts at x = 0
and will continue to execute
as long as x is less than 20.

Line 5 sends the values for
x and x squared
with the appropriate labels to the
system output device.

Notice how the string is concatenated
by using the + operator.

 

After compiling and running this program the output should be

x = 0  x squared = 0
x = 1  x squared = 1
x = 2  x squared = 4
x = 3  x squared = 9
x = 4  x squared = 16
x = 5  x squared = 25
x = 6  x squared = 36
x = 7  x squared = 49
x = 8  x squared = 64
x = 9  x squared = 81
x = 10  x squared = 100
x = 11  x squared = 121
x = 12  x squared = 144
x = 13  x squared = 169
x = 14  x squared = 196
x = 15  x squared = 225
x = 16  x squared = 256
x = 17  x squared = 289
x = 18  x squared = 324
x = 19  x squared = 361

Notice that x = 20 is not printed. The value of x actually does get to 20 but the loop exits at that point therefore it is never printed. The controlling decision x < 20 could be changed to x <= 20 if we wanted the loop to continue to that point.

Loops continued (While Loops)