Wednesday, November 23, 2011

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:- 

No comments:

Post a Comment