0
Could someone explain me how nested for works?with an example of number maybe ,it will be so helpfull for me.
confuse about nested loops and its application
3 Antworten
+ 4
#include <iostream>
using namespace std;
int main () {
int i, j;
for(i = 2; i<100; i++) {
for(j = 2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) cout << i << " is prime\n";
}
return 0;
}
+ 2
imagine a function that creates a full row that holds place for, i dunno, polar bears.
for(int i = 0; i <10; i++)
{
create_polar_row();
/* so this one creates a row. now, i would like to put my bears into that row, so to make stuff quicker, i can do a nested loop that will put all of my bears in this particular row */
for(int j=0; j <bears.count; j++)
{
add_bear_to_row();
}
}
so by fallowing the logic of our program, you can see that at the start, i = 0, you go in, see the funcion and you create a row for bears. then, next like. you see a loop, so you start to execute it.
j = 0, add a bear,
j = 1, add a bear,
...
...
j = 9, add a bear,
leave the function. But wait! i is still less that 10! get back to the top!
i = 1
create a row for bears
enter nested loop
j = 0, add a bear,
j = 1,...
aaand so on, up to the moment when i will be 10. the nice logic with nested loops is to think of every one creating another dimension for your object, or to clearer, one creates a row, another one adds columns to that row, another nested loop inside the nested loop will create aother dimension for that!
hope it is not pretty messy and it helped at least a little