Nested for Loop
Nested for loop refers to any type of loop that is defined inside a ‘for’ loop. Below is the equivalent flow diagram for nested ‘for’ loops:
Syntax:
for ( initialization; condition; increment ) { for ( initialization; condition; increment ) { // statement of inside loop } // statement of outer loop }
Example: Below program uses a nested for loop to print a 3D matrix of 2x3x2.
C
// C program to print elements of Three-Dimensional Array // with the help of nested for loop #include <stdio.h> int main() { // initializing the 3-D array int arr[2][3][2] = { { { 0, 6 }, { 1, 7 }, { 2, 8 } }, { { 3, 9 }, { 4, 10 }, { 5, 11 } } }; // Printing values of 3-D array for ( int i = 0; i < 2; ++i) { for ( int j = 0; j < 3; ++j) { for ( int k = 0; k < 2; ++k) { printf ( "Element at arr[%i][%i][%i] = %d\n" , i, j, k, arr[i][j][k]); } } } return 0; } |
Element at arr[0][0][0] = 0 Element at arr[0][0][1] = 6 Element at arr[0][1][0] = 1 Element at arr[0][1][1] = 7 Element at arr[0][2][0] = 2 Element at arr[0][2][1] = 8 Element at arr[1][0][0] = 3 Element at arr[1][0][1] = 9 Element at arr[1][1][0] = 4 Element at arr[1][1][1] = 10 Element at arr[1][2][0] = 5 Element at arr[1][2][1] = 11
Nested Loops in C with Examples
A nested loop means a loop statement inside another loop statement. That is why nested loops are also called “loop inside loops“. We can define any number of loops inside another loop.