while loop




A while loop is a control structure that allows you to repeat a series of instructions over and over again. The while loop is a pre-test loop, since the boolean expression is evaluated before the loop body (i.e. the loop may be skipped). Loops are especially useful to traverse (travel across) an array or an ArrayList (or similar data structure).

Example:


// The following code prints out 0 1 2 3 4 done
// Here are the steps executed: 
// Step 1: int i=0;  creates a variable called i 
//                          and sets the value to 0
// Step 2: i<5 is evaluated and 
//                     if true, the 
//                       instructions inside the block { } 
//                       are executed
//                     if false, exit (terminate) the loop, 
//                        and continue with the 
//                        next instruction after the loop body
// Step 3: Execute the instructions in the body of the loop
//             System.out.print(i+" ");
//             i++;
// Step 4: Go to step 2.

 

int i=0;
while (i<5)
{
    System.out.print(i+" ");
	i++;
}
System.out.print("done");	
	

// note that 2 instructions are executed each time through the loop
// the braces { } are used to block off the body of the loop


More Examples:

// prints HelloHelloHellodone int i=0; while(i<3) { System.out.print("Hello"); i++; } System.out.print("done");
// prints HelloHelloHellodone int i=1; while(i<=3) { System.out.print("Hello"); i++; } System.out.print("done");
// prints HelloByeHelloByeHelloByedone int i=1; while(i<=3) { System.out.print("Hello"); System.out.print("Bye"); i++; } System.out.print("done");
// prints Hello Bye Hello Bye Hello Bye done int i=1; while(i<=3) { System.out.println("Hello"); System.out.println("Bye"); i++; } System.out.print("done");
// prints HelloBye HelloBye HelloBye int i=1; while(i<=3) { System.out.print("Hello"); System.out.println("Bye"); i++; }
// prints 1 10 2 20 3 30 int i=1; while(i<=3) { System.out.println(i + " " + i*10); i++; }