Wednesday, November 23, 2011

JAVA Programming : Do While Loop

JAVA Do While Loop


Do Loop is very similar to the while loop. The only difference between while and do while loop is that the while loop first checks the condition and executes the body of while loop only if the conditions results as true but in while loop the condition is evaluated after the loops body is executed once, so even if the condition is false at the first time the body of loop will be executed at least once.


  do{
     //set of statement
  while(condition);



Example of Do While loop:- The examples below will explain the working of do while loop.

In the examples below the while loop and do while will work exactly same i.e. will give the same output.

public class DoWhileLoop {
  public static void main(String[] args) {
  int i=1;
    do {
      System.out.println("enter into loop");
      i++;
    while (i<=10);
  }
}

public class DoWhileLoop {
  public static void main(String[] args) {
    int i = 1;
    while (i <= 10) {
      System.out.println("enter into loop");
      i++;
    }
  }
}

In the examples below the while loop and do while will not give the same output. 

public class DoWhileLoop {
  public static void main(String[] args) {
  int i=11;
    do {
      System.out.println("enter into loop");
      i++;
    while (i<=10);
  }
}

public class DoWhileLoop {
  public static void main(String[] args) {
    int i = 11;
    while (i <= 10) {
      System.out.println("enter into loop");
      i++;
    }
  }
}



In these examples the condition will be false at the first time so the body of while loop will never get processed but the body of do while will be processed once.

No comments:

Post a Comment