Loops in Java: Nested While, Do-While, and For-Each Loop

Loops in Java - for, do, and while with break and continue

Java loops (iterative statements - while, do, and for) are used to repeat the execution of one or more statements a certain number of times. Java provides three looping statements (while, do, and for) to iterate a single or compound statement. Along with the iterative statements Java also provides break and continue statements to control the execution of a looping statement. Java's break and continue statements used in labeled and unlabeled forms discussed later in this tutorial.

Java while Loop

Java's while loop is an entry-controlled iterative statement. It has the following syntax in a Java program:

while (booleanExpression)
    Statement //single or a block enclosed in { and } 

Java's while loop keeps executing the booleanExpression and Statement repeatedly until the booleanExpression evaluates to false.

A while statement starts execution by evaluating booleanExpression, if it returns true then Statement is executed. This cycle is repeated until the booleanExpression returns false or a break is executed within from loop's body. The following program illustrates the use of while loop.

/* WhileLoopDemo.java */
//Demonstrates while statement
public class WhileLoopDemo
{
    public static void main(String[] args)
    {
        int fib = 0, step = 1;
 
        while (fib < 50)
        {
            System.out.print(fib + " ");
            fib = fib + step;
            step = fib - step;
        }
    }
}
 
OUTPUT
======
0 1 1 2 3 5 8 13 21 34

Above program prints fibonacci numbers from 0 to 50. After printing 34, the value of fib becomes 55 that is larger than 50, therefore in next iteration expression fib < 50 returns false and the execution of while stops here.

If the boolean expression in while statement's parentheses does not evaluate to false, the loop will be executed indefinitely and will never terminate.

Java do-while Loop

In Java's while statement you have seen that the booleanExpression is tested for truth before entering in the loop's body. On the contrary, in Java's do loop booleanExpression is tested for truth when exiting from the loop. If it returns false then control does not execute loop's body again else it will do.

So, on the basis of where booleanExpression is evaluated (while entering in loop's body or while exiting from loop's body) loops can be categorized as entry-controlled and exit-controlled. Java's do loop is an exit-controlled loop. From the above context, you can also conclude that the body of exit-controlled loop will be executed at least once even if the test condition returns false in first time.

Basic syntax of Java's do statement is as follows.

do
   Statement //single or a block enclosed in { and }
while (booleanExpression);

Note that there is a semicolon (;) after while (booleanExpression) in do syntax. Following program illustrates the use of do statement.

/* DoWhileLoopDemo.java */
//Demonstrates do-while statement
public class DoWhileLoopDemo
{
    public static void main(String[] args)
    {
        int fib = 0, step = 1, i = 1;
 
        System.out.println("Prints counting from 1 - 10");
        // demonstrates single statement version of do-while
        do
           System.out.print(i++ + " ");
        while(i <= 10);
 
        System.out.println(); // one blank line
        System.out.println("\nPrints fibonacci series up to 50");
        // demonstrates compound statement version of do-while
        do
        {
            System.out.print(fib + " ");
            fib = fib + step;
            step = fib - step;
        }while (fib < 50);
    }
}
 
OUTPUT
======
Prints counting from 1 - 10
1 2 3 4 5 6 7 8 9 10 
 
Prints fibonacci series up to 50
0 1 1 2 3 5 8 13 21 34 

If you look at above program you will observe that in second do loop we printed a fibonacci series up to 50 that we had also done via while loop in previous example. It shows that a task you perform by while can also be done by do. But, it may not true vice versa because do loop at least once gets executed, whereas while is not if the test condition is false initially.

Java for Loop

Java's for loop has two syntaxes. First is the basic for statement that you might have seen in C and C++ languages also. And, the second is enhanced for loop that is used to iterate through arrays, and iterable collections. However, you can iterate through arrays by using basic for loop also, but enhanced one makes it easier. We will see both variants of Java's for loop.

Java's Basic for Loop

