Like IF statements loops can be nested. Actually most things in Java can be nested! Let us consider a classic algorithim called bubble sort -

This code will sort an array of numbers into ascending order. It does it by looping a loop! Look at the code below and the output. Notice that the inner loop will run through before the outer loop increments -

  1. int a=0;
  2. int b=0;
  3. for(System.out.println("A start"); a<3; System.out.println("A inc to " + a)){
    1. System.out.println("A run");
    2. b=0;
    3. for(System.out.println("B start"); b<3; System.out.println("B inc to " + b)){
      1. System.out.println("B run");
      2. b = b + 1;
    4. }
    5. a = a + 1;
  4. }

A start
A run
B start
B run
B inc to 1
B run
B inc to 2
B run
B inc to 3
A inc to 1
A run
B start
B run
B inc to 1
B run
B inc to 2
B run
B inc to 3
A inc to 2
A run
B start
B run
B inc to 1
B run
B inc to 2
B run
B inc to 3
A inc to 3

Notice that "B start" is called 3 times (once per itteration of the outer loop) while "A start" is only called once. The inner most code block will run A * B times where A and B are the amount of itterations of the inner or outer loop.

Going back to bubble sort, the inner code will run aproximatly N^2 where N is the size of the array.

next summary >>

 

 

 
Basics
Menu
Search