Table of Contents
What is a Nested Loop?
A nested loop in Java is a loop that is placed inside the body of another loop. The loop that contains another loop is called the outer loop, and the loop placed inside it is called the inner loop.- For every single iteration of the outer loop, the inner loop runs through all of its iterations completely from start to finish.
- This means if the outer loop runs 5 times and the inner loop runs 5 times, the total number of executions of the inner loop body will be 5 × 5 = 25.
- Any type of loop in Java for, while, or do-while can be nested inside any other type of loop.
Syntax:
Example:for (initialization; outerCondition; outerUpdate) {
for (initialization; innerCondition; innerUpdate) {
// inner loop body
}
// outer loop body (optional)
}
// Java program to implement
// Nested loops
public class TutorialforGeeks {
public static void main (String [] args)
{
for (int i = 1; i = 3; i++)
{
for (int j = 1; j = 3; j++)
{
System.out.println("i = " + i + ", j = " + j);
}
}
}
}
Output:
Explanation:i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 2
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3
- The outer loop starts with i = 1 and runs until i = 3.
- For every value of i, the inner loop starts fresh from j = 1 and runs until j = 3.
- When i = 1, the inner loop runs three times printing j = 1, 2, 3.
- When i = 2, the inner loop again runs three times printing j = 1, 2, 3.
- When i = 3, the inner loop again runs three times printing j = 1, 2, 3.
- Total executions of the inner body = 3 × 3 = 9 lines printed in the output.
Key Features of Nested Loops
- Loop Inside a Loop: A nested loop is simply any loop placed inside the body of another loop. The outer loop and the inner loop can be of any type – for, while, or do-while and they do not need to be of the same type.
- Complete Inner Execution Per Outer Iteration: For every single iteration of the outer loop, the inner loop runs through all of its iterations completely. This multiplying behavior is what makes nested loops so powerful for working with multi-dimensional data.
- Independent Loop Variables: The outer loop and inner loop each have their own separate loop variable. These variables are independent of each other and can both be used together inside the inner loop body to produce meaningful results.
- Total Iterations = Outer × Inner: If the outer loop runs m times and the inner loop runs n times, the total number of times the inner loop body executes is m × n. This is an important consideration when thinking about performance and time complexity.
- Supports All Loop Types: Java allows any combination of loop types in a nested structure. A for loop can be nested inside a while loop, a while loop can be nested inside a do-while loop, and so on. The choice depends entirely on the problem being solved.
- Used for Patterns and 2D Arrays: Nested loops are the standard approach for printing patterns like triangles, pyramids, and diamonds, as well as for traversing and processing two-dimensional arrays and matrices in Java.
Nested For Loop
When you know exactly how many rows and columns your output needs, putting one for loop inside another is the most natural and clean solution. Most Java programmers reach for this combination first when working with patterns, tables, and grids.Syntax:
Example:for (int i = 1; i = outerLimit; i++) {
for (int j = 1; j = innerLimit; j++) {
// inner loop body
}
}
// Java program to implement
// Nested for loop
public class TutorialforGeeks {
public static void main (String [] args)
{
System.out.println("Right-angled triangle pattern:");
for (int i = 1; i = 5; i++)
{
for (int j = 1; j = i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
Explanation:Right-angled triangle pattern:
*
* *
* * *
* * * *
* * * * *
- 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, i = 1 so the inner loop runs once and prints 1 star.
- In row 2, i = 2 so the inner loop runs twice and prints 2 stars.
- This pattern continues until row 5 where 5 stars are printed.
- System.out.println() after the inner loop moves to the next line after completing each row.
Nested While Loop
A while loop placed inside another while loop. Used when the number of iterations depends on dynamic conditions.Syntax:
Example:int i = 1;
while (i = outerLimit) {
int j = 1;
while (j = innerLimit) {
// inner loop body
j++;
}
i++;
}
// Java program to implement
// Nested while loop
public class TutorialforGeeks {
public static void main (String [] args)
{
System.out.println("Multiplication table (3 and 4):");
int i = 3;
while (i = 4)
{
int j = 1;
while (j = 10)
{
System.out.println(i + " x " + j + " = " + (i * j));
j++;
}
System.out.println();
i++;
}
}
}
Output:
Explanation:Multiplication table (3 and 4):
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
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
- The outer while loop runs for i = 1 to i = 3, representing each table number.
- For every value of i, the inner while loop runs from j = 1 to j = 10.
- The inner loop prints the complete multiplication table for the current value of i.
- After the inner loop finishes, System.out.println() adds a blank line for readability.
- i++ increments the outer counter and the process repeats for the next table number.
Nested Do-While Loop
A do-while loop placed inside another do-while loop. The body of both loops always executes at least once.Syntax:
Example:int i = 1;
do {
int j = 1;
do {
// inner loop body
j++;
} while (j = innerLimit);
i++;
} while (i = outerLimit);
// Java program to implement
// Nested do-while loop
public class TutorialforGeeks {
public static void main (String [] args)
{
System.out.println("Number grid using nested do-while:");
int i = 1;
do {
int j = 1;
do {
System.out.print(i * j + "\t");
j++;
} while (j = 5);
System.out.println();
i++;
} while (i = 5);
}
}
Output:
Explanation:Number grid using nested do-while:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
- The outer do-while loop runs from i = 1 to i = 5, representing each row.
- For every value of i, the inner do-while loop runs from j = 1 to j = 5.
- The inner loop prints i * j for each column, separated by a tab character \t.
- After the inner loop, System.out.println() moves to the next row.
- Since both are do-while loops, both bodies execute at least once before any condition is checked.
Mixed Nested Loop
A for loop placed inside a while loop. Used when the outer iteration count is unknown but the inner count is fixed.Syntax:
Example:int i = 1;
while (outerCondition) {
for (int j = 1; j = innerLimit; j++) {
// inner loop body
}
i++;
}
// Java program to implement
// mixed Nested loop
public class TutorialforGeeks {
public static void main (String [] args)
{
System.out.println("Pyramid pattern using mixed nested loop:");
int i = 1;
while (i = 5)
{
for (int j = 1; j = i; j++)
{
System.out.print(j + " ");
}
System.out.println();
i++;
}
}
}
Output:
Explanation:Pyramid pattern using mixed nested loop:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
- The outer while loop controls the number of rows, running from i = 1 to i = 5.
- For every row, the inner for loop runs from j = 1 to j = i, printing the column numbers.
- In row 1, only 1 is printed. In row 2, 1 2 is printed, and so on.
- This creates a left-aligned number pyramid pattern with 5 rows.
- System.out.println() moves to the next line after each row is complete.
Nested Loop with Break and Continue
Nested loops combined with break and continue to control execution at specific points inside the loop.Syntax:
Example:for (int i = 1; i = outerLimit; i++) {
for (int j = 1; j = innerLimit; j++) {
if (j == skipValue) continue; // skip this iteration
if (j == stopValue) break; // exit inner loop
// inner loop body
}
}
// Java program to implement
// nested loop with break and
// continue statement
public class TutorialforGeeks {
public static void main (String [] args)
{
for (int i = 1; i = 3; i++)
{
System.out.println("Outer loop i = " + i);
for (int j = 1; j = 5; j++)
{
if (j == 2)
{
System.out.println(" Skipping j = " + j);
continue;
}
if (j == 4)
{
System.out.println(" Breaking at j = " + j);
break;
}
System.out.println(" Inner loop j = " + j);
}
}
}
}
Output:
Explanation:Outer loop i = 1
Inner loop j = 1
Skipping j = 2
Inner loop j = 3
Breaking at j = 4
Outer loop i = 2
Inner loop j = 1
Skipping j = 2
Inner loop j = 3
Breaking at j = 4
Outer loop i = 3
Inner loop j = 1
Skipping j = 2
Inner loop j = 3
Breaking at j = 4
- The outer loop runs 3 times for i = 1, 2, 3.
- For each value of i, the inner loop starts from j = 1.
- When j == 2, continue skips that iteration so j = 2 is never printed as an inner loop value.
- When j == 4, break exits the inner loop immediately so j = 4 and j = 5 are never reached.
- Note that break here only exits the inner loop the outer loop continues normally for the next value of i.
Nested For Loop vs Nested While Loop vs Nested Do-While Loop
| Feature | Nested For Loop | Nested While Loop | Nested Do-While Loop |
|---|---|---|---|
| Purpose | Used when both outer and inner iteration counts are fixed and known in advance. | Used when both outer and inner iterations depend on dynamic runtime conditions. | Used when both outer and inner iterations depend on dynamic runtime conditions. Used when both the outer and inner loop bodies must execute at least once. |
| Condition Check | Both outer and inner conditions are checked before each iteration entry-controlled. | Both outer and inner conditions are checked before each iteration entry-controlled. | Both outer and inner conditions are checked after each iteration exit-controlled.. |
| Minimum Executions | Neither loop body executes if the condition is false from the beginning. | Neither loop body executes if the condition is false from the beginning. | Both loop bodies always execute at least once regardless of the condition. |
| Best Used When | Best for printing patterns, iterating 2D arrays, and matrix operations with known sizes. | Best for nested dynamic conditions like reading variable-length data row by row. | Best when both outer and inner actions must happen at least once before any check. |
| Update Expression | Built into the loop header for both outer and inner loops. | Must be written manually inside both the outer and inner loop bodies. | Must be written manually inside both the outer and inner loop bodies. |
| Example Use | Printing star patterns, number pyramids, and multiplication tables. | Processing rows and columns of dynamically sized data structures. | Nested menu-driven programs where both menus must show at least once. |
How Nested Loops Work Step by Step?
- Outer Loop Initializes: The outer loop variable is initialized once before the loop begins. This variable typically represents the row number or the first dimension of the data being processed.
- Outer Loop Condition Checked: The outer loop condition is evaluated. If it is true, execution enters the outer loop body. If it is false from the start, neither the outer nor the inner loop body executes at all.
- Inner Loop Runs Completely: For every single iteration of the outer loop, the inner loop runs through all of its iterations from start to finish. The inner loop variable is re-initialized at the beginning of each outer loop iteration.
- Inner Loop Body Executes: The body of the inner loop executes for each iteration. This is where the actual work is done: printing a character, processing an array element, or computing a value.
- Inner Loop Ends, Outer Loop Updates: Once the inner loop condition becomes false, the inner loop ends. Control returns to the outer loop, the outer loop variable is updated, and the outer condition is checked again.
- Process Repeats Until Outer Loop Ends: Steps 2 through 5 repeat until the outer loop condition becomes false. At that point, both loops have finished, and execution continues with the next statement after the nested loop block.
Conclusion
Nested loops are one of the most powerful and versatile tools available in Java programming. By placing one loop inside another, you gain the ability to work with multi-dimensional data, generate complex patterns, traverse 2D arrays, build multiplication tables, and solve a wide variety of real-world programming problems. The key to understanding nested loops is remembering that for every single iteration of the outer loop, the inner loop completes all of its iterations, and this multiplying behavior is what gives nested loops their power. While nested loops are extremely useful, it is equally important to be mindful of their time complexity since the total number of iterations grows as a product of both loop counts. Knowing when and how to use nested for loops, nested while loops, nested do-while loops, and mixed combinations makes you a far more capable and effective Java programmer.Frequently Asked Questions
1. Can we nest more than two loops in Java?2. Does break inside a nested loop exit all loops or just the inner one?Yes, Java allows nesting three or more loops, but deeply nested loops significantly increase time complexity and should be used only when absolutely necessary.
3. What is a labeled break in Java and when is it used in nested loops?By default, break exits only the innermost loop it is placed in to break out of an outer loop, Java provides labeled break statements.
4. What is the time complexity of a nested loop with two levels?A labeled break allows you to exit a specific outer loop directly from inside a nested inner loop by attaching a label to the outer loop and using break label Name.
5. Can the inner loop variable have the same name as the outer loop variable?If both the outer and inner loops run n times, the time complexity is O(n²) which means the total iterations grow quadratically as n increases.
No, if both loops are in the same scope, using the same variable name causes a compile-time error each loop must use a uniquely named variable.
0 Comments