Java's basic for loop inherits its syntax from C language. It has three sections in parentheses those are initialization, booleanExpression, and UpdateCounter. Here goes the syntax of basic for statement.

for (initialization; booleanExpression; UpdateCounter)
    Statement // single or a block enclosed in { and } 

In above syntax of basic for statement all three section in parentheses are optional, so some of them or all can be omitted. If a for has empty parentheses like for(;;), it is always true and results into indefinite run cycles. Let's see the following example where all sections of Java's basic for loop are demonstrated.

/* BasicForLoopDemo.java */
//Demonstrates basic for statement
public class BasicForLoopDemo
{
    public static void main(String[] args)
    {
        System.out.println("Prints counting from 1 - 10");
        for (int i = 1; i <= 10; i++)
        {
            System.out.print(i + " "); //prints counting from 1 - 10
        }
 
        System.out.println(); // print one blank line
        System.out.println("\nPrints fibonacci series up to 50");
        for(int fib = 0, step = 1; fib < 50; fib = fib + step, step = fib - step)
            System.out.print(fib + " "); //prints fibonacci numbers up to 50
 
        for (;;)
        {
            System.out.println("\n\nAll time true...");
            break;
        }
    }
}
 
OUTPUT
======
Prints counting from 1 - 10
1 2 3 4 5 6 7 8 9 10 
 
Prints fibonacci series up to 50
0 1 1 2 3 5 8 13 21 34 
 
All time true...

Above example code demonstrates three flavors of basic for statement. Very first is the typical one which you will see most of the time. The second one has more than one initializations, as well as more than one update variables. This is perfectly legal and acceptable to initialize, and update more than one variable in initialization and update sections. All operations should be comma separated. This also demonstrates a special use of comma operator. Third and last flavor of for loop can run into indefinite cycles, if break is removed from the loop.

Java's Enhanced for Loop or for-each Loop

Java's enhanced for loop was introduced in Java 5.0 to facilitate array and collection traversing. It is also referred as the for-each loop. By providing enhanced for statement Java folks simplified the code structure. Following is the syntax the enhanced for follows.

for (Type Identifier : Expression)
    Statement // single or a block enclosed in { and } 

The Expression should be either of type Iterable or an array. Otherwise, there will be a compile time error. The Identifier is a local variable of a suitable type for the set's contents. The following program illustrates the use of Java's enhanced for loop.

/* EnhancedForLoopDemo.java */
//Demonstrates enhanced for statement
public class EnhancedForLoopDemo
{
  public static void main(String[] args)
  {
    int[] arrOneD = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
    int[][] arrTwoD = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
 
    System.out.println("printing one dimensional array with basic for:");
    for(int i = 0; i <  arrOneD.length; i++)
      System.out.print(arrOneD[i] + " ");
 
    System.out.println(); //blank line	
    System.out.println("printing one dimensional array with enhanced for:");
    for(int i : arrOneD)
      System.out.print(i + " ");
 
    System.out.println(); //blank line
    System.out.println("\nprinting two dimensional array with basic for:");
    for (int i = 0; i < 3; i++)
    {
      for(int j = 0; j < 3; j++)
        System.out.print(arrTwoD[i][j] + " ");
      System.out.println();
    }
 
    System.out.println(); //blank line
    System.out.println("\nprinting two dimensional array with enhanced for:");
    for (int[] arr : arrTwoD)
    {
      for(int elm : arr)
        System.out.print(elm + " ");
      System.out.println();
    }
  }
}
 
OUTPUT
======
printing one dimensional array contents with basic for:
10 11 12 13 14 15 16 17 18 19 20 
 
printing one dimensional array contents with enhanced for:
10 11 12 13 14 15 16 17 18 19 20 
 
printing two dimensional array contents with basic for:
1 2 3 
4 5 6 
7 8 9
 
printing two dimensional array contents with enhanced for:
1 2 3 
4 5 6 
7 8 9

