Java for Loop

The for loop statement provides a compact way to iterate over a range of values. Programmers often refer to it as the “for loop” because of the way it repeatedly loops until a particular condition is satisfied.

1. for loop syntax

The general form of the for statement can be expressed as follows:

for (initialization; termination; increment) 
{
    statement(s);
}
  1. The initialization expression initializes the loop; it’s executed once, as the loop begins.
  2. When the termination expression evaluates to false, the loop terminates.
  3. The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.

2. for loop example

For example, the following for-loop statement will print all integers between 1 and 6, inclusive:

for(int num = 1; num <= 6; num++)
{
	 System.out.println(num);
}

Program output.

1
2
3
4
5
6

The execution of for loop flows like this-

  1. First, 'int num = 1' is executed, which declares an integer variable num and initializes it to 1.
  2. Then, condition-expression (num <= 6) is evaluated, which is 1 <= 6. It evaluates to true for the first time. Now, the statement associated with the for-loop statement is executed, which prints the current value of num.
  3. Finally num++ is executed, which increments the value of num by 1. At this point, the value of num becomes 2.
  4. The condition-expression 2 <= 6 is evaluated, which returns true, and again current value of num is printed.
  5. This process continues until the value of num becomes 6 and it is printed.
  6. After that, num++ sets the value of num to 7, and the expression 7 <= 6 returns false, which stops the execution of the for-loop statement.

3. initialization and increment are optional parts

Please note that initialization and increment are optional parts, can be controlled from other places. But termination condition is mandatory for a finite loop. If you do not mention termination condition, then it will be an infinite for loop.

int num = 1;		//initialization

for( ; num <= 6 ; )
{
	 System.out.println(num);
	 num++;			//increment
}

Program output.

1
2
3
4
5
6

Above for loop is perfectly valid and will result in similar output as it’s previous version.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.