Table of Contents

    Nested Loops

    Programming Mastery

    Nested Loops

    Learn how loops inside loops help programs work with repeated patterns, tables, grids, rows and columns, combinations, and multi-level data.

    What are Nested Loops?

    Nested loops mean writing one loop inside another loop.

    In simple words, when a loop is placed inside the body of another loop, it is called a nested loop. The outside loop is called the outer loop, and the loop inside it is called the inner loop.

    A nested loop is a loop inside another loop, where the inner loop runs completely for every single iteration of the outer loop.

    Nested loops are useful when a program needs repeated actions inside another repeated action. For example, printing rows and columns, creating multiplication tables, processing a grid, checking all combinations, or working with two-dimensional data.

    Easy Real-Life Example

    Nested Loops as Days and Periods

    Imagine a school timetable. For each day, there are multiple class periods. First, you choose a day. Then, for that day, you go through all the periods. After all periods are completed for one day, you move to the next day.

    This is similar to nested loops:

    FOR each day
        FOR each period
            DISPLAY day and period
        END FOR
    END FOR

    The outer loop controls the days. The inner loop controls the periods for each day.

    Why are Nested Loops Needed?

    A single loop is useful when one level of repetition is needed. But some problems require two levels of repetition. For example, to print a table, we need rows and columns. To process marks of multiple students in multiple subjects, we need students and subjects. To print a pattern, we need lines and symbols inside each line.

    Importance of Nested Loops

    • They help repeat a task inside another repeated task.
    • They are useful for rows and columns.
    • They help print patterns such as stars, numbers, and tables.
    • They are useful for working with grids and matrices.
    • They help process two-dimensional data.
    • They are useful for comparing every item with every other item.
    • They help generate combinations.
    • They build strong understanding of iteration and control flow.

    General Syntax of Nested Loops

    The language-neutral structure of nested loops is:

    FOR outerVariable FROM start TO end
        FOR innerVariable FROM start TO end
            statements
        END FOR
    END FOR

    The inner loop is written inside the outer loop. For each value of the outer loop variable, the inner loop completes all its repetitions.

    How Nested Loops Work

    Nested loops follow a very important rule:

    Rule: For every one iteration of the outer loop, the inner loop runs completely from start to finish.

    Working Steps

    • The outer loop starts its first iteration.
    • The program enters the inner loop.
    • The inner loop runs all its iterations.
    • After the inner loop finishes, control returns to the outer loop.
    • The outer loop moves to its next iteration.
    • The inner loop again runs completely.
    • This continues until the outer loop also finishes.

    Nested Loop Flow

    START
      ↓
    Outer loop iteration 1
      ↓
    Inner loop runs all iterations
      ↓
    Outer loop iteration 2
      ↓
    Inner loop runs all iterations again
      ↓
    Outer loop continues until finished
      ↓
    END

    This flow shows why nested loops can execute many times even when the outer loop runs only a few times.

    Example 1: Printing Rows and Columns

    This example prints row and column numbers.

    /*
    This program prints row and column positions.
    */
    
    ENTRY POINT
        FOR row FROM 1 TO 3
            FOR column FROM 1 TO 2
                DISPLAY "Row: " + row + ", Column: " + column
            END FOR
        END FOR
    END ENTRY POINT

    Expected Output

    Row: 1, Column: 1
    Row: 1, Column: 2
    Row: 2, Column: 1
    Row: 2, Column: 2
    Row: 3, Column: 1
    Row: 3, Column: 2

    The outer loop runs 3 times for rows. For each row, the inner loop runs 2 times for columns. So the total output lines are 3 × 2 = 6.

    Example 2: Multiplication Table

    Nested loops are commonly used to print multiplication tables.

    /*
    This program prints multiplication tables from 1 to 3.
    */
    
    ENTRY POINT
        FOR tableNumber FROM 1 TO 3
            DISPLAY "Table of " + tableNumber
    
            FOR multiplier FROM 1 TO 10
                DISPLAY tableNumber + " x " + multiplier + " = " + (tableNumber * multiplier)
            END FOR
    
            DISPLAY "----------------"
        END FOR
    END ENTRY POINT

    The outer loop chooses the table number. The inner loop multiplies that table number from 1 to 10.

    Example 3: Printing a Star Rectangle

    Nested loops are very useful for pattern printing.

    /*
    This program prints a rectangle pattern.
    */
    
    ENTRY POINT
        FOR row FROM 1 TO 4
            FOR column FROM 1 TO 5
                DISPLAY "*" WITHOUT NEW LINE
            END FOR
    
            DISPLAY NEW LINE
        END FOR
    END ENTRY POINT

    Expected Output

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

    The outer loop controls the number of rows. The inner loop controls how many stars appear in each row.

    Example 4: Printing a Right Triangle Pattern

    /*
    This program prints a right triangle pattern.
    */
    
    ENTRY POINT
        FOR row FROM 1 TO 5
            FOR column FROM 1 TO row
                DISPLAY "*" WITHOUT NEW LINE
            END FOR
    
            DISPLAY NEW LINE
        END FOR
    END ENTRY POINT

    Expected Output

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

    In this example, the inner loop depends on the current value of the outer loop. When row is 1, one star is printed. When row is 5, five stars are printed.

    Example 5: Processing a Grid

    A grid has rows and columns, so nested loops are a natural fit.

    /*
    This program visits every cell in a grid.
    */
    
    ENTRY POINT
        FOR row FROM 1 TO 3
            FOR column FROM 1 TO 3
                DISPLAY "Visiting cell (" + row + ", " + column + ")"
            END FOR
        END FOR
    END ENTRY POINT

    This type of logic is useful in games, tables, spreadsheets, image processing, and matrix-style problems.

    Example 6: Students and Subjects

    Nested loops can be used when each student has multiple subject marks.

    /*
    This program reads marks for multiple students and subjects.
    */
    
    ENTRY POINT
        DECLARE numberOfStudents AS INTEGER = 3
        DECLARE numberOfSubjects AS INTEGER = 4
        DECLARE marks AS DECIMAL = 0.0
    
        FOR student FROM 1 TO numberOfStudents
            DISPLAY "Student " + student
    
            FOR subject FROM 1 TO numberOfSubjects
                DISPLAY "Enter marks for subject " + subject
                INPUT marks
            END FOR
    
            DISPLAY "Marks entry completed for student " + student
        END FOR
    END ENTRY POINT

    The outer loop controls students. The inner loop controls subjects for each student.

    Trace Table for Nested Loops

    Let us trace this nested loop:

    FOR i FROM 1 TO 2
        FOR j FROM 1 TO 3
            DISPLAY i, j
        END FOR
    END FOR
    Outer Loop Value i Inner Loop Value j Output
    1 1 1, 1
    1 2 1, 2
    1 3 1, 3
    2 1 2, 1
    2 2 2, 2
    2 3 2, 3

    The outer loop runs 2 times and the inner loop runs 3 times for each outer loop value. Total inner statements executed: 2 × 3 = 6.

    How to Calculate Total Iterations

    In many nested loop problems, total execution count is calculated by multiplying the number of iterations.

    Outer Loop Iterations Inner Loop Iterations Total Inner Executions
    3 2 3 × 2 = 6
    5 10 5 × 10 = 50
    10 10 10 × 10 = 100
    Important: Nested loops can run many times quickly. Always think about total iterations before using them on large data.

    Types of Nested Loops

    Different types of loops can be nested together.

    Nested Loop Type Meaning Example Use
    FOR inside FOR A for loop written inside another for loop. Rows and columns, multiplication table.
    WHILE inside WHILE A while loop written inside another while loop. Repeating until two conditions are completed.
    FOR inside WHILE A for loop written inside a while loop. Menu repetition with fixed inner options.
    WHILE inside FOR A while loop written inside a for loop. For each item, repeat until a condition becomes false.

    FOR Inside FOR Example

    FOR row FROM 1 TO 3
        FOR column FROM 1 TO 3
            DISPLAY row + "," + column
        END FOR
    END FOR

    WHILE Inside WHILE Example

    SET row = 1
    
    WHILE row <= 3 DO
        SET column = 1
    
        WHILE column <= 2 DO
            DISPLAY "Row: " + row + ", Column: " + column
            SET column = column + 1
        END WHILE
    
        SET row = row + 1
    END WHILE

    In this example, the inner loop variable column is reset every time the outer loop starts a new row.

    Resetting the Inner Loop Variable

    In nested loops, the inner loop usually starts again for each outer loop iteration.

    SET row = 1
    
    WHILE row <= 3 DO
        SET column = 1
    
        WHILE column <= 3 DO
            DISPLAY row + "," + column
            SET column = column + 1
        END WHILE
    
        SET row = row + 1
    END WHILE

    Here, column must be set back to 1 for each new row. If we forget this reset, the inner loop may not work correctly after the first row.

    Break and Continue in Nested Loops

    Loop control statements can also be used inside nested loops.

    Break in Nested Loops

    In many programming languages, a BREAK inside the inner loop stops only the inner loop, not the outer loop.

    FOR row FROM 1 TO 3
        FOR column FROM 1 TO 3
            IF column == 2 THEN
                BREAK
            END IF
    
            DISPLAY row + "," + column
        END FOR
    END FOR

    Continue in Nested Loops

    A CONTINUE inside the inner loop skips the current inner-loop iteration and moves to the next inner-loop iteration.

    FOR row FROM 1 TO 3
        FOR column FROM 1 TO 3
            IF column == 2 THEN
                CONTINUE
            END IF
    
            DISPLAY row + "," + column
        END FOR
    END FOR

    Nested Loops vs Single Loop

    Feature Single Loop Nested Loop
    Meaning One loop repeats one block. One loop repeats another loop.
    Best For One-dimensional repetition. Two-level repetition.
    Example Print numbers from 1 to 10. Print multiplication table rows and columns.
    Execution Count Usually simple to count. Often multiplication of loop counts.

    When to Use Nested Loops

    Use nested loops when the problem naturally has two or more levels of repetition.

    Good Use Cases

    • Printing star patterns.
    • Generating multiplication tables.
    • Processing rows and columns.
    • Working with grids or boards.
    • Processing matrices.
    • Working with nested lists.
    • Checking combinations of two lists.
    • Handling students and subjects.

    When to Avoid Nested Loops

    Nested loops should be used carefully because they can increase execution time, especially when the data is large. Power Automate Best Practices.pdf explicitly warns that nested “For Each” loops can increase execution time because iterations multiply, such as 10 × 10 = 100. [4](https://ts.accenture.com/sites/RoboExchange/Platform/PowerPlatform/Shared%20Documents/Power%20Automate%20Best%20Practices.pdf?web=1)

    Avoid or Reconsider When

    • The data size is very large.
    • The same result can be achieved with a simpler loop.
    • The nested logic becomes hard to read.
    • There are too many levels of nesting.
    • The inner loop repeats unnecessary work.
    • The program becomes slow because of too many iterations.

    Common Beginner Mistakes

    Mistakes

    • Not understanding that the inner loop runs completely for each outer loop iteration.
    • Using the same loop variable name for both outer and inner loops.
    • Forgetting to reset the inner loop variable in while-based nested loops.
    • Creating infinite loops by not updating counters.
    • Writing too many nested levels.
    • Not calculating total iterations.
    • Putting output in the wrong loop level.
    • Using nested loops when a simpler solution is possible.

    Better Habits

    • Use different variable names such as row and column.
    • Trace nested loops step by step.
    • Calculate total iterations before running large loops.
    • Keep nested loop logic simple.
    • Use proper indentation.
    • Reset inner loop counters when needed.
    • Use comments for complex nested logic.
    • Test with small values first.

    Best Practices for Nested Loops

    Good nested loop logic should be clear, controlled, and easy to trace.

    Recommended Practices

    • Use nested loops only when the problem needs multiple levels of repetition.
    • Use meaningful loop variables such as row, column, student, and subject.
    • Keep the inner loop simple.
    • Avoid unnecessary calculations inside the inner loop.
    • Use proper indentation to show loop levels clearly.
    • Start with small loop limits while testing.
    • Use trace tables to understand execution order.
    • Avoid deep nesting unless absolutely necessary.
    • Check total iterations for performance.
    • Use comments when the nested logic is not obvious.

    Prerequisites Before Learning Nested Loops

    To understand nested loops properly, students should already know these concepts:

    Basic Prerequisites

    • What is control flow?
    • Sequential execution.
    • Looping and iteration.
    • For loop.
    • While loop.
    • Loop counters.
    • Loop conditions.
    • Increment and decrement.
    • Break and continue basics.
    • Trace tables.

    Practice Activity: Predict the Output

    Predict the output of the following nested loop.

    FOR row FROM 1 TO 3
        FOR column FROM 1 TO 2
            DISPLAY row + "-" + column
        END FOR
    END FOR

    Your Answer

    Write the output here:
    
    ________________
    ________________
    ________________
    ________________
    ________________
    ________________

    Sample Answer

    1-1
    1-2
    2-1
    2-2
    3-1
    3-2

    Mini Quiz

    1

    What is a nested loop?

    A nested loop is a loop written inside another loop.

    2

    What is the outer loop?

    The outer loop is the loop that contains another loop inside its body.

    3

    What is the inner loop?

    The inner loop is the loop written inside the outer loop.

    4

    If the outer loop runs 4 times and the inner loop runs 5 times, how many times does the inner statement execute?

    The inner statement executes 4 × 5 = 20 times.

    5

    Give one use of nested loops.

    Nested loops can be used to print multiplication tables, star patterns, grids, or rows and columns.

    Interview Questions on Nested Loops

    1

    Define nested loops in programming.

    Nested loops are loop structures where one loop is placed inside another loop to handle multiple levels of repetition.

    2

    How does the inner loop execute in a nested loop?

    The inner loop executes completely for every single iteration of the outer loop.

    3

    Why are nested loops useful for rows and columns?

    Rows and columns require two levels of repetition: one loop for rows and another loop for columns.

    4

    What is a common mistake in nested loops?

    A common mistake is forgetting that the inner loop runs fully for each outer loop iteration, which can lead to unexpected output or too many executions.

    5

    Why should deep nesting be avoided?

    Deep nesting should be avoided because it can make code difficult to read, debug, and maintain.

    Quick Summary

    Concept Meaning
    Nested Loop A loop inside another loop.
    Outer Loop The main loop that contains the inner loop.
    Inner Loop The loop that runs inside the outer loop.
    Execution Rule The inner loop runs completely for each outer loop iteration.
    Total Iterations Usually calculated by multiplying outer and inner loop counts.
    Best Use Patterns, multiplication tables, rows and columns, grids, matrices, and combinations.
    Best Practice Use clear variables, proper indentation, and avoid unnecessary nesting.

    Final Takeaway

    Nested loops are used when a program needs repetition inside repetition. They are powerful for printing patterns, generating tables, processing rows and columns, and working with multi-level data. In the Programming Mastery Course, students should understand that the inner loop runs completely for each iteration of the outer loop. Nested loops are useful, but they should be written carefully because total iterations can grow quickly.