...
Both, Java and Python allow to use one loop inside another loop. Following section shows few examples to illustrate the concept.
Nested While loops
The following program uses a nested for loop to find the prime numbers from 2 to 100:
Code Block |
---|
language | java |
---|
title | Java nested loops |
---|
| // prime numbers from 2 to 100
int i = 2;
while(i < 100){
int j = 2;
while(j <= (i / j)){
if (i % j == 0) break;
j = j + 1;// or j++;
}
if (j > i/j) System.out.println(i + " is prime");
i = i + 1; // or i++;
}
System.out.println("Good bye!"); |
| Code Block |
---|
language | py |
---|
title | Python nested loops |
---|
| # prime numbers from 2 to 100
i = 2
while(i < 100):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print i, " is prime"
i = i + 1
print "Good bye!" |
|
Nested for loops
You can often use for-loops to make code easier to read. The following code with nested for-loops prints...
...