A nested for loop is a for loop that is contained within another for loop. Nested for loops are used to execute a block of code repeatedly, within multiple iterations.
Here is an example of a nested for loop in C:
#include <stdio.h>
int main() {
int i, j;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
printf("%d, %d ", i, j);
}
printf("\n");
}
return 0;
}
In this example, the outer for loop iterates 10 times, from 0 to 9. The inner for loop also iterates 10 times, from 0 to 9. The combination of these two loops results in 100 iterations of the code inside the loops. The output of this code is a grid of 10 rows and 10 columns, with the values of i and j printed in each cell.
You can use a nested for loop to perform operations on two-dimensional arrays, as well. Here is an example:
#include <stdio.h>
int main() {
int array[10][10] = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
{20, 21, 22, 23, 24, 25, 26, 27, 28, 29},
{30, 31, 32, 33, 34, 35, 36, 37, 38, 39},
{40, 41, 42, 43, 44, 45, 46, 47, 48, 49},
{50, 51, 52, 53, 54, 55, 56, 57, 58, 59},
{60, 61, 62, 63, 64, 65, 66, 67, 68, 69},
{70, 71, 72, 73, 74, 75, 76, 77, 78, 79},
{80, 81, 82, 83, 84, 85, 86, 87, 88, 89},
{90, 91, 92, 93, 94, 95, 96, 97, 98, 99}};
int i, j;
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
return 0;
}
In this example, the nested for loop iterates through the elements of the two-dimensional array, and prints out the values. The output of this code is a grid of 10 rows and 10 columns, with the values of the array printed in each cell.
You can use a nested for loop to perform operations on strings, as well. Here is an example:
#include <stdio.h>
#include <string.h>
int main() {
char str[10][10] = {"Hello", "World", "Goodbye", "Earth", "Moon",
"Sun", "Galaxy", "Universe", "Star", "Nebula"};
int i, j;
for (i = 0; i < 10; i++) {
for (j = 0; j < strlen(str[i]); j++) {
printf("%c", str[i][
...