Do-while loop

Do-while loop in Java

Syntax

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

Program

 
public class do_while
{
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

Explanation

  • 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.
  • do while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.
  • After the execution of the statements, and update of the variable value, the condition is checked for true or false value. If it is evaluated to true, next iteration of loop starts.
  • When the condition becomes false, the loop terminates which marks the end of its life cycle.
  • It is important to note that the do-while loop will execute its statements atleast once before any condition is checked, and therefore is an example of exit control loop.

Infinite do-while loop

Syntax

 
do{
//code to be executed
}while(true);

Program

 
public class infinite_dowhile
{
public static void main(String args[])
{
do
{
System.out.println("Infinite while loop");
}while(true);
}
}

Output

 
Infinite while loop
Infinite while loop
Infinite while loop
Infinite while loop
Infinite while loop
Infinite while loop

Explanation

  • If you pass true in the do-while loop, it will be infinitive do-while loop.
  • You have to press ctrl+c to stop this program otherwise it will run continuously.

Comments

Popular posts from this blog

System.Environment

System.Console

Datatype and keyword