Do while loop in java with example

Previous Code:-
while loop

List Code:-
Java codes

Next Code:-
Nesting loop in java

Java Programs:-
List of Java Programs



Do While loop is another loop in java

Syntax:-

do
{
Body of the loop
}
while(condition);
Statement;

Note:-

# If body of loop is only one statement than braces ({}) are not needed.
# Body of the loop may have one or more statement.
# Semicolon is present after while.
# At least once body of loop is executed even condition is false.

Execution:-

In do while loop 1st body of the loop is executed than condition will check if condition is true than body of the loop will executed. After body of the loop is execute, the condition is again tested if condition is true than again body of loop is executed, this process is repeated until condition is true. When condition is false than statement next to while loop is executed.

Hence body is 1st executed before the condition check so body of loop is always executed at least once.

Example:-

Program to count n numbers

import java.util.Scanner;

class group{
public static void main(String angr[]){
Scanner num = new Scanner(System.in);
int n, i;
System.out.println("hey enter number");
n=num.nextInt();
i=0;
do
{

System.out.println(i);
i++;
}while(i<=n);
}
}

Program to display even number up to 20

class simple{
public static void main(String args[]){
int num = 0;
do
{
num = num + 2;
System.out.println(num);
}
while(num<=20);
}
}

Here 22 also displayed because condition is checked at bottom.

2 Comments

  1. no. it display 22 because you put equal sign at the bottom condition, try to erase that

    ReplyDelete

Add your comments here

Back to Top