ITERATIVE STATEMENTS

 
Repeating the same code fragment several times is called iterating. Java iteration statements are given below it.
a. for statement
b. while statement
c. do-while statement
 
a) for statement
for loop statement is a iteration statement.
Syntax:
1
2
3
4
for( initialization; condition; change ){
        statement1;
        statement2;
        statementN;}

The loop first starts; the initialization portion of the loop is executed. This sets the value of the loop control variable. Next, condition is evaluated. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates. Next, the change portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable.

Example:
1
2
3
4
5
6
7
8
class ForDemo
{
    public static void main(String args[ ]) 
    {
        for(int n=5; n>0; n--)
        System.out.println("tick " + n);
    }
}
 
b) While statement:
The while loop is Java’s most fundamental looping statement. In a simpler language; while statement continually executes a block of statements while a particular condition is true. The while loop is Java’s most fundamental looping statement.
Syntax: while(condition)  { // body of loop }
The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control comes out of the while loop and execute the next line of code immediately following the loop.
 
Example:
1
2
3
4
5
6
7
8
9
10
public static int WhileDemo (int x)
{
      int n = 0, p = 1;
      while ( p < x )  
      {
          p = p*2;
          n++;
      }
      return n;
}
 
c) do-while statement:
The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates.
Syntax:
1
2
3
4
5
do
    {
        statement(s)
    }
        while (expression);

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class DoWhileDemo  
  {
        public static void main (String args[])
        {
            int i = 0;
            do 
            {
                System.out.print("Bonjour"); 
                System.out.println(" ");
                i = i + 1; 
            }
            while (i < 5);
        }
 }