0
Nested Loops
Could you please explain me how nested loops in c++ work? I just can't comprehend it myself. Providing examples would be much appreciated
3 Réponses
+ 2
Nested loop is a loop inside another loop
Example. This uses nested loop to find prime numbers from 2-100
#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
#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(j > (i/j)) cout << i << " is prime\n";
}
return 0;
}
Sorry for a scatters code
0
Thank you!