Looping statements in java

What is Looping statement?

 

In a big program one may need to repeat things hundreds of times or, most often get known how many times things are to be repeated only during the program run. Let's compact the code using for loop.

 

Java has very flexible three looping mechanisms. You can use one of the following three loops:

  • while loop

  • do…while loop

  • for loop

 

The While Loop:

 

Syntax:

A while loop is a control structure that allows you to repeat a task a certain number of times.

When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.

Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example:

Output:

The Do…While loop:

Syntax:

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.

If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.


 

Example:

Output:

The For Loop:

 

Syntax:

Here is the flow of control in a for loop:

  • The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables.

  • Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.

  • After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.

 

Example:

Output:

Manikandan is Founder and author of codenread. Tech Blogger by Passion | Computer Science Engineer by Qualification