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

The 'triangle' pattern logic

The 'triangle' pattern logic

What you'll learn: How to use a nested loop where the inner loop's limit depends on the outer loop's current value to create shaped output.

In the previous lesson, we used nested loops to build rectangles. In a rectangle, the inner loop always runs a fixed number of times. But what if we want to build a triangle? To do this, we need the "width" of our rows to change as we move from top to bottom.

The "Growing" Inner Loop

Imagine you are building a staircase. On the first step, you lay one brick. On the second step, you lay two bricks. On the third, three. The number of bricks depends entirely on which step you are currently standing on.

In C, we replicate this by making the inner loop's condition dependent on the outer loop's counter variable. Instead of saying j < 5 (which creates a fixed width), we say j <= i.

Seeing the code

Look at how the inner loop (j) uses the outer loop's variable (i) as its finish line:

#include <stdio.h>

int main() {
    int rows = 5;

    // Outer loop handles the vertical rows
    for (int i = 1; i <= rows; i++) {
        
        // Inner loop handles the horizontal stars
        // It stops when it hits the current row number (i)
        for (int j = 1; j <= i; j++) {
            printf("*");
        }
        
        // Move to the next line after finishing a row
        printf("\n");
    }

    return 0;
}

How it works

  1. Row 1 (i = 1): The inner loop runs while j <= 1. It prints one star and stops.
  2. Row 2 (i = 2): The inner loop resets. It runs while j <= 2. It prints two stars and stops.
  3. Row 5 (i = 5): The inner loop runs while j <= 5. It prints five stars.

By linking the two loops, the "limit" of the inner loop is no longer a static wall; it is a moving target that expands every time the outer loop ticks forward. This creates the classic right-angle triangle shape in your console.

Key takeaway

To create a triangle pattern, set the inner loop's maximum boundary to the current value of the outer loop's counter.