- What is a for loop?
- Syntax of the for Loop
- Let’s break it down:
- Example of For Loop (Print Numbers from 1 to 5)
- Step-by-Step Explanation:
- 1. Class and main method
- 2. For loop
- Let’s break the loop into parts:
- 3. Inside the loop
- 🔢 Loop Iterations:
- Summary:
- Flowchart of for Loop
- Use Cases of for Loop
- Infinite for Loop
- Decrementing for Loop
- Syntax:
- Example
- Output
- How It Works:
- Some For Loop Program to Practice
- Program 1: Sum of First N Numbers Using for Loop
- Program 2: Using for Loop with Arrays
- Program 3: Pattern Printing Using for Loops
- Common Mistakes to Avoid
- Nested for Loops
- Practice Set
- Summary
- Final Thought
When learning Java programming, loops are one of the most important concepts to understand because they allow us to repeat tasks efficiently. In Java, the for loop is one of the most commonly used loop structures.
This tutorial will walk you through everything about for loops in Java.
What is a for loop?
A for loop is a control flow statement used to repeat a block of code a certain number of times. It is best used when you know in advance how many times you want to execute a statement or block of statements.
Syntax of the for Loop
for (initialization; condition; update) {
// body of the loop
}
Let’s break it down:
| Part | Description |
|---|---|
initialization | This is where you declare and initialize the loop control variable (like int i = 0). It runs only once at the beginning. |
condition | This is the condition that gets evaluated before each iteration. If it returns true, the loop continues. If it returns false, the loop stops. |
update | This is executed after every iteration. It usually increases or decreases the loop variable. |
{ body } | This contains the code that runs on every iteration. |
Example of For Loop (Print Numbers from 1 to 5)
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
Step-by-Step Explanation:
1. Class and main method
public class ForLoopExample {
public static void main(String[] args) {
- This is the starting point of the program.
- The
mainmethod is where the program execution begins.
2. For loop
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
The for loop is used to repeat a task, in this case, printing numbers from 1 to 5.
Let’s break the loop into parts:
- Initialization:
int i = 1;
→ A variableiis created and set to 1. This is the starting point of the loop. - Condition:
i <= 5;
→ Before each loop run, Java checks this condition.
If it’strue, the loop runs. Iffalse, it stops. - Update:
i++
→ After every loop execution,iincreases by 1.
3. Inside the loop
System.out.println(i);
- This line prints the current value of
ito the screen.
🔢 Loop Iterations:
| i Value | Condition (i <= 5) | Output |
|---|---|---|
| 1 | true | Prints 1 |
| 2 | true | Prints 2 |
| 3 | true | Prints 3 |
| 4 | true | Prints 4 |
| 5 | true | Prints 5 |
| 6 | false | Loop stops |
Summary:
Above program uses a for loop to print numbers from 1 to 5, each on a new line. It’s a simple example to show how looping works in Java.
Flowchart of for Loop
Initialization → Condition → Body → Update
↑ ↓
← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ←
Use Cases of for Loop
- Printing numbers or patterns
- Repeating an operation with a counter
- Traversing arrays or lists (fixed size)
- Summing a series of numbers
Infinite for Loop
If the condition never becomes false, the loop runs forever.
for (;;) {
System.out.println("This is an infinite loop");
}
is an example of an infinite loop in Java.
- A
forloop has no initialization, no condition, and no update. - Since there’s no condition to stop, it keeps running forever.
- It will continuously print:
This is an infinite loop
until the program is manually stopped.
🛑 Use infinite loops carefully, and make sure to include a break when needed.
Decrementing for Loop
You can count backward too!
A decrementing for loop is used when you want to count backward, such as from a higher number down to a lower number.
Syntax:
for (int i = start; i >= end; i--) {
// Code to execute
}
start= starting value (e.g., 5)end= the limit to stop (e.g., 1)i--= decreasesiby 1 after each loop
Example
for (int i = 5; i >= 1; i--) {
System.out.println(i);
}
Output
5
4
3
2
1
How It Works:
- Starts from
i = 5 - Prints the value of
i - Decreases
iby 1 in each step - Stops when
ibecomes less than 1
Some For Loop Program to Practice
Program 1: Sum of First N Numbers Using for Loop
public class SumExample {
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
Program 2: Using for Loop with Arrays
public class ArrayExample {
public static void main(String[] args) {
int[] marks = {85, 90, 78, 92, 88};
for (int i = 0; i < marks.length; i++) {
System.out.println("Marks of subject " + (i + 1) + ": " + marks[i]);
}
}
}
Output:
Marks of subject 1: 85
Marks of subject 2: 90
Marks of subject 3: 78
Marks of subject 4: 92
Marks of subject 5: 88
Program 3: Pattern Printing Using for Loops
Let’s print a simple pyramid:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
*
* *
* * *
* * * *
* * * * *
This is an example of a nested for loop, a loop inside another loop.
Common Mistakes to Avoid
| Mistake | What Happens |
|---|---|
Forgetting i++ or i-- | The loop may become infinite |
Writing i = 0; i < 5; instead of ; | Causes a syntax error |
| Misusing array index | Results in ArrayIndexOutOfBoundsException |
Nested for Loops
You can put one for loop inside another. Commonly used in matrix operations and pattern printing.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println("i = " + i + ", j = " + j);
}
}
Practice Set
- Write a
forloop to print the even numbers between 1 and 20. - Calculate the factorial of a number using a
forloop. - Print this pattern:
1 1 2 1 2 3 1 2 3 4 - Find the maximum number in an array using a
forloop. - Reverse an array using a
forloop.
Summary
| Concept | Details |
|---|---|
| Best use | When number of iterations is known |
| Syntax | for(initialization; condition; update) |
| Nested loops | Yes, supported |
| Infinite loop | Possible with for(;;) |
| Array support | Excellent for indexing |
Final Thought
The for loop in Java is a powerful and flexible tool for repeating code. Once you understand how it works with initialization, condition, and update, you can write efficient programs with ease.