Java Loops

loops in java

A Java Loops statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages.

There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.


for Loops:

Another loop structure is the for loop. A for loop allows you to efficiently write a loop that needs to execute a specific number of times.

Example:

                    for(int x = 1; x <=5; x++) {
  System.out.println(x);
}
/* Outputs
1
2
3
4
5
*/

A for loop is best when the starting and ending numbers are known.


While Loops:

A loop statement allows to repeatedly execute a statement or group of statements.

A while loop statement repeatedly executes a target statement as long as a given condition is true.

Example :

                     int x = 3;
while(x > 0) {
   System.out.println(x);
   x–;
}
/*
Outputs
  3
  2
  1
*/

The while loops check for the condition x > 0. If it evaluates to true, it executes the statements within its body. Then it checks for the statement again and repeats.


do…while Loops:

A do…while loop is similar to a while loop, except that a do…while loop is guaranteed to execute at least one time.

Example :

                    int x = 1;
do {
  System.out.println(x);
  x++;
} while(x < 5);
/*
1
2
3
4
*/

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

Even with a false condition, the code will run once.


Java Loop Control Statements:

The break and continue statements change the loop’s execution flow.

The break statement terminates the loop and transfers execution to the statement immediately following the loop.

Example :

                    int x = 1;
while(x > 0) {
 System.out.println(x);
  if(x == 4) {
    break;
  }
  x++;
}
/* Outputs
1
2
3
4
*/

The continue statement causes the loop to skip the remainder of its body and then immediately retest its condition prior to reiterating. In other words, it makes the loop skip to its next iteration.

Example :

                     for(int x=10; x<=40; x=x+10) {
  if(x == 30) {
    continue;
  }
  System.out.println(x);
}
/* Outputs
  10
  20
  40
*/

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *