Java while loop

In while loop we iterate  a block of code in many times in this number of iteration is not fixed 


working of while loop:-➰

In while  loop condition is checked first if the condition is true then block of code inside while loop body will be executed 

if the condition is false  the loop  get the end

the program jumps to the next statement after while  loop


Syntax of while loop🍸

while(condition)
{

   //statement;

}


🤔💭 how to fix iteration in a while loop?


There was a problem we can’t fix no of iteration with the condition so how to do that?


 when using the while loop is that we need to use increment or decrement statement inside  while loop so that the loop variable

get a change on each iteration


Digram of While Loop:

while loop diagram java

Example of While Loop:-

class WhileLoopExample {
    public static void main(String args[]){
         int i=10;
         while(i>1){
              System.out.println(i);
              i--;
         }
    }
}
10
9
8
7
6
5
4
3
2

Infinite while Loop

beware !!
if we create a test expression which never false then while loop never terminates it goes on. so careful

Example

class WhileLoopExample2 {
    public static void main(String args[]){
         int i=10;
         while(i>1)
         {
             System.out.println(i);
              i++;
         }
    }
}

Java do…while Loop

do While loop is similar to while loop
the main difference is that the body of the do-while loop is executed the one time before the test expression

Syntax of do while

do {
   // codes inside body of do while loop
} while (testExpression);

Working of while loop

In the first body of the do-while loop is executed before checking the test expression

then the condition is going to check after the execution of do-while loop body

if the test expression is false then it again checks the test expression it goes on until the test expression get false

if the test expression is false then loop gets terminated

while loop diagram java - flow chart

Example:

class DoWhileLoopExample {
    public static void main(String args[]){
         int i=10;
         do{
              System.out.println(i);
              i--;
         }while(i>1);
    }
}
10
9
8
7
6
5
4
3
2


SHARE THIS PAGE





Important Link