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.

JAVA Programming : While Loop

JAVA While Loop


Loops in java are the control flow statements that are used to repeat a block of code multiple times according to a given condition.  There are three types of loops: For , Do , While. The while loop is very simple but very effective when we have to execute a block of code until a particular expression(condition) is true. The condition will evaluate into a boolean result.

Syntax of while loop:-


    while(condition){
      //set of statements    
    }


Example of while loop:- To understand the functionality of while loop lets see the example. While loop first checks the given condition, if the condition results into true then the statement written inside the while loop block will be executed and then the condition is checked again. This process goes until the given condition is false.

import java.util.Scanner;
public class While {
  public static void main(String[] args) {
    int i=1;
    System.out.println("Enter any number to print table");
    Scanner scan = new Scanner(System.in);
    int num = scan.nextInt();

    while (i<=10) {
      System.out.println(num+" * "+i+" = "+num*i);
      i++;
    }  
  }
}

Output of Program:-