Java do...while Loop

The do...while loop is similar to while loop with one key difference. The body of do...while loop is executed for once before the test expression is checked.

How do...while loop works?

The body of do...while loop is executed once (before checking the test expression). Only then, the test expression is checked.

If the test expression is evaluated to true, codes inside the body of the loop are executed, and the test expression is evaluated again. This process goes on until the test expression is evaluated to false.

The Java do-while loop is used to iterate a part of the program several times. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop.

The Java do-while loop is executed at least once because condition is checked after loop body.

When the test expression is false, the do..while loop terminates.

Syntax:
do{ //code to be executed }while(condition);
flowchart of do while loop in java
Write a program in Java to display the n terms of even natural number
public class DoWhileExample { public static void main(String[] args) { int i=1; System.out.println("Displat "+10+" even natural numbers:"); do { if(i%2==0) { System.out.println(i); } i++; }while(i<=10); } }


Output:
Displat 10 even natural numbers: 2 4 6 8 10
import java.util.Scanner; public class DoWhileExample { public static void main(String[] args) { int i=1,n; Scanner p=new Scanner(System.in); System.out.println("Enter any value:"); n=p.nextInt(); System.out.println("Displat "+n+" even natural numbers:"); do { if(i%2==0) { System.out.println(i); } i++; }while(i<=n); } }


Output:
Enter any value: 30 Displat 30 even natural numbers: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
write a java program to calculate factorial of a number in java
import java.util.Scanner; public class DoWhileExample { public static void main(String[] args) { int n,i=1,fact=1; Scanner p=new Scanner(System.in); do { System.out.println("Enter n value:"); n=p.nextInt(); do { fact=fact*i; i++; }while(i<=n); System.out.println("Factorial of given number:"+fact); fact=1; }while(n!=0); } }


Output:
Enter n value: 5 Factorial of given number:120 Enter n value:
Java Infinitive do-while Loop

If you pass true in the do-while loop, it will be infinitive do-while loop.

If the test expression never evaluates to false, the body of while and do..while loop is executed infinite number of times (at least in theory)

Syntax:
do { //code to be executed }while(true);
public class DoWhileExampleIn { public static void main(String[] args) { do { System.out.println("infinitive do while loop"); }while(true); } }


Output:
infinitive do while loop infinitive do while loop infinitive do while loop ctrl+c



Instagram