Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Both, Java and Python allow to use one loop inside another loop. Following section shows a 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
languagejava
titleJava 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
languagepy
titlePython 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...

...