/* */ Click to Join Live Class with Shankar sir Call 9798158723

While Loop in Java


Java While Loop is used to execute a code block repeatedly in a loop based on a condition.A while loop is a control statement using which the programmer can give instructions to the computer to execute a set of statement repeatedly as long as specified condition is satisfied. Ones the specified condition is false control comes out of the loop.


Syntex :-

whilewhile(condition)
{
statement(s); //block of code
}

How while Loop Works in Java.

  • step 1:-
    The initialization statement is executed first
  • step 2:-
    Then, the test expression is evaluated. If the test expression is evaluated to false, then the while loop gets terminated and the control comes out of the while loop.
  • step 3:-
    if the test expression is evaluated to true,The statements defined inside the while loop will repeatedly execute until the given condition fails.
  • step 4:-
    After successful execution of statements inside the body of the while loop, the update expression is executed.
  • step 5:-
    Again the test expression is evaluated.


Q.) W.A.P to Print 1 to 5 no.using while loop ?
   

class Main {
  public static void main(String[] args) {

    // declare variables
    int i = 1, n = 5;

    // while loop from 1 to 5
    while(i <= n) {
      System.out.println(i);
      i++;
    }
  }
}
Output
1 2 3 4 5