Syntax of do while loop
do {
// code block to execute
}while ( condition)
condition : Check the logic and it should return true or false.
int i=0;
do {
i=i+1;
System.out.println(i);
}while (i<5);
Output
1
2
3
4
5
In above code we are first incrementing the value of the variable by 1 and then printing the value of variable. So the output prints 1 to 5.
boolean my_condition=true;
do{
System.out.println(my_condition);
my_condition=false;
}while ( my_condition==true);
Output is
true
int i=0;
do {
i=i+1;
System.out.println(i);
}while (i >-5);
int i=0;
do {
i=i+1;
if(i==2) {
break;
}
System.out.println(i);
}while (i < 5);
Output is here
1
After printing 1 ( first iteration ), in second iteration i value will be equal to 2, so the break statement will be encountered and the execution will come out of the loop.
int i=0;
do {
i=i+1;
if(i==2) {
continue;
}
System.out.println(i);
}while (i < 5);
Output is here
1
3
4
5
Except printing 2 , all values from 1 to 5 will be printed. When i value became 2, the continue statement is encountered and execution returns to the starting of the loop without executing balance ( print ) command.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.