Table of Contents
What is For Loop?
A for loop in Java is a control flow statement that executes a block of code repeatedly. It is used when a task needs to be performed a fixed number of times. A for loop consists of three parts — initialization, condition, and update expression. All three parts are written in a single line and together determine how many times the loop will run.Syntax:
Example:for (initialization; condition; update) {
// body of loop
}
// Java program to implement
// for loop
public class ForLoopExample {
public static void main(String[] args)
{
for (int i = 1; i = 5; i++)
{
System.out.println("Iteration number: " + i);
}
}
}
Output:
Explanation:Iteration number: 1
Iteration number: 2
Iteration number: 3
Iteration number: 4
Iteration number: 5
- int i = 1: The loop variable i is initialized to 1. This runs only once at the start.
- i = 5: The condition is checked before every iteration. As long as i is less than or equal to 5, the loop body runs.
- i++: After every iteration, i is incremented by 1.
- When i becomes 6, the condition i = 5 becomes false and the loop stops.
- The output shows 5 lines, one for each iteration from 1 to 5.
Key Features of For Loop
- Compact Syntax: In a for loop, the initialization, condition, and update expression are all written in a single line. This makes the code more readable and compact.
- Fixed Iteration Count: When we already know exactly how many times the loop should run, the for loop is the best choice. It makes controlling the iteration count straightforward and easy.
- Initialization: Once In a for loop, the initialization happens only once — before the loop begins. After that, only the condition and update expression are executed in each iteration.
- Condition Check Before Execution: The for loop is an entry-controlled loop. This means the condition is checked before the loop body executes. If the condition is false from the very beginning, the loop body does not execute even once.
- Update Expression: After every iteration, the update expression is automatically executed. It is generally used to increment or decrement the loop variable.
- Supports Nested Loops: A for loop can be written inside another for loop, which is called a nested for loop. It is commonly used for printing 2D arrays or patterns.
Simple For Loop
This is the most basic form. It uses a counter variable to control the loop.
Syntax:
for (int i = 0; i 5; i++) {
System.out.println(i);
}
Example:
// Java program to implement
// simple for loop
public class SimpleForLoop {
public static void main(String[] args)
{
System.out.println("Multiplication table of 3:");
for (int i = 1; i = 10; i++)
{
System.out.println("3 x " + i + " = " + (3 * i));
}
}
}
Output:
Explanation:Multiplication table of 3:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
- The loop starts at i = 1 and runs until i = 10.
- In each iteration, it prints the multiplication of 3 with the current value of i.
- i++ increments the counter after every iteration.
- After i becomes 11, the condition fails and the loop exits.
- This is one of the most common real-world uses of a simple for loop.
Enhanced For Loop (For-Each Loop)
This loop is used with arrays and collections. It does not use a counter variable — it directly traverses each element.
Syntax:
Example:int[] arr = {1, 2, 3, 4, 5};
for (int num : arr) {
System.out.println(num);
}
// Java program to implement
// enhanced for loop
public class EnhancedForLoop {
public static void main(String[] args)
{
String[] fruits = {"Apple", "Mango", "Banana",
"Orange", "Grapes"};
System.out.println("List of fruits:");
for (String fruit : fruits)
{
System.out.println(fruit);
}
}
}
Output:
Explanation:List of fruits:
Apple
Mango
Banana
Orange
Grapes
- The array fruits holds 5 string values.
- The enhanced for loop declares a temporary variable fruit that takes the value of each element one by one.
- In every iteration, the current element is stored in fruit and printed.
- There is no index variable, no condition to write, and no update expression needed.
- The loop automatically stops after the last element of the array is processed.
Nested For Loop
When one for loop is placed inside another, it is called a nested for loop. It is used for patterns and 2D arrays.Syntax:
Example:for (int i = 1; i = 3; i++) {
for (int j = 1; j = 3; j++) {
System.out.print(i * j + " ");
}
System.out.println();
}
// Java program to implement
// nested for loop
public class NestedForLoop {
public static void main(String[] args)
{
System.out.println("Star pattern using nested for loop:");
for (int i = 1; i = 5; i++)
{
for (int j = 1; j = i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
Explanation:Star pattern using nested for loop:
*
* *
* * *
* * * *
* * * * *
- The outer loop controls the number of rows. It runs from i = 1 to i = 5.
- The inner loop controls how many stars are printed in each row. It runs from j = 1 to j = i.
- In row 1, the inner loop runs once and prints 1 star.
- In row 2, the inner loop runs twice and prints 2 stars, and so on.
- System.out.println() after the inner loop moves to the next line after each row.
- When the outer loop finishes all 5 iterations, the complete triangle pattern is printed.
Infinite For Loop
If the condition is always true or no condition is written at all, the loop becomes infinite. A break statement is used to stop it.Syntax:
Example:for (;;) {
System.out.println("Infinite loop");
break;
}
// Java program to implement
// infinite for loop
public class InfiniteForLoop {
public static void main(String[] args)
{
int count = 0;
for (;;)
{
System.out.println("Count is: " + count);
count++;
if (count == 5)
{
System.out.println("Limit reached. Exiting loop.");
break;
}
}
}
}
Output:
Explanation:Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Limit reached. Exiting loop.
- for (;;) has no initialization, no condition, and no update, this creates an infinite loop by default.
- Inside the loop body, count is printed and then incremented by 1 after every iteration.
- The if statement checks whether count has reached 5.
- When count == 5, a message is printed and the break statement immediately exits the loop.
- Without the break, this loop would run forever and the program would never stop.
Simple For Loop vs Enhanced For Loop vs Nested For Loop
| Feature | Simple For Loop | Enhanced For Loop | Nested For Loop |
|---|---|---|---|
| Meaning | Loop is controlled by a counter variable | Array/collection elements are traversed directly | One loop is placed inside another loop |
| Main Use | For fixed count repetition | For iterating arrays and collections | For patterns and 2D data |
| Index Access | Index is available | Index is not directly available | Index is available for both loops |
| Complexity | Simple and flexible | Simple and clean syntax | Complex but powerful |
| Modification | Elements can be modified inside the loop | Elements cannot be directly modified | Control available at both levels |
| Example Use | Printing numbers 1 to 10 | Printing all elements of an array | Printing a star pattern or matrix |
How For Loop Works?
- Initialization: The loop variable is declared and initialized. This happens only once, before the loop starts. Example: int i = 0
- Condition Check: The condition is evaluated. If the condition is true, the loop body executes. If false, the loop terminates.
- Loop Body Executes: When the condition is true, the code written inside the loop is executed.
- Update Expression: After the loop body executes, the update expression runs. This is generally i++ or i--.
- Back to Condition: After the update, the condition is checked again. This process continues until the condition becomes false.
Conclusion
The for loop is a very useful and commonly used concept in Java programming. Whenever a task needs to be repeated a fixed number of times, the for loop is the most efficient and appropriate choice. The simple for loop is used for basic counting; the enhanced for loop works with arrays and collections, and the nested for loop handles complex patterns and 2D data. What all types have in common is that they are all entry-controlled loops – meaning the condition is checked first and the body executes after. Understanding these loops builds a strong foundation in Java programming.Frequently Asked Questions
1. What is the difference between a for loop and a while loop?2. Why is the index not available in an enhanced for loop?A for loop is used when the number of iterations is known in advance. A while loop is used when the count is not known and the loop depends only on a condition.
3. When is an infinite for loop used?The enhanced for loop only traverses elements without tracking the index. If the index is needed, a simple for loop should be used instead.
4. What is the time complexity of a nested for loop?When a process needs to run until a specific condition is met, an infinite loop is used together with a break statement to control termination.
5. Can multiple variables be initialized in a for loop?If both loops run n times, the time complexity is O(n²), which can be slow for large inputs.
Yes, for (int i = 0, j = 10; i j; i++, j--) — multiple variables can be initialized and updated simultaneously in this way.
0 Comments