print
Advertisment
Advertisment

Do while

In the do while loop the first statement is executed and later the condition is checked if the condition is true or false then there is no effect on the do part of this loop because this condition is checked at the end and Executes the first statement. Hence it is known as an exit control loop, this loop must run at least once.

Syntax


  do{
     //code to be executed
     //increment-decrement
  }while(condition);
  

Example of do while loop in java

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

Output :


 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
Advertisment

Nested Do while loop in java

In Java programming language, one do-while loop inside another do-while loop is known as a nested do-while loop. In do while the first statement is executed, then after that the condition is tested. How to work Nested do-while loop. initially, the initialization statement is executed only once, and statements(do part) execute only one. Then, the flow of control evaluates the test expression. Then, when the test expression is false, the loop exit from the inner loop, and the flow of control comes to the outer loop.

Syntax


  	do{
    		do{

      	}while(condition);

  	}while(condition);

Nested while loop in java

class DoWhileLoopProgram{
 public static void main(String args[]){
    int i = 1;
    int j = 1;
    do{
       do{
          System.out.println("This is inner do while loop example.");
          j++;
       }while(j<=3);
       System.out.println("This is outer do while loop example.");
       i++;
    }while (i<=2);
 }    
}

Output :


	This is inner do while loop example.
	This is inner do while loop example.
	This is inner do while loop example.
	This is outer do while loop example.
	This is inner do while loop example.
	This is outer do while loop example.

Advantage of loops in java

  • The complexity and length of the code are less. As you know, that looping is used to execute some statements multiple times. If the same thing is done with the help of other statements, then the length of the code will increase.
  • The for loop requires less memory space. Loops require less memory space than other Java control structures or statements.
  • Execution happens fast. Because looping reduces the length of the program and memory consumption, it becomes easier for the Java compiler to compile and run the program.
  • Loops control the flow of the program
  • it saves your time
Advertisment
Advertisment
arrow_upward