For Loop in Java

Among different types of loop, for loop is one. This is the simplest loop in java. It is used to execute same piece of code multiple times with some condition.
Syntax:

for (initialization; condition; post-operation) {
statements here
}
As we can see above, we have three properties inside parenthesis starting with keyword for. Between these properties, we must use semicolon ;.

Lets break down those properties. In first, we set and initial value for iteration. Then it checks for the given condition. If the condition is true, then it executes the program inside curly braces. Finally it does post operation. After post operation, there must be new iteration value. Then again, it restarts the process. Only after the the condition fails, the loop stops.


Examples:

Lets say I want to print BCA Boost 10 times. So instead of writing same line 10 times, we can do this:
Code:

public class LearnForLoop { public static void main(String[] args) { for(int i = 1; i <= 10; i++) { System.out.println("BCA Boost"); } } }
we can see in above program, we set i to 1 and checked condition if i is less than or equal to 10. And if it is, execute the code below. For post operation we incremented i by 1 so that it will go for next iteration.
Output:
BCA Boost
BCA Boost
BCA Boost
BCA Boost
BCA Boost
BCA Boost
BCA Boost
BCA Boost
BCA Boost
BCA Boost


Also we can use the value of iteration inside the code block. Lets see this example:
Code:

public class LearnForLoop { public static void main(String[] args) { for(int i = 1; i <= 5; i++) { System.out.println("Iteration: " + i); } } }
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5


Lets try to print multiplication table of 4 using for loop:
Code:

public class LearnForLoop { public static void main(String[] args) { for(int i = 1; i <= 10; i++) { int res = 4 * i; System.out.println(4 + " X " + i +" = "+ res); } } }
Output:
4 X 1 = 4
4 X 2 = 8
4 X 3 = 12
4 X 4 = 16
4 X 5 = 20
4 X 6 = 24
4 X 7 = 28
4 X 8 = 32
4 X 9 = 36
4 X 10 = 40


Loops in Java Previous Next While Loop in Java