Home Java Introduction Decisions Loops Classes Access Inheritance Inner Classes Arrays Exceptions Strings Generics Container Input/Output MultiThreading jdk8 Versions Books

Loops


Contents



Loops allow a block of code to be executed repeatedly. We have different kinds of loops in java with additional keywords such as "break", "continue" to control the flow of execution.

while

We use loops to repeat a statement or group of statements. There are 3 types of loops in C++ "While" , "do while" and the "for" loop. The syntax of the while loop is:
   while ( boolean expression )
        statements
The while loop will test the boolean expression and if true will proceed to execute the statement or a group of statements. Control will then jump back to the boolean expression and it will be evaluated and if true the same sequence of actions is repeated.

File: while1.java
import java.util.* ;

public class while1
{
   public static void main( String args[] )
   {
     int x1=0, number=0   ;

    System.out.println( "Enter a value between 1 and 10" ) ;
    Scanner scanner = new Scanner(System.in);
    x1  =  scanner.nextInt() ;
       while (number < x1 )
        {
                 System.out.println( "Hello" ) ;
                 number++;
        }
   } //public static void main( String args[] )


}
C:\WebSite\Learn\2\Java\loops>java while1
Enter a value between 1 and 10
3
Hello
Hello
Hello
In the above we request a number from the user and the loop runs that many number of times executing "cout" every time it does so.
We need to be careful that the condition fails at some point:


File: while2.java
import java.util.* ;

public class while2
{
   public static void main( String args[] )
   {
     int x1=0, number=0   ;

    System.out.println( "Enter a value between 1 and 10" ) ;
    Scanner scanner = new Scanner(System.in);
    x1  =  scanner.nextInt() ;
       while (number < x1 )
        {
                 System.out.println( "Hello" ) ;
                 //number++;
        }
   } //public static void main( String args[] )


}


File: while3.java
import java.util.* ;

public class while3
{
   public static void main( String args[] )
   {
     int x1=0, number=0   ;

    System.out.println( "Enter a value between 1 and 10" ) ;
    Scanner scanner = new Scanner(System.in);
    x1  =  scanner.nextInt() ;
       while (number < x1 ) ;
        {
                 System.out.println( "Hello" ) ;
                 number++;
        }
   } //public static void main( String args[] )


}
What does the above program do when run ?

File: while4.java
import java.util.* ;

public class while4
{
   public static void main( String args[] )
   {
     int x1=0, number=0   ;
     final int UPPER = 10 ;
     final int LOWER = 1 ;
    System.out.println( "Enter a value between 1 and 10" ) ;
    Scanner scanner = new Scanner(System.in);
    number  =  scanner.nextInt() ;

     while (number < LOWER || number > UPPER)
       {
         System.out.println(  "ERROR: Enter a value in the range 1-100: " ) ;
         number  =  scanner.nextInt() ;
       }
     System.out.println(  "The number entered was:" + number )  ;

   } //public static void main( String args[] )


}
C:\WebSite\Learn\2\Java\loops>java while4
Enter a value between 1 and 10
34
ERROR: Enter a value in the range 1-100:
4
The number entered was: 4
We can use loops for validation of an input number as shown in the above program.

Do While Loops

The do while loop is similar to the while loop except it executes the statement first ( at least once ) and then checks the condition.
   do

    statement ;

  while ( expression );
If the expression is false then we exit.

File: do1.java
import java.util.* ;

public class do1
{
   public static void main( String args[] )
   {

     int number = 0  ;
     Scanner scanner = new Scanner(System.in);

     do
     {
           System.out.println( "Enter a value in the range 1-10: " ) ;
           number = scanner.nextInt() ;
     }  while (number < 1 || number > 10) ;
    System.out.println(  "The number entered was:" + number )  ;


   } //public static void main( String args[] )


}

for

The for loop has the following syntax:
for ( initialization; test; update )

    statement;
The initialization happens first and only once. Then the test condition is tested and if true then the statement is executed and then the update statement happens. After that the test condition is evaluated and if true the whole sequence repeats. The for loop is useful when we want to iterate based on integer values.

File: for1.java
import java.util.* ;

public class for1
{
   public static void main( String args[] )
   {

     int number = 0  ;
     System.out.println( "Enter a value in the range 1-10: " ) ;
     Scanner scanner = new Scanner(System.in);
     number = scanner.nextInt() ;
     for( int i1=0 ; i1 < number ; i1++ )
     {
         System.out.println(  "Hello" )   ;
     }


   } //public static void main( String args[] )


}
Enter a value in the range 1-10:
3
Hello
Hello
Hello
As usual there are many ways of coding to accomplish the same logic in programming.

File: for2.java
import java.util.* ;

public class for2
{
   public static void main( String args[] )
   {

     int number = 0  ;
     System.out.println( "Enter a value in the range 1-10: " ) ;
     Scanner scanner = new Scanner(System.in);
     number = scanner.nextInt() ;
     int i1=0 ;
     for(  ; i1 < number ; i1++ )
     {
         System.out.println( "Hello" )   ;
     }


   } //public static void main( String args[] )


}
In the above we have left the initialization part of the for statement blank. In fact all the 3 parts can be blank. Notice the variable "number" is not defined in the for loop but outside it.

File: for3.java
import java.util.* ;

public class for3
{
   public static void main( String args[] )
   {

     for(  ;  ;  )
     {
         System.out.println( "Hello" )   ;
     }


   } //public static void main( String args[] )


}
The above is an example of a for loop with all 3 sections as blank leading to an infinte loop. We can use Ctrl-C to come out of the loop.

Scope

It is possible to use 2 variables with the same name in a function as long as the variables are in different scope. In a for loop a variable can declare a variable in the initialization part. It's scope is valid to what's ever in the for loop block.
We cannot declare another variable of the same name in the body of the for loop.

File: for4.java
import java.util.* ;

public class for4
{
   public static void main( String args[] )
   {

      for( int i1=0 ; i1 < 10 ; i1++ ) //A
        {
             for(int i1=1 ; i1<5 ;   i1++ )          //B
             {
                 System.out.println(  "i1:" + i1 ) ;
             }   //C
       }    //D


   } //public static void main( String args[] )


}


File: for5.java
import java.util.* ;

public class for5
{
   public static void main( String args[] )
   {

      for( int i1=0 ; i1 < 10 ; i1++ ) //A
        {
             for(i1=1 ; i1<5 ;   i1++ )          //B
             {
                 System.out.println(  "i1:" + i1 ) ;
             }   //C
       }    //D


   } //public static void main( String args[] )


}
Now we are going to remove the declaration of the inner i1.

The outer loop goes from 0 to 9 as before. Now let's see what
happens when i1 is 0 . The nested for loop starts and
initializes i1 with 1 and loops from 1 to 4 and comes
out when i1 is is 5 . Now the update statement

of the outer for loop is executed and i1 is 6 . Now we
come to the test condition of the outer for loop:

i1 < 10

and since 6 is less than 10 we enter the inner for loop
where i1 is again reset to 1 . We can see that the program
will keep running forever and print 1 to 4 and
repeat the sequence.

Fibonacci Sequence

The Fibonacci sequence starts with 2 numbers of 1 and 1. The
3rd number is computed by summing the 1st and 2nd number to
give us the number 2 . To get the nth number we simply add the
previous 2 numbers .

First few numbers of the Fibonacci sequence .

1 1 2 3 5 8 13 21  34

The below program uses loops to print the Fibonacci sequence .


File: fib1.java
import java.util.* ;

public class fib1
{
   public static void main( String args[] )
   {
    int x1=1, x2=1 ;
    int temp ;
    for( int i1=0 ; i1<10 ; i1++ )
    {
        System.out.print( x1 + x2 )  ;
        System.out.print( " " ) ;
        temp = x1 + x2 ;
        x1 = x2 ;
        x2 = temp ;
    }
    System.out.println( " " ) ;


   } //public static void main( String args[] )


}
C:\WebSite\Learn\2\Java\loops>java fib1
2 3 5 8 13 21 34 55 89 144

break and continue

We have 2 keywords "break" and continue" that apply to only loops. The "break" breaks out of the loop and control falls to outside the loop.

File: br1.java
import java.util.* ;

public class br1
{
   public static void main( String args[] )
   {
        for( int i1=0  ; i1<10   ; i1++  )
        {
            if( i1 == 3 )
              break ;
            System.out.println(  i1 )   ;
        }


   } //public static void main( String args[] )


}
C:\WebSite\Learn\2\Java\loops>java br1
0
1
2
The "continue" keyword skips the rest of the body in the for loop and continues as if the body was executed to the next place in the code.

File: br2.java
import java.util.* ;

public class br2
{
   public static void main( String args[] )
   {
        for( int i1=0  ; i1<5   ; i1++  )
        {
            if( i1 == 3 )
              continue ;
            System.out.println(  i1 )   ;
        }


   } //public static void main( String args[] )


}
C:\WebSite\Learn\2\Java\loops>java br2
0
1
2
4
The variable i1 is getting incremented and will attain the value of 3 and then the continue is encountered and the cout will be skipped but the update statement i1++ will be executed and control moves as before.

label

The label is used in loops and is used with either break or continue.

File: label1.java
import java.util.* ;

public class label1
{
   public static void main( String args[] )
   {
    System.out.println( "Case 1: continue in outer loop." ) ;
    String text = "" ;
    loop1: for (int j1 = 1; j1 < 5; j1++)
    {
      loop2: for (int i1 = 1; i1 < 5; i1++)
      {
        if (i1 == 3)
        {
          //comes out inner for and continues in outer for
          continue loop1;
        }
        text += i1 ;
       }
    }


    System.out.println( "text: " + text ) ;

         //Same as
         text = "" ;
         for (int j1 = 1; j1 < 5; j1++)
         {
           for (int i1 = 1; i1 < 5; i1++)
           {
            if (i1 == 3)
             {
               i1 = 10  ; continue ;
             }
            text += i1 ;
           }
        }
        System.out.println( "text: " + text ) ;
    //----------------------
    // Case 2
    System.out.println( "Case 2: continue in inner loop." ) ;
    text = "" ;
    loop1: for (int j1 = 1; j1 < 5; j1++)
    {
      loop2: for (int i1 = 1; i1 < 5; i1++)
      {
        if (i1 == 3)
        {
          //continues in inner for
          continue loop2;
        }
        text += i1 ;
       }
    }


    System.out.println( "text: " + text ) ;

         //Same as
         text = "" ;
         for (int j1 = 1; j1 < 5; j1++)
         {
           for (int i1 = 1; i1 < 5; i1++)
           {
            if (i1 == 3)
             {
                continue ;
             }
            text += i1 ;
           }
        }
        System.out.println( "text: " + text ) ;

    //----------------------
    // Case 3
    System.out.println( "Case 3: break out of outer loop." ) ;



    text = "" ;
    loop1: for (int j = 1; j < 5; j++)
    {
      loop2: for (int i = 1; i < 5; i++)
      {
        //Breaks out of the outer loop
        if (i == 3) { break loop1; }
        text += i;
       }
    }
    System.out.println( "text: " + text ) ;

    text = "" ; //same as
    loop1: for (int j = 1; j < 5; j++)
    {
      loop2: for (int i = 1; i < 5; i++)
      {
        //Breaks out of the outer loop
        if (i == 3) { j =10 ; break ; }
        text += i;
       }
    }
    System.out.println( "text: " + text ) ;

    //----------------------
    // Case 4
    System.out.println( "Case 4: break out of inner loop." ) ;



    text = "" ;
    loop1: for (int j = 1; j < 5; j++)
    {
      loop2: for (int i = 1; i < 5; i++)
      {
        //Breaks out of the inner loop
        if (i == 3) { break loop2; }
        text += i;
       }
    }
    System.out.println( "text: " + text ) ;

    text = "" ; //same as
    loop1: for (int j = 1; j < 5; j++)
    {
      loop2: for (int i = 1; i < 5; i++)
      {
        //Breaks out of the inner loop
        if (i == 3) {  break ; }
        text += i;
       }
    }
    System.out.println( "text: " + text ) ;

    //----------------------
    // Case 5
    System.out.println( "Case 5 Using while: continue in outer loop." ) ;


    text ="" ;
    int j1=1 ;
    loop1: while( j1 < 5 )
    {
      int i1=1 ;
      loop2: while( i1 < 5 )
      {

        if (i1 == 3)
        {
          //comes out inner for and continues in outer for
          j1++ ; //necessary else infinite loop
          continue loop1;
        }
        text += i1 ;
        i1++ ;
      } //while
       j1++ ;
    } //while
    System.out.println(  text ) ;


   } //public static void main( String args[] )


}

Exercises:
1) Write an input validation loop that asks the user to enter 'Y','y', 'N' or 'n' .

File: ex1.java
import java.util.* ;

public class ex1
{
   public static void main( String args[] )
   {

     char ch1 = ' ' ;
     System.out.println( "Enter a single character: " ) ;
     Scanner scanner = new Scanner(System.in);
     ch1  =  scanner.next().charAt(0) ;
      //user msut enter
      //'Y','y', 'N' or 'n'
      //Hint use the && operator
     while (
               )
       {
         System.out.println(  "Enter a single character: " ) ;
         ch1  =  scanner.next().charAt(0) ;
       }
     System.out.println(  "The character entered was:" + ch1 )  ;

   } //public static void main( String args[] )


}
2)What does the below print ?

File: ex2.java
import java.util.* ;

public class ex2
{
   public static void main( String args[] )
   {

      int count = 0, number = 0, limit = 4;
         do
         {
            number += 2;
            count++;
         } while (count < limit);

         System.out.println( "number:" + number +
         " count:" + count ) ;

   } //public static void main( String args[] )


}
3)What does the below print ?

File: ex3.java
import java.util.* ;

public class ex3
{
   public static void main( String args[] )
   {

           {
              int   x = 2;
              int   y = x++;
              System.out.println( x << y );
           }
           {
             int  x = 2 ;
             int  y = ++x ;
             System.out.println( x << y  ) ;
           }
           {
               int x = 2 ;
               int y = 4 ;
                System.out.println( x++ << --y    ) ;
           }
           {
             int  x = 2  ;
             int  y = 2 * x++  ;
             System.out.println( x << y   ) ;
           }
           {
              int  x = 99;
              if (x++ < 100)
                System.out.println( "It is true!\n"  ) ;
              else
                System.out.println( "It is false!\n"   ) ;
            }
            {
               int  x = 0 ;
               if ( ++x != 0 )
                   System.out.println( "It is true!\n"  ) ;
               else
                   System.out.println( "It is false!\n"  ) ;

            }

   } //public static void main( String args[] )


}
4)What does the below print ?

File: ex4.java
import java.util.* ;

public class ex4
{
   public static void main( String args[] )
   {
      for( int j1=0  ; j1< 5   ; j1++  )
             {
                   if ( j1 == 1 )
                       break ;
                   for( int i1=0  ; i1< 5   ; i1++  )
                    {
                         if( i1 == 3 )
                            break ;
                         System.out.println(  i1 )  ;
                     }
             }
   } //public static void main( String args[] )


}
5)What does the below print ?

File: ex5.java
import java.util.* ;

public class ex5
{
   public static void main( String args[] )
   {
      for( int j1=0  ; j1< 5   ; j1++  )
             {
                   if ( j1 == 1 )
                       break ;
                   for( int i1=0  ; i1< 5   ; i1++  )
                    {
                         if( i1 == 3 )
                            break ;
                         System.out.println(  i1 )  ;
                     }
             }
   } //public static void main( String args[] )


}
6)What does the below print ?

File: ex6.java
import java.util.* ;

public class ex6
{
   public static void main( String args[] )
   {
        for( int j1=0  ; j1< 5   ; j1++  )
         {
                    if ( j1 > 1 )
                       continue ;
                    for( int i1=0  ; i1< j1   ; i1++  )
                     {
                          if( i1 == 3 )
                              break ;
                          System.out.println( i1 )  ;
                      }
         }
   } //public static void main( String args[] )


}
7)What does the below print ?

File: ex7.java
import java.util.* ;

public class ex7
{
   public static void main( String args[] )
   {
      for( int j1=0  ; j1< 5   ; j1++  )
      {
         for( int i1=0  ; i1< j1   ; i1++  )
            {
                    if( i1 == 1 )
                      break ;
                    System.out.println( i1 )  ;
            }
      }

  } //public static void main( String args[] )


}














1)
File: soln1.java
2)