Thursday, 5 May 2011

While loop definition

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement.
The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed. This repeats until the condition becomes false. Because while loops check the condition before the block is executed, the control structure is often also known as a pre-test loop. Compare with the do while loop, which tests the condition after the loop has executed.

Definition from: http://download.oracle.com/javase/tutorial/java/nutsandbolts/while.html

Visualisation of how a while loop works:



A code example of a while loop in Java/Processing:

int counter = 5; //The number of times the loop will execute
while (counter > 1) //the boolean condition, must be true for the while loop to execute
{    
   System.out.print(counter + " "); //this code and the next line are repeated until the boolean condition becomes false
   counter--;
}
System.out.print("end"); //proving that the loop does finish
 
 
Will give the following output as it loops around a prints out the numbers: 5 4 3 2 1 end

No comments:

Post a Comment