While printing contents of arrOneD by for-each loop the array arrOneD returns one int value at a time from the array until it reaches to the end. Whereas, in arrTwoD outer for loop returns a one-dimensional array that is stored in arr then in inner for loop array arr is dereferenced to get individual elements printed.

Loop Control Variable in for Loop

Note that sometimes a variable is only needed to control a for loop. If this is the case, it can be declared and initialized in the first portion of for loop where initialization of loop control variables takes place.

A very important point to note that if a variable is declared in initialization section of for loop, its scope is limited up to the body of for loop only. Attempting to use that variable outside the body of for will result into a compile time error.

Have a look at the following program to understand the functioning of initialization variable inside Java's for loop.

/* LoopControlVarDemo.java: demonstrates declaration and initialization
 * of loop control variable inside for loop.
 */
public class LoopControlVarDemo
{
    public static void main(String[] args)
    {
        for (int i = 1; i <= 10; i++)
        {
            System.out.print(i + " ");
        }
        System.out.println(i + " "); // Error, i is not visible out of for block
    }
}

In above piece of code class LoopControlVarDemo will not compile because variable i is being tried to access outside the for loop's block while i is only visible up to body of for statement.

Java break Statement

Java's break statement is mainly used to break the flow of execution. It has three uses in Java:

  1. to terminate the execution of a switch statement.
  2. to exit a loop.
  3. to use as goto.

Java's break statement can be labeled or unlabeled. An unlabeled break is used to terminate the execution of a switch or a loop, whereas the labeled break is used as goto statement.

Java's Unlabelled break Statement

Let us first look at Java's unlabeled break statement. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop.

It is important to note that when a break is used inside nested loops, it only exits from the loop in which it is executed. Here is a simple example:

// Using break to exit a loop.
class UnlabeledLoopBreak
{
    public static void main(String args[])
    {
        // break exiting from a single loop
        for(int i = 1; i <= 100; i++)
        {
            if(i * i == 121) break; // terminate loop if i is 11
            System.out.print(i + " ");
        }
        System.out.println("\nDone printing counting.");
        System.out.println(); // blank line
        // break exiting from nested loops
        for(int i = 1; i <= 10; i++)
        {
            for(int j = 1; j <= 10; j++)
            {
                if(j > i) break; // terminate loop if j is greater than i
                System.out.print(j + " ");
            }
            System.out.println();
        }
        System.out.println("\nDone printing pyramid.");
    }
}
 
OUTPUT
======
1 2 3 4 5 6 7 8 9 10
Done printing counting.
 
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
 
Done printing pyramid.

The first for loop in above program exits in two conditions either i is greater than 100 or product of i * i is equal to 121. Latter condition causes this for loop to terminate early by using break statement.

Second time while printing the number pyramid there are two nested for loops and the condition if(j > i) when becomes true control exits from the inner loop only.

Importantly note that unlabeled break cannot be used outside of a loop or a switch.

Java's Labeled break Statement

Java's labeled break statement fulfils the purpose of goto in some sense. Java has goto as a reserved word, but it is not used currently. Because goto statements are considered poor style of programming, they lower the spirit of structured programming. It has always been a topic of debate whether goto should be used in a program or not. A bigger fraternity of programmers says that unrestricted use of goto is error prone but an occasional use to get out of a loop is expedient. Java designers agreed to programmers' community and added a labeled break to support this programming style.

A labeled break marks a block of code and gets you out of that block when executed within from that block. The condition is that the break statement should be executed within from the same block and properly labeled.

The syntax of labeled break statement goes here:

break label;

Take a look at the following program where we have a named block breakIt, and we want to get out of this block if a particular condition occurs. In that case we will execute break breakIt; statement within from the named block breakIt. The following example program demonstrates the use of labeled break.

//Demonstrates labeled break
public class LabeledBreakDemo
{
  public static void main(String[] args)
  {
    breakIt:
    {
      for(int i = 1; i < 5; i++)
      {
        for(int j = 1; j < 5; j ++)
        {
          for(int k = 1; k < 5; k ++)
          {
            if (j == 3)
            {
              //gets out of breakIt block
              break breakIt; 
            }
            System.out.print(j + " ");
          }
          System.out.println();
        }
        System.out.println();
      }
    }
    System.out.println("Out of breakIt block");
  }
}
 
OUTPUT
======
1 1 1 1 
2 2 2 2 
Out of breakIt block

If you look at the body of inner most for statement in above program, you will see a break breakIt; statement controlled by if (j == 3). As soon as this condition returns true the statement break breakIt; will be executed and control will be moved out of the block breakIt.

Java continue Statement

Java's continue statement can only be placed in iterative (loop) statements (while, do, and for) to cause an early iteration. It means that during certain situations if you do not want to process complete body of the loop and wish to pass the control to the loop-continuation point then you can place a continue statement at that point.

The continue statement of Java can also be used with or without label. It has the following syntax in a Java program:

continue optional-label;

Java's continue statement without label transfers control to the immediate enclosing while, do, or for loop. Whereas, a continue statement with label transfers control to the labeled loop statement. The following program illustrates the use of both unlabeled, and labeled continue statements.

/* ContinueDemo.java */
//Demonstrates unlabeled, and labeled continue
public class ContinueDemo
{
  public static void main(String[] args)
  {
    // demonstrating unlabelled break
    System.out.println("Demonstration of unlabeled continue:");
    for (int i =1; i <= 50; i++)
    {
      if (i % 5 != 0) continue;
      System.out.format("%5d", i);
    }
 
    System.out.println("\n");
    System.out.println("Demonstration of labeled continue:");
    outer:
    for (int i =1; i <= 50; i++)
    {
      for(int j = 1; j <= 10; j++)
      {
        if (i % 5 != 0) continue outer;
        System.out.format("%5d", i*j);
      }
      System.out.println();
    }
  }
}
OUTPUT
======
Demonstration of unlabeled continue:
    5   10   15   20   25   30   35   40   45   50
 
Demonstration of labeled continue:
    5   10   15   20   25   30   35   40   45   50
   10   20   30   40   50   60   70   80   90  100
   15   30   45   60   75   90  105  120  135  150
   20   40   60   80  100  120  140  160  180  200
   25   50   75  100  125  150  175  200  225  250
   30   60   90  120  150  180  210  240  270  300
   35   70  105  140  175  210  245  280  315  350
   40   80  120  160  200  240  280  320  360  400
   45   90  135  180  225  270  315  360  405  450
   50  100  150  200  250  300  350  400  450  500

The labeled continue in above example takes program control to the label outer from where outer for loop starts. However, there are many easy ways to print vertical and horizontal tables from 5 to 50, we did this way to just demonstrate the use of labeled continue.

Last Word

In this tutorial we talked of Java's iterative (loop) statements such as while, do, and for. Java provides two variants of for loop those are basic for and enhanced for or for-each. Java's enhanced for loop is useful when we have to iterate through a list. To control loop execution Java provides break and continue statements. Both break and continue can be used with and without label.

Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

References




Get Free Tutorials by Email

About the Author

is the main author for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

Bees 'go online' in ManchesterPosted on Friday September 22, 2017

Rory visits a beekeeper in Manchester who is gluing wireless chips to his bees.

The long wait for a Persian iPhone keyboardPosted on Friday September 22, 2017

The new Apple's iOS has Persian keyboard. BBC Persian's Sam Farzaneh discusses why it is an important feature.

Uber London loses licence to operatePosted on Friday September 22, 2017

Ride-hailing app Uber is "not fit and proper" to operate in London, the transport regulator says.

Courtesy BBC News

AD BLOCKER DETECTED!

Advertisements help running this site for free.


To view the content please disable AdBlocker and refresh the page.

×