For Loop in Java | Example Program

The for loop in Java is an entry-controlled loop structure that executes a set of statements a fixed number of times.

The for statement provides a more concise syntax for creating loops. It executes a block of statements as long as the condition is true.

The general syntax of the for loop in Java is as follows:

for(initialization; test-condition;  iteration (increment/decrement)) {
   // Loop body
      Statement(s);
}
Or, 
for (i = initialValue; i < endValue; i++) {
 // Loop body
     Statement(s);
}

The flowchart of the for loop statement is shown in the below figure (a).

Java for loop statement

In the above syntax, for loop statement begins with a keyword for, followed by a pair of parentheses enclosing the loop control structure.

This structure consists of initialization, test condition, and iteration (increment or decrement). This control structure is followed by the body of loop enclosed inside curly braces.

The initialization, test condition, and iteration are separated by semicolons. There is no semicolon at the end iteration section.

The execution of for statement is as follows:

1. Initialization of control variables: A for loop generally uses a variable to control how many times the body of loop will be executed and when the body of loop terminates.

This variable is called control variable. It is initialized using an assignment operator such as i = 1 and count = 0. The variables i and count are called loop control variables. It is performed only once when a for statement is executed.

2. Test-condition: The value of control variable is evaluated using the test condition. The test condition is a Boolean expression, such as i < 10 that determines when the loop will exit.

It is evaluated before each loop iteration (execution). When the condition is true the loop body is executed. When false, the loop is terminated and the execution continues to the next statement after closing a curly brace that immediately follows the loop.

3. Iteration: When the loop body is executed, the control of execution is transferred back to for statement after executing the last statement in the loop.

The control variable is incremented or decremented using assignment statements such i++ (i.e. i = i + 1), or i– (i.e. i = i – 1), and the new value of control variable is again evaluated to see whether it satisfies the loop condition or not.

If the test condition is satisfied, the loop body is again executed. This process continues as long as the value of control variable fails to satisfy to test condition.


Consider the following code of a program.

int i;
for(i = 1; i <= 10; i++ ) {
    System.out.println("Hello Java");
}

Let’s understand how for loop works in the above example. The flowchart of statement is shown in the above figure (b). The for loop is initially set to 1 and the expression i = 1 will be executed only once for the first time.

The test condition is a Boolean expression. The expression (i <= 10) will be tested right after the initialization and at the beginning of each iteration. If this condition is true, the statement inside the loop body is executed and prints “Hello Java”.

The expression (i++) will be executed. Now, the value i becomes 2. Since the value of i is less than 10, the statement will be executed and prints “Hello Java” again.

This process continues until the value of i is greater than 10. If it is greater than 10, the expression (i <= 10) will be false and the loop terminates.

Now, we understood from the above discussion, the expression (i = 1) will be executed only once at the starting of the loop. Then expressions (i <= 10) and (i++) will be executed repeatedly until i is less than or equal to 10.

If there is only one statement in the body of loop, as in this example, the curly braces can be omitted.

Example Program based on for loop statement


1. Let’s take an example program where we will display numbers from 1 to 5 and from 5 to 1.

Program source code 1:

package javaProgram;
public class Test {
public static void main(String[] args) 
{
  System.out.println("Displaying numbers from 1 to 5:");	
  for(int i = 1; i <=5; i++) { // Here, i++ is increment operator.
     System.out.println(i);	
   }
System.out.println("Displaying numbers from 5 to 1:");
for(int j = 5; j > 0; j--) { // Here, j-- is decrement operator.
  System.out.println(j);	
 }
 }}
Output:
            Displaying numbers from 1 to 5:
            1
            2
            3
            4
            5
           Displaying numbers from 5 to 1:
           5
           4
           3
           2
           1

We can also write the same for loop like this:

int i = 1;
for(; i <= 5;) {
  System.out.println(i);
  i++;
}

2. Let’s take another program where we will calculate the sum of squares of integer numbers from 1 to 5 using for loop statement. Look at the following source code to understand better.


Program source code 2:

package javaProgram;
public class Test {
public static void main(String[] args) 
{	
int i = 1;
int sum = 0;
for(; i <= 5;) {
  sum = sum + i*i;	
  i++;
  }
System.out.println("Sum: " +sum);
 }
}
Output:
             Sum: 55

 Infinite For Loop in Java


Consider the following example code of a program.

int x = 1;
for(; ;)
{
  System.out.println(x);
  x++;
 }

In this example, there is no test condition in the for statement that tells where to stop. So, the code will execute without stoppage. This loop is called infinite loop in Java. We should avoid to make an infinite loop.

By mistake, if we make infinite for loop in java program, we can stop it using break statement. It can be used to come out of loop.

3. Let’s take an example program based on infinite for loop where we will display the sum of cubes of numbers from 1 to 5.

Program source code 3:

package javaProgram;
public class Test {
public static void main(String[] args) 
{
 int i = 1;
 int sum = 0;
for(; ;){
  sum = sum + i * i * i;	
  i++;
  if(i >= 5) break; // If the i value exceeds 5, then come out of this loop.
  }
System.out.println("Sum: " +sum);
 }
}
Output:
            Sum: 100

4. Let’s take an example program where we will initialize two variables in for statement and will display numbers from 1 to 5 and 5 to 1 simultaneously.

Program source code 4:

package javaProgram;
public class Test {
public static void main(String[] args) 
{
 int i, j;
for(i = 1, j = 5; i <=  5; i++, j--)
{
    System.out.println(i+ "\t" +j);
  }
 }}
Output:
            1	   5
            2	   4
            3	   3
            4	   2
            5	   1

In this loop, we have used two initialization expressions (i = 1, and j = 5) and two iteration expressions (i++, and j–). But there is only one test conditional expression (i < = 5).

This for loop will print i values from 1 to 5 whereas, the values of j will simultaneously change from 5 to 1.

Note:

1. The for loop can have more than one initialization expression and iteration expression. This feature cannot apply in other loops. Each expression must be separated from the next by a comma.

Let’s take one more program based on this point.

Program source code 5:

package javaProgram;
public class Test {
public static void main(String[] args) 
{
 int x, y;
for(x = 1, y = 5; x < y; x++, y--) 
{
    System.out.println("x = " + x);
    System.out.println("y = " + y);
  }
 }}
Output:
             x = 1
             y = 5
             x = 2
             y = 4

In this example program, the initialization portion consists of two control variables x and y that have been separated by comma. The two comma separated expressions (x++ and y–) in the iteration portion are executed each time the loop repeats.

2. The test condition in for loop statement can also have compound relation. Let’s understand it with the help of an example program.

Program source code 6:

package javaProgram;
public class Test {
public static void main(String[] args) 
{
int x = 1, sum = 0;
for(x = 1; x < 20 && sum < 20; x++){
  sum = sum + x;
 }
System.out.println("Sum: " +sum);
 }
}
Output:
             Sum: 21

In this example, the loop will be executed until both conditions x < 20 and sum < 20 are true. The sum is evaluated within the body of loop.

3. It is also possible to use expressions in the initialization and increment portions. For example, this type of statement for(x = (a + b)/5; x > 10; x = x/5) is perfectly valid.

4. When we declare control variable inside a for statement, the scope of that variable is ended after the ending of for loop. It means that the control variable defined inside a for statement is a local variable that cannot be accessed from outside the loop.

Program source code 7:

public class Test {
public static void main(String[] args) 
{
for(int x = 1; x < 10; x++){
  System.out.println(x); //  No error.
}
System.out.println(x); // Compile time error.
 }
}

Hope that this tutorial has covered all the important points related to for loop in Java with a variety of example programs. I hope that you will have understood this simple topic and practiced programs based on Java for loop.
Thanks for reading!!!
Next ⇒ Nested for loop in Java

⇐ Prev Next ⇒