Course contentsShow
← C
Lesson 303 of 1,2194. Control FlowFree lesson

Controlling the inner loop with outer loop variables

Controlling the inner loop with outer loop variables

What you'll learn: How to create dynamic repeating patterns by using the outer loop's counter to change how many times the inner loop runs.

The "Growing Rows" Concept

Up until now, you may have used nested loops to create grids—like a 5x5 square where the inner loop always runs five times. However, the inner loop doesn't have to be a static number. Because the inner loop lives inside the scope of the outer loop, it has full access to the outer loop's counter variable.

Think of it like a staircase. On the first floor (Step 1), you lay one brick. On the second floor (Step 2), you lay two bricks. The number of bricks you lay is directly tied to which floor you are currently on. In C, we achieve this by setting the "stop condition" of our inner loop to the current value of the outer loop's variable.

Seeing it in C

By using the outer variable i as the limit for the inner variable j, the inner loop starts short and gets longer with every iteration of the outer loop.

#include <stdio.h>

int main() {
    int rows = 5;

    // The outer loop tracks which row we are on
    for (int i = 1; i <= rows; i++) {
        
        // The inner loop runs 'i' times
        // It resets and looks at the NEW value of 'i' every row
        for (int j = 1; j <= i; j++) {
            printf("*");
        }
        
        // Move to the next line after the inner loop finishes
        printf("\n");
    }

    return 0;
}

How the logic flows

  1. First Pass: The outer loop sets i = 1. The inner loop starts and says, "Run until j reaches i." Since i is 1, it runs once and prints one star.
  2. Second Pass: The outer loop increments to i = 2. The inner loop starts fresh and says, "Run until j reaches 2." It prints two stars.
  3. Progression: This continues until the last row, where i is 5, causing the inner loop to print five stars.

This technique is the foundation for processing triangular data, building pyramids, or handling any scenario where the sub-task depends on the progress of the main task.

Key takeaway

By using the outer loop's counter as the limit for the inner loop, you create a dynamic relationship where the length of the inner task changes with each iteration.