C Nested Loops
Nested loops in C refer to loops placed inside another loop. They are commonly used for working with multi-dimensional arrays, printing patterns, and solving complex iterative problems.
In this tutorial, you will learn the syntax of nested loops in C programming, and how to use them effectively with examples.
Syntax of Nested Loops
In a nested loop structure, the inner loop runs completely for each iteration of the outer loop.
</>
Copy
for (initialization; condition; increment/decrement) {
for (initialization; condition; increment/decrement) {
// Code to execute in each iteration of inner loop
}
// Code to execute in each iteration of outer loop
}
Explanation of Syntax:
- The outer
for
loop executes first. - For each iteration of the outer loop, the inner
for
loop executes completely. - After the inner loop completes, control moves back to the outer loop for the next iteration.
Examples of Nested Loops
1 Printing a Number Pattern
In this example, we will use nested loops to print a number pattern.
main.c
</>
Copy
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Explanation:
- The outer loop runs from
1
to5
, controlling the rows. - The inner loop runs from
1
to3
, printing numbers in a row. - After each iteration of the inner loop, a new line is printed.
Output:
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
2 Creating a Multiplication Table
We will use nested loops to print a multiplication table from 1 to 5.
main.c
</>
Copy
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
printf("%d\t", i * j);
}
printf("\n");
}
return 0;
}
Explanation:
- The outer loop iterates through numbers
1
to5
. - The inner loop multiplies the outer loop index with the inner loop index.
- The result is printed with a tab space.
- After each row, a new line is printed.
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Conclusion
In this tutorial, we explored nested loops in C, including:
- The syntax of nested loops and how they work.
- A number pattern program using nested loops.
- A multiplication table program using nested loops.