In the last tutorial, we discussed while loop. In this tutorial we will discuss do-while loop in java. The Java programming language also provides a do-while statement
In java do-while loop is similar to while loop, the difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. That means the statements within the do block are always executed at least once.
Syntax:
do{
// code to be executed
}while(condition);
Working
First, the statements inside the loop execute and then the condition tested, if the condition returns true then the control gets transferred to the “do” else it jumps to the next statement after do-while.
// Java program to print number form 1 to 15
class Simple{
public static void main(String args[]){
int i = 1;
do{
System.out.println(i);
i++;
}while(i <= 15);
}
}
Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Java program to print number form 1 to 10
class Simple{
public static void main(String args[]){
int i = 1;
do{
System.out.println(i);
}while(i <= 15);
}
}
Output:
1
1
1
1
1
1
1
.
.
.
ctrl+c
Note: ctrl+c is used for stop the execution of this program and exit form the program.