Java For Loop Examples

Java For Loop Examples

The for loop is commonly used when the number of iterations is known. Below are multiple practical examples.


📌 Example 1: Print 1 to 10

public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}

📌 Output:

1
2
3
4
5
6
7
8
9
10

📌 Example 2: Print Even Numbers

public class Main {
public static void main(String[] args) {
for (int i = 2; i <= 20; i += 2) {
System.out.println(i);
}
}
}

📌 Output:

2
4
6
8
10
12
14
16
18
20

📌 Example 3: Reverse Countdown

public class Main {
public static void main(String[] args) {
for (int i = 10; i >= 1; i--) {
System.out.println(i);
}
}
}

📌 Output:

10
9
8
7
6
5
4
3
2
1

📌 Example 4: Multiplication Table

public class Main {
public static void main(String[] args) {
int number = 5;

for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
}
}
}

📌 Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 10 = 50

📌 Example 5: Sum of First 10 Numbers

public class Main {
public static void main(String[] args) {
int sum = 0;

for (int i = 1; i <= 10; i++) {
sum += i; // sum = sum + i
}

System.out.println("Sum = " + sum);
}
}

📌 Output:

Sum = 55

📌 Example 6: Loop Through an Array

public class Main {
public static void main(String[] args) {
String[] cars = {"BMW", "Audi", "Tesla"};

for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
}
}

📌 Output:

BMW
Audi
Tesla

📌 Example 7: Nested For Loop (Pattern)

public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}

📌 Output:

*
* *
* * *
* * * *
* * * * *

🧠 Summary

Example Type Purpose
Counting Print numbers sequentially
Even Numbers Increment pattern
Countdown Reverse iteration
Multiplication Table Pattern multiplication
Sum Accumulation logic
Array Iteration Access array elements
Nested Loop Print patterns

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *