Nested loops for multiplication tables
What you'll learn: How to use one loop inside another to generate structured, grid-based data like a multiplication table.
The Clock Analogy
Think of a digital clock. The minutes "loop" from 0 to 59. However, for every full cycle of minutes, the hour hand moves forward exactly once. Nested loops work the same way: an inner loop completes its entire run for every single step of the outer loop.
When we want to build a multiplication table, we need to move across columns (inner loop) and down rows (outer loop).
Building the Grid
To create a 5x5 table, we need to think in two dimensions. The outer loop represents the "multiplier" (the rows), and the inner loop represents the "multiplicand" (the columns).
As the program runs, the outer loop starts at 1. While the outer loop is stuck at 1, the inner loop counts from 1 to 5. Once the inner loop finishes, we print a new line, and the outer loop moves to 2. Then, the inner loop starts all over again from 1 to 5.
#include <stdio.h>
int main() {
int rows = 5;
int cols = 5;
// Outer loop: Controls the current row
for (int i = 1; i <= rows; i++) {
// Inner loop: Controls the current column
for (int j = 1; j <= cols; j++) {
// Calculate and print the product
// \t adds a tab space to keep columns neat
printf("%d\t", i * j);
}
// After the inner loop finishes a row, move to the next line
printf("\n");
}
return 0;
}
How it Executes
- Outer loop starts (i = 1): The inner loop runs 5 times, printing
1, 2, 3, 4, 5. - Line break: The
\nmoves the cursor down. - Outer loop increments (i = 2): The inner loop resets and runs 5 times again, but now it multiplies everything by 2, printing
2, 4, 6, 8, 10. - Repeat: This continues until the outer loop reaches 5.
Nested loops are powerful for any task involving grids, coordinates, or tables because they allow you to visit every possible combination of two variables.
Key takeaway
Nested loops allow you to repeat a sequence of actions (the inner loop) multiple times as part of a larger cycle (the outer loop).