For Loop in Java

For Loop in Java

For Loop In Java Notes

The for loop in Java runs for a fixed number of times. In other words, loop which executes a set of statements a fixed number of times is known as a for loop. for loop is an entry-controlled loop. That means decision whether the loop will run or not is taken at the beginning of the loop.

A for loop has three parts:

  1. Initialization Expression
  2. Test/Conditional Expression
  3. Update Expression

The variable used in a for loop is known as a loop variable.

The for loop can be used in three different ways:

  • Single line loop

    for(i = 1; i <= 10000; i++);
  • Two line loop

    for(i = 1; i <= 10; i++)
    System.out.print( i + " ");
  • Multi-line loop

    for( i = 1; i <= 10; i++){
        a = i + 2;
        System.out.print(a + " ");

The for loop can be used to generate series, patterns, traverse an array or simply repeat certain statements for a specified number of times. Following is a simple program to generate squares of natural numbers up to 10 terms.

class NaturalSquares{

 public static void main(String args[]){

 int i, a;

  for(i = 1; i <= 10; i++){

     a = i * i;

   System.out.print(a+" ");

  }//end of loop

 }//end of main

}//end of class