Β
π for loop in Java
One of the most powerful tools in Java is the for loop. Whether you want to repeat a task 10 times or process millions of records, the for loop is your go-to. π
π§ What is a for loop?
A for loop is used to execute a block of code repeatedly until a given condition is false.
π Syntax:
for(initialization; condition; update) {
// Code to be executed
}
π Breaking it Down
-
Initialization β Runs once, sets the starting point.
-
Condition β Checked before each loop; if false, loop stops.
-
Update β Executes after each iteration, usually increments/decrements a counter.
π Example:
for(int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
π‘ Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
π― Why use a for loop?
βοΈ Best when you know exactly how many times you want to run the loop.
βοΈ Cleaner and more concise compared to while loops.
βοΈ Perfect for arrays, lists, and collections.
Β
β‘ Types of for loops in Java
-
Standard for loop
-
Example above π
-
-
Enhanced for loop (for-each loop)
-
Best for arrays & collections.
int numbers[] = {10, 20, 30}; for(int n : numbers) { System.out.println(n); } -
-
Nested for loop
-
A loop inside another loop (commonly used in patterns & matrices).
for(int i = 1; i <= 3; i++) { for(int j = 1; j <= 3; j++) { System.out.print(i + "," + j + " "); } System.out.println(); } -
Examples:
Got it π
Here are some popular, practical, and engaging examples of for loop in Java that you can post on your website to keep readers hooked π
π Popular Examples of for loop in Java
1οΈβ£ Print Numbers from 1 to 10
for(int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
Output:
1 2 3 4 5 6 7 8 9 10
2οΈβ£ Print the Multiplication Table
int num = 5;
for(int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
Output (for 5):
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50
3οΈβ£ Calculate Sum of First N Numbers
int sum = 0;
for(int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum = " + sum);
Output:
Sum = 5050
4οΈβ£ Reverse a String
String str = "Java";
for(int i = str.length() - 1; i >= 0; i--) {
System.out.print(str.charAt(i));
}
Output:
avaJ
5οΈβ£ Pattern Printing (Star Pyramid)
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
*
* *
* * *
* * * *
* * * * *
6οΈβ£ Iterate an Array (Using for-each loop)
int[] arr = {10, 20, 30, 40, 50};
for(int num : arr) {
System.out.print(num + " ");
}
Output:
10 20 30 40 50
Β