Iteration Statements

provides execution of one set of statements repeatedly until the termination condition satisfied.

for, while, do-while.

  • While

It is the foundation loop where it will execute the set of statements while the condition is true means when the condition is false it will terminates the condition.

Syntax:

while(condition)

{

statements;

}

//example for while loop
class WhileLoopExample
{

     public static void main(String []args)
     {
         int count=1;
         while(count<=10)
         {
             System.out.print(count+" ");
             count++;
         }
         System.out.println();

     }
}

Output:

1 2 3 4 5 6 7 8 9 10

As while checks the condition at top, if the condition is false it will not execute the body of the loop.

If the body of loop contains only one statement there is no need for braces.

//example for while loop  which will not execute any statement
class WhileLoopExample2{

     public static void main(String []args)
     {
         int count=1;
         while(count<=0)

             System.out.print("It will not execute");

     }
}

The while loop may be null also means there will be no body of loop.

//example for while loop with no body
class WhileLoopExample3
{

     public static void main(String []args)
     {
         int count=10, i=20 ;
         while(++count < --i);

             System.out.println("value of count is::"+count);

     }
}

Output:

value of count is::15

  • do-while

It provides the execution of group of statements at least once by using evaluating the condition at the bottom of the loop.

syntax:

do

{

satements;

}while(condition);

//example for do-while loop
class DoWhileLoopExample1{

     public static void main(String []args)
     {
         int count=1;
                     do
                     {
                     System.out.print(count+" ");
                     count++;
                     }
                     while(count<=10);
                     System.out.println();
     }
}

Output:

1 2 3 4 5 6 7 8 9 10

It is useful when we process a menu selection which should be execute at least once.

//example for do-while loop for menu
public class DoWhileExample
{
  public  static void main(String args[]) throws java.io.IOException 
  {
    char ch;
    do
    {
      System.out.println("1. a value ");
      System.out.println("2. b value ");
      System.out.println("3. c value ");
      System.out.println("4. exit ");
      System.out.println("enter ur choice");
      ch= (char) System.in.read();
      /*switch(ch)
      {

      }*/
      System.out.println(ch);
    } while( ch < '1' || ch > '4');
  }
}
  • For

It is the powerful control statement. JDK5 introduces for-each loop.

Syntax:

for(initialization, condition, iteration)

{

statements;

}

Initialization- This evaluates first. sets the value of the control variable for the loop.

Condition- It is the boolean expression which checks the control variable against a target value.If it is then executes the body of loop and then iteration otherwise bypassed from loop.

Iteration- either increment or decrement of the control variable. Then it checks the condition and so on until the condition is false.

//example for for loop
public class ForExample
{
  public  static void main(String args[]) throws java.io.IOException 
  {
    for(int count=1;count<=10;count++) //declaring within for loop
      System.out.print(count+" "); // braces not required as it is a singe statement

    System.out.println();
  }
}

Output:

1 2 3 4 5 6 7 8 9 10

Declaring control variable within for loop

The scope of the variable ends when that particular for loop work done.

Means we can't use that variable outside of that scope.

//example for declaring control variable in for loop and accessing outside scope
public class ForExample
{
  public  static void main(String args[]) throws java.io.IOException 
  {
    for(int count=1;count<=10;count++)
      System.out.print(count+" ");


    System.out.print(count); // error as we can't access the loop variable outside of its scope.

    System.out.println();
  }
}

Using comma

In for loop we can use comma t mo initialize two or more and to make iterations of two or more variables.

//example for using  comma in for loop
public class ForExample
{
  public  static void main(String args[]) throws java.io.IOException 
  {
    for(int a=1,b=5; a<=b; a++,b--)
    {
      System.out.println("value of a is::"+a);
       System.out.println("value of b is::"+b);
    }

  }
}

Output:

value of a is::1

value of b is::5

value of a is::2

value of b is::4

value of a is::3

value of b is::3

Variations in for loop

  • we can use any expressions than using the control variable.

Ex:

boolean b = true;

for(int i=0; b ;i++)

for(int j=0; a<b; i++)

  • we can write for loop without initialization and iteration.

Ex:

for(;a<b;)

  • Infinite loop which uses in operating system commands.

for(; ;)

The For-Each Version

Also referred as enhanced for loop.It prevents breakage of pre existing code and no usage of new keyword.

Syntax:

for(type ite_var : collection)

{

statements;

}

type is the data type of the variable.

ite-var is the name of the iteration variable which holds the elements of collection.

collection is the group of elements which iterates through. There are so many collections in java. like arrays, Lists, Maps, sets.

The type of iteration variable and the type of elements in the collection should be same.

//example for for-each loop
public class ForEachLoopExample
{
  public  static void main(String args[]) throws java.io.IOException 
  {
    int a[]={1,2,3,4,5};
    int sum=0;
    for(int x:a)
    {
      sum +=x;
    }
    System.out.println("sum of 5 numbers is::"+sum);
  }
}

Output:

sum of 5 numbers is::15

using break keyword we can terminate the loop at time of execution.

//example for using break keyword in for-each loop
public class UsingBreakExample
{
  public static void main(String args[])
  {
    int a[]={1,2,3,4,5};
    for( int i: a)
    {
      if(i==5)
        break;
      System.out.print(i);
    }

  }
}

Output:+

1 2 3 4

The iteration variable is the read-only type. Even if we try to change its value also it will not change.

//example for showing iteration variable as read-only
  public class ReadOnlyIterationVariableExample
{
  public static void main(String args[])
  {
    int a[]={1,2,3,4,5};
    for( int i: a)
    {
      System.out.print(i+" ");
      i+=5;

    }

  }
}

Output:

1 2 3 4 5

Iterating Over Multidimensional Array

Multidimensional array is the arrays of arrays. Means each iteration obtains array not an element.

//example for using for-each loop over multidimensional array
public class ReadOnlyIterationVariableExample
{
  public static void main(String args[])
  {
    int a[][]=new int[2][4];

    for(int i=0;i<2;i++)
      for(int j=0;j<4;j++)
      a[i][j]=(i+1)*(j+1);

      for(int x[]:a)
    {
      for(int ele: x)
      {
        System.out.print(ele+" " );
      }
      System.out.println();
    }

  }
}

Output:

1 2 3 4
2 4 6 8

Applying for-each loop

To find the element in the un-order list it is very easy to find by using for-each loop.

//example for using for-each loop for searching an element
public class ReadOnlyIterationVariableExample
{
  public static void main(String args[])
  {
    int a[]={2,5,7,1,9,10};
    boolean b=false;

    for(int i:a)
    {
      if(i==3)
      {
        b=true;
        break;
      }

    }
    if(b)
      System.out.println("element found");
    else

      System.out.println("element not found");
  }
}

Output:

element not found

Nested Loops

java allows to use one loop inside another loop.

//example for Nested loops
public class NestedLoopExample
{
public static void main(String args[])
{
int a[][]=new int[10][5];
for(int i=0;i<10;i++)
{
for(int j=0;j<5;j++)
a[i][j]=i*j;
}


 for(int i=0;i<10;i++)
{
for(int j=0;j<5;j++)
System.out.print(a[i][j]+ " ");
}
} 
}

Output:

0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 4 8 12 16 0 5 10 15 20 0 6 12 18 24 0 7 14 21 28 0 8 16 24 32 0 9 18 27 36

results matching ""

    No results matching ""