]

Loop Tracing Examples - Nested Loops


Two independent loops - a while loop and a for loop.

Of note is that the first loop (the while loop) must complete its full set of iterations before the for loop begins execution. After the for loop completes its set of iterations the program ends.

Code

                        
public class LoopExercise
{
	public static void main(String [] args)
	{
		int n = -3;
		int q = -3;
		
		while(n < 3)
		{
			System.out.println("n = " + n);
			n++;
		}
		
		for(q = -3; q < 3; q++)
			System.out.println("q = " + q);
	}
}
  

Output

This second program uses the same two loops as Example 1. Of note is that the for loop is now nested within the while loop. In this case the for loop will perform its entire set of each iterations for every single iteration of the while loop.

Code

                        
public class LoopExerciseNested1
{
	public static void main(String [] args)
	{
		int n = -3;
		int q = -3;
		
		while(n < 3)
		{
			System.out.println("n = " + n);
			n++;
		
			for(q = -3; q < 3; q++)
				System.out.println("q = " + q);
			
		}
	}
}
  

Output

For a more tangible example of the relationship between nested loops, one may wish to consider the second, minute and hour hands of a clock. The second hand makes sixty revolutions (iterations) for each change in value of the minute hand. Consequently, the minute hand makes sixty revolutions (iterations) for each change in value of the hour hand. It is of interest to note that it takes 60 * 60 iterations between the second and minute hands for a single change in value of the hour hand. A JAVA code example simulating the second and minute hands of a clock can be seen below.

Code

                        
public class LoopExerciseNested2
{
	public static void main(String [] args)
	{
		int secondHand = 0;
		int minuteHand = 0;
		
		while(minuteHand < 60)
		{
			System.out.println("minutes = " + minuteHand);
					
			for(secondHand = 0; secondHand < 60; secondHand++)
				System.out.println("seconds = " + secondHand);
			
			minuteHand++;
		}
	}
}
  

Output

Another example of nested loop. In this example the inner ("q") loop will perform its entire set of five iterations for each iteration of the outer ("n") loop. The System.out.println( ); statement below the inner loop will be executed after the completion of the inner loop, but before returning to the outer ("n") loop. Here the println( ) method takes no arguments. Its purpose is to provide a line break for the data displayed by the five iterations of the inner loop, resulting in a display of five rows and five columns.

It is useful to note that the output produced displays a 5 X 5 grid, or a set of five rows and five columns. Among other things, this loop structure will be valuable for processing two-dimension arrays.

Code

                        
public class LoopExerciseNested3
{
	public static void main(String [] args)
	{
		int n = 0;
		int q = 0;
		
		for(n = 1; n <= 5; n++)
		{
			for(q = 1; q <= 5; q++)
				System.out.print(q);
				
			System.out.println();
		}
	}
}
  

Output

Example 5 is based on the same looping structure as Example 4, the difference being that the inner loop condition now terminates at the current value of n found in the outer ("n") loop. Additionally, the output value is the current value of n displayed n number of times (for example, when n is 1, the value 1 is displayed one time, when n is 2, the value 2 is displayed two times, and so on).

Code

                        
public class LoopExerciseNested
{
	public static void main(String [] args)
	{
		int n = 0;
		int q = 0;
		
		for(n = 1; n <= 5; n++)
		{
			for(q = 1; q <= n; q++)
				System.out.print(n);
				
			System.out.println();
		}
	}
}
  

Output

This example is identical to Example 5 with the exception that the output variable found within the inner loop is the variable q rather than n. As a result the output data has changed from repetitive values on a given line to sequential values for each line.

Code

                        
public class LoopExerciseNestedVer2
{
	public static void main(String [] args)
	{
		int n = 0;
		int q = 0;
		
		for(n = 1; n <= 5; n++)
		{
			for(q = 1; q <= n; q++)
				System.out.print(q);
				
			System.out.println();
		}
	}
}
  

Output

Example 6 continues to use the nested loop structure of Example 5. In this case the output is derived from a relationship between the values of the outer loop and inner loop counters, specifically the result of multiplying n and q. The output result is an n by q grid that represents a multiplication table. Note that the separator placed between each output value is a tab, produced by placing the key combination \t within the output string.

Code

                        
public class LoopExerciseNested4
{
	public static void main(String [] args)
	{
		int n = 0;
		int q = 0;
		
		for(n = 1; n <= 5; n++)
		{
			for(q = 1; q <= 5; q++)
				System.out.print(n*q + "\t");
				
			System.out.println();
		}
	}
}
  

Output

Nested for loop within a while loop with expanded input and output data. Note that n is decremented not by step (for example n--), but by division.

Code

                        
   public class LoopExerciseExpandedData_1
   {
       public static void main(String[ ] args)
      {
         int n = 8;
         int i = 1;
         int j = 1;
      
         j = n + 2;
      
         System.out.println (n + " " + i + " " + j );
      
         while (n > 1)
         {
            n = n/2;
            for (i = 2; i <= n; i = i+2)
               System.out.println (n + " " + i + " " + j );
         
            j++;
         }
         System.out.println (n + " " + i + " " + j );
      }
   }
  

Output

Nested for loop within a while loop with expanded input and output data.

Code

                        
class Quiz3Problem1Sample
{
	public static void main(String[ ] args)
	{
		int n = 7;
		int i = 0;
		int j = 0;
		
		j = n + 1;
		
		System.out.println (n + " " + i + " " + j );
		
		while (n > 1)
		{
			n = n/2;
			for (i = 0; i <= n; i = i+2)
				System.out.println (n + " " + i + " " + j );
		}
		System.out.println (n + " " + i + " " + j );
	}
}
  

Output