The for loop

The for loop is very popular with programmers as it combines the creation of counting variables and performing a test on a value all in one neat package. The general structure of the for loop is

for(Create counter variable; test counter; modify counter){
	Body of for loop
}

You can think of these three parts separated by the semi colon as initialise, test and modify.

In actual Java code this typically translates to

for(int i=0; i <3; i ++){
	//Do something in the body of the code
}

In this example the counter variable i was created within the body of the for loop with the statement

int i=0;

The test part simply matches against the number 3, in a real program you would probably testing against some other variable. The modify counter adds one to value of i on each loop around.

Last modified: Thursday, 24 July 2014, 2:54 PM