+ 1
How do nested for loops work?
6 Answers
+ 3
Which language?
One example would be a two-dimensional array, which is filled with data.
The first loop goes through the first index and the second loop goes through the second index.
Something like this:
FOR (START; END; INCREMENT)
FOR (START; END; INCREMENT)
... some code ...
END FOR
END FOR
Here is an example to fill a two-dimensional array with numbers in Javascript:
for (let i=0; i<8; i++) {
for (let j=0; j<8; j++) {
arr[i][j] = i + "-" + j;
}
}
+ 1
Basically like numbers.
Try this (example in Python):
for i in range(10):
for j in range(10):
print(str(i)+str(j))
+ 1
I prefer the example with js or c++
+ 1
To illustrate:
while(true){
while(true){
while(true){
std::cout<<"hi";
}}}
is the same as:
while(true){
std::cout<<"hi";
}
this can be observed if you step through every line of code using an IDE such as Visual Studio.
0
In c++:
for(int i=0;i<9;i++){
for(int i=0;i<9;i++)std::cout<<i;
}
This prints: "0123456789" 10 times.
The innermost loop executes before the outer executes.