Java for Loop

🔁 Java for Loop

The for loop is used when you know exactly how many times you want to repeat a block of code.
It combines initialization, condition, and increment/decrement in one line.


Syntax

for (initialization; condition; update) {
// code to execute
}

📘 Example 1: Print 1 to 5

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

📌 Output:

1
2
3
4
5

📘 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);
}
}
}

📘 Example 3: Reverse Countdown

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

📘 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));
}
}
}


📘 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;
}

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


📘 Example 6: Loop Through an Array

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

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


📘 Example 7: Nested for Loop (Pattern Example)

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:

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

🧠 When to Use a for Loop?

Use it when:

✔ You know the number of iterations
✔ You want compact control of start, stop, and step values


🔍 while vs for Summary

Feature while for
Best for Unknown iteration count Known iteration count
Structure Condition only Init + Condition + Update
Readability Moderate Very clear

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 *