Using nested loops to print 2D grids
What you'll learn: How to use one loop inside another to generate rows and columns for visual grids.
Thinking in two dimensions
When you write a single for loop, you are moving along a line. But to create a 2D shape—like a game board, a spreadsheet, or a pixel map—you need to move in two directions: left-to-right (columns) and top-to-bottom (rows).
Think of a nested loop like a clock. The outer loop is the hour hand; it moves slowly. The inner loop is the minute hand; it completes a full circle for every single "tick" of the hour hand. In programming, the outer loop tells the computer which row you are currently standing on, and the inner loop tells it to walk across all the seats in that row.
Building the grid
To print a grid, we use the outer loop to manage the vertical movement and the inner loop to manage the horizontal movement. Every time the inner loop finishes printing a set of characters, we must remember to print a "newline" (\n) to move the cursor down to the next row.
Here is how you would print a 3x5 rectangle of stars:
#include <stdio.h>
int main() {
int rows = 3;
int cols = 5;
// The outer loop handles the rows
for (int i = 0; i < rows; i++) {
// The inner loop handles the columns in the current row
for (int j = 0; j < cols; j++) {
printf("* ");
}
// After the inner loop finishes one row, move to the next line
printf("\n");
}
return 0;
}
How the execution flows
- The outer loop starts at row 0.
- The inner loop runs completely, printing
* * * * *. - The inner loop finishes, and
printf("\n")jumps to a new line. - The outer loop moves to row 1, and the process repeats.
Without the nested structure, you would have to write hundreds of print statements for a large grid. With it, changing a 3x5 grid into a 100x100 grid only requires changing two numbers. This logic is the foundation for rendering graphics, processing images, and managing data tables in C.
Key takeaway
Nested loops create 2D grids by using an outer loop for rows and an inner loop for columns, separated by a newline.