You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

nested loop is a (inner) loop that appears in the loop body of another (outer) loop. The inner or outer loop can be any type: whiledo while, or for. For example, the inner loop can be a while loop while an outer loop can be a for loop. Of course, they can be the same kind of loops too.

Both, Java and Python allow to use one loop inside another loop. Following section shows few examples to illustrate the concept.

Example

The following program uses a nested for loop to find the prime numbers from 2 to 100:

Java nested loops
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!");
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!"
  • No labels