What is For Loop in Java?

Any conditional repetitive kind of flow can be performed using a for-loop.

The syntax of a for-loop is:

for ( <control variable> ; <test condition>; <step value> )

{

 // block of statements

}

The for-loop will start execution from the control variable i.e. initial value to the final value until the test condition is found true. The initial value will be updated by the step value.

For example, if you want to print 8 times “I love Computer”, the code will be:

class Repeat
{
public static void main()
{
for(i=1;i<=8;i++)
{
System.out.println("I Love Computers");
i++;
}
}
}

Output:

I Love Computers
I Love Computers
I Love Computers
I Love Computers
I Love Computers
I Love Computers
I Love Computers
I Love Computers

 

Let us understand what happened:

Step 1) The control variable ‘i’ is declared outside the loop construct.

Step 2) The for-loop construct starts and initializes ‘i’ with the value 1.

Step 3) The test condition is given as  ‘ i<=8’, which means while the value of i is less than or equals to 8, the loop will execute.

Step 4) The step value is given as ‘i++’ which means i=i+1, i.e. the value of I is incremented by 1 at every iteration until the test condition is true.

 

Now suppose we want to write a program to print the first ten multiples of 2.

The source code will be:

class Multiple
{
public static void main()
{
int c=0;
for(i=1;i<=10;i++)
{
c=2*i;
System.out.println(c);
}
}
}

Output:

2
4
6
8
10
12
14
16
18
20
What is For Loop in Java?