The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Looping Statements in Java

Loop control statements are used to execute a statement or a group of statements multiple times. Suppose you want to print a number 10 times. Instead of using 10 System.out.println( ) statements, we can simply loop over a single System.out.println( ) statement 10 times. Let's see the looping constructs supported by Java.

' for ' Loop
Consider the following code snippet :

for ( int i = 1; i <= 10; i++ ) {
      System.out.println ( " i = " + i );
}

i = 0; is the initialization statement.
i <= 10; is the condition statement.
i++; is the increment statement.

The initialization ( i = 0; ) statement is executed once.
Then, the condition ( i < 10; ) statement is checked. If it evaluates to True, body of the loop is executed. If it evaluates to False, loop is terminated and the statement after the loop body is executed.
After all the statements in loop body are executed, control jumps to the increment statement and the condition statement is evaluated again.
Every for loop follows this syntax :

for ( init; condition; increment / decrement ) {
      statement 1;
      statement 2;
              .
              .
      statement n;
}

for loop is known as entry controlled loop since the condition check is done at beginning of the loop. Following program illustrates the use of for loop :

/*
 * This program prints the multiplication table of a number
 * using for loop
 */
public class MulTableForLoop {
    public static void main(String args[]) {
      int num = 7;
      // following loop executes 10 times
      for ( int i = 1; i <= 10; i++ ) {
          int value = num * i;
          System.out.println(num + " * " + i + " = " + value);
      }
    }
}


' while ' loop
Syntax of the while loop is :

while ( condition ) {
      statement 1;
      statement 2;
              .
              .
      statement n;
}

Initialization statement is declared just before the while statement.
Increment / Decrement statement is present inside the body of while loop.

while loop is also known as entry controlled loop. It is possible that the body of the while loop is not executed even once. Following program illustrates the use of while loop :

/*
 * This program prints the multiplication table of a number
 * using while loop
 */
public class MulTableWhileLoop {
    public static void main(String args[]) {
      int num = 11;
      int i = 1; // loop variable initialization
      while ( i <= 10 ) { // condition
          int value = num * i;
          System.out.println(num + " * " + i + " = " + value);
          i++;
      }
    }
}


' do ... while ' loop
Syntax of the do ... while while loop is :

do {
      statement 1;
      statement 2;
              .
              .
      statement n;
} while ( condition );

' do ... while ' loop is known as exit controlled loop since the condition check is done at the end of the loop. Following program illustrates the use of do ... while loop :

/*
 * This program prints the multiplication table of a number
 * using while loop
 */
public class MulTableDoWhileLoop {
    public static void main(String args[]) {
      int num = 9;
      int i = 1; // loop variable initialization
      do {
         int value = num * i;
          System.out.println(num + " * " + i + " = " + value);
          i++;
      } while ( i <= 10 ); // condition check for exit
    }
}


Nested Loops
We can use a loop inside the body of another loop. This is known as nesting of loops. Following program illustrates the use of nested loops:

/*
 * This program prints the multiplication tables of multiple
 * consecutive numbers using loop nesting
 */
public class MulTablesNesting {
    public static void main(String args[]) {
      int curr_no = 5;   // start building mul table from 5
      int num_tables = 3; // No. of tables to build is 3 ( 5 - 7 )
      for ( int i = 0; i < num_tables; i++ ) { // outer loop builds three tables
         for ( int j = 1; j <= 5; j++ ) { //inner loop builds table for each no
            int value = curr_no * j;
            System.out.println(curr_no + " * " + j + " = " + value);
         }
         curr_no++; // increment curr_no for next table
         System.out.println(); //add an extra newline char between two tables
      }
    }
}


' break ' and ' continue ' statement
' break ' statement is used to terminate the loop immediately without going for further conditional check. In case of nested loop, the innermost loop is terminated and the execution starts from the next line of the program after the inner loop. We have already seen that break is used to break out of switch case construct.
' continue ' statement doesn't terminate the loop but goes to the beginning of the loop for next iteration skipping rest of the loop body.
Following program illustrates the use of break statement :

/*
 * Program to demonstrate the behaviour of break statement
 */
public class BreakDemo {
    public static void main(String args[]) {
      for ( int i = 0; i < 10; i++ ) {
         if ( i == 7 ) {
            // program terminates here
            break;
         }
         System.out.print( i + " ");
      }
    }
}

The for loop is supposed to have 10 iterations printing 0 1 2 3 4 5 6 7 8 9 but the break statement causes termination of the loop once i becomes 7. So the output will be 0 1 2 3 4 5 6 .

Following program illustrates the use of continue statement :

/*
 * Program to demonstrate the behaviour of continue statement
 * This program prints odd numbers only from 0 to 9
 */
public class ContinueDemo {
    public static void main(String args[]) {
      for ( int i = 0; i < 10; i++ ) {
         if ( i % 2 == 0 ) { // check for even number
            // 'i' is even, goto the beginning of the loop
            // skip the print statement
            continue;
         }
         System.out.print( i + " ");
      }
    }
}

Output of the above program is 1 3 5 7 9 . The print statement is skipped using the continue statement when we see an even number.

Back | Next