๐ C Nested Loops – Loop Inside a Loop
In C programming, nested loops mean using one loop inside another. The inner loop runs completely every time the outer loop runs once. They are useful for printing patterns, grids, tables, and more!
๐น Syntax of Nested Loops
for (int i = 0; i < outerLimit; i++) { for (int j = 0; j < innerLimit; j++) { // inner loop code } }
๐ Example 1: Simple Nested For Loop
This prints a 3×3 grid of asterisks using nested loops.
#include <stdio.h> int main() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { printf("* "); } printf("\n"); } return 0; }
๐ Example 2: Printing Row and Column Numbers
This displays the current row and column of each loop iteration.
#include <stdio.h> int main() { for (int row = 1; row <= 2; row++) { for (int col = 1; col <= 3; col++) { printf("Row %d, Col %d\n", row, col); } } return 0; }
๐ฏ What You Should Know
- Each time the outer loop runs, the inner loop restarts and completes its cycle.
- Useful for printing number patterns, grids, and solving matrix-related problems.
- You can use
for
,while
, ordo-while
loops inside each other.
๐ Practice Challenge
Try printing a triangle pattern using nested loops. Or loop through a 2D array and print each value โ have fun looping!