Showing posts with label Loop. Show all posts
Showing posts with label Loop. Show all posts

Wednesday, April 29, 2015

Java DO...WHILE loop



Flow control of do...while loop


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Example


public class HelloWorld{
public static void main(String []args){
int i = 5;
int k = 0;
do{
System.out.println(k+"\n");
k++;
}while(k<i)
}
}

Monday, April 27, 2015

Java WHILE loop


Flow of control in a WHILE loop:

  1. When executing, if the boolean_expression in while result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.
  2. Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example

public class HelloWorld{

     public static void main(String []args){
        int i = 5;
        int k = 0;
        while(k<=i){
            System.out.println(k+"\n");
            k++;
        }
     }
}

Java FOR Loop



Flow of control in a FOR loop:

  1. The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
  2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
  3. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
  4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

Example

public class HelloWorld{
     public static void main(String []args){
        int i = 5;
        for(int k=0;k<=i;k++){
            System.out.println(k+"\n");
        }
     }
}

Types of Java Loop



There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop.

Java has very flexible three looping mechanisms. You can use one of the following three loops:

  1. while Loop
  2. do...while Loop
  3. for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.