on Leave a Comment

Java for Loop With Examples

The java for loop is a entry controlled loop, that allows to execute specific block of code repeatedly until certain condition is false.

General Form of Java for Loop is:

for(initialization; condition; update)
{
  //Body of the loop
}

Execution of for loop statement is as follows:

(1) Initialization is done using assignment operator, for example i = 0. The variable which is initialized is called loop control variable. Initialization code executes once at the beginning of for loop statement. You can initialize zero or more than one variable in a single for loop statement.

Example:

class JavaForLoop
{
 public static void main(String[] args) {
  int i = 1;
  for( ; i<=5; i++)
  {
   System.out.println(i);
  }
 }
}

Output:

1
2
3
4
5

(2) The loop condition is a relational expression. This condition can be either true or false. If it is true, body of for loop executes and if the condition is false, body of for loop will skipped. This condition is checked every time after executing body of for loop

(3) After executing the last statement of for loop, control is transferred back to the for statement. Now the control variable will update (for example increment or decrement). New value of control variable is again tested will loop condition.

Flow Chart of Java for Loop
Java for Loop
Java for Loop
Example of Java for Loop

class JavaForLoop
{
 public static void main(String[] args) {
  int i = 2;
  for(int j = 1 ; j<=10; j++)
  {
   System.out.println(i+" * "+j+" = "+i*j);
  }
 }
}

Output:


2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

0 comments:

Post a Comment