Java: For Loop

java for loop

For Loop 

Here, in this page we will discuss about For loop in Java. Looping is a cardinal feature of any programming language. It allows the execution of a set of instructions  or commands repetitively for a specified number of iteration, until a certain condition is met.

Using loops saves the programmer from the hassle of writing the same code again and again to obtain the desired results. We have three different loops in programming:

  • For Loop.
  • While Loop.
  • Do- While loop.

Understanding the concept

The For loop is a functionality of a programming language that comes into play when some code needs to be executed iteratively. It is the most favorable looping technique to be used where the number of iterations are known beforehand. Let us know how the control flows in a for loop.

  • Initialization: It marks the beginning of the for loop. We can use an already declared variable or a local variable can be  declared for the loop only.
  • Check Condition: It is basically the exit condition for the loop which yields a boolean value. This condition is evaluated in each iteration. If the condition is true then the statements inside for loop body gets executed. But once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.
  • Code/Statements inside loop: If the check condition yields true this block of code is executed for a specific number of iterations.
  • Update Counter: After each iteration of the loop the counter is updated. It is either incremented or decremented.
  • Loop Termination: When the check condition yields false the control flow comes out of the loop and it is terminated.

For better understanding, the working of this flowchart has been given in the following image.

for loop

Syntax of For Loop

public class Main
{
	public static void main(String[] args) {
            for (initialization ; check condition; update counter(inc/dec)){
                block of code;
            }
	}
}

Now that we have seen the syntax of the for loop, let us understand it further with the help of an example.  Suppose we want to print a series of numbers starting from 0 till 10. Now instead of writing the code again and again we will be using for loop

For this, the code using if statement will be :

Run
public class Main
{
	public static void main(String[] args) {
             for(int i = 0; i < 5; i++)
		System.out.println("Number:"+i);
	}
}

Output: 

Number:0
Number:1
Number:2
Number:3
Number:4