Nested Loops in C
Introduction
In programming, loops are used to execute a block of code repeatedly. Nested loops are loops inside another loop. The inner loop will be executed one time for each iteration of the outer loop. This concept is very useful in scenarios where we need to work with multi-dimensional arrays or perform repetitive tasks in a structured manner.
Basic Structure of Nested Loops
The basic structure of nested loops looks as follows:
for (initialization; condition; increment/decrement) { for (initialization; condition; increment/decrement) { // Inner loop code } // Outer loop code }
Example 1: Nested For Loop
Let's take a simple example where we print a 5x5 grid of asterisks.
#include <stdio.h> int main() { int i, j; for (i = 0; i < 5; i++) { for (j = 0; j < 5; j++) { printf("* "); } printf("\n"); } return 0; }
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
Example 2: Multiplication Table
We can use nested loops to create a multiplication table. Here’s how you can do it:
#include <stdio.h> int main() { int i, j; for (i = 1; i <= 10; i++) { for (j = 1; j <= 10; j++) { printf("%d\t", i * j); } printf("\n"); } return 0; }
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Example 3: Pyramid Pattern
Nested loops can also be used to create patterns. Here is an example of a pyramid pattern:
#include <stdio.h> int main() { int i, j, k; int n = 5; // Number of levels for (i = 1; i <= n; i++) { for (j = i; j < n; j++) { printf(" "); } for (k = 1; k <= (2 * i - 1); k++) { printf("* "); } printf("\n"); } return 0; }
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
Conclusion
Nested loops are a powerful tool in C programming, allowing you to perform complex tasks with relative ease. They are essential when dealing with multi-dimensional arrays and creating intricate patterns. By understanding and using nested loops effectively, you can write more efficient and readable code.