Java - Looping Statements

1. For Loop

  • For Loop is used to execute set of statements repeatedly until the condition is true.
  • For Loop contain the following statements such as Initialization , Conditionand Increment/Decrement statement.

Syntax :

							  
for (initialization; condition ; increment) {
    Statement1
    Statement2
    .
    .
    .
    StatementN
}

							  

Example :

							  							  
class ForDemo {
    public static void main(String[] args){
         for(int i=1; i<11; i++){
              System.out.println("Count is : " + i);
         }
    }
}

							  

OUTPUT :

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

2. While Loop

  • In java, while is iteration statements like for and do-while.
  • In for loop initialization,condition and increment all three statements are combined into the one statement , in while loop all these statements are written as separate statements.

Example :

							  
class WhileDemo {
    public static void main(String[] args){
        int cnt = 1;
        while (cnt < 11) {
            System.out.println("Number Count : " + cnt);
            count++;
        }
    }
}

							  

3. While Loop

  • In java Do-while is iteration statements like for loop and while loop.
  • Do-while Statement is Exit Controlled Loop because condition is check at the last moment.

Syntax :


do {
     Statement1;
     Statement2;
     Statement3;
     .
     .
     .
     .
     StatementN;
} while (expression);


Example :

							  
class DoWhile {
  public static void main(String args[]) {
    int n = 5;
    do
     {
     System.out.println("Sample : " + n);
     n--;
     }while(n > 0);
}

							  

OUTPUT :

Sample : 5
Sample : 4
Sample : 3
Sample : 2
Sample : 1
Sample : 0

BytecodeTechnosolutions.com | Raju