Java Notes‎ > ‎

for loop

The discussion below uses the following Multiplication Tables Examples:

The for loop gives us the same functionality as a while loop, with a more convenient way to keep track of loop counting variables. The general format is:

for (initialize; endingCondition; postLoopUpdate) {
	action;
}

The initialize code is performed the first time only. Then endingCondition is checked. If it is true, the action(s) inside the loop are exectued. After the code in the loop is executed, the postLoopUpdate code is executed. The endingCondition is again checked, and the code in the loop is again executed, and so on, until the endingCondition is false.

Multiplication Tables Examples

Before studying the following examples make sure you understand basic input (using Scanner) and output (using System.out.print() )

Consider the following examples. The first one shows how to display a multiplication list for a single number. For instance, selecting 2 would then display in a row the values 2 4 6 8 10 ... and so on up to 24, which is 2 times 12. Using a while loop, this looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/* multiplicationTableUsingWhile.java
 *     Display a multiplication table from 1-12 for some number
 * Output:
 *     Please enter the base: 2
 *     2 4 6 8 10 12 14 16 18 20 22 24 
 */
import java.util.Scanner;

public class multiplicationTableUsingWhile
{
	public static void main(String[] args)
	{
		Scanner keyboard = new Scanner( System.in);
		int base,counter;

		System.out.print("Please enter the base: ");
		base = keyboard.nextInt();

		//Now display the output
		counter=1;
		while (counter <= 12) {
			System.out.print(counter * base + " ");
			counter++;
		}
	}//end main()
	
}//end class            

Note that we must declare a counter (line 14), initialize it (line 20), check the ending condition for the loop (line 21) and increment the counter (line 23).  The equivalent using a for loop instead of a while loop is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* multiplicationTableUsingFor.java
 *     Display a multiplication table from 1-12 for some number
 * Output:
 *     Please enter the base: 2
 *     2 4 6 8 10 12 14 16 18 20 22 24 
 */
import java.util.Scanner;

public class multiplicationTableUsingFor
{
	public static void main(String[] args)
	{
		Scanner keyboard = new Scanner( System.in);
		int base;

		System.out.print("Please enter the base: ");
		base = keyboard.nextInt();

		//Now display the output
		for( int counter=1; counter <= 12; counter++) {
			System.out.print(counter * base + " ");
		}
	}//end main()
	
}//end class      

In this version the counter declaration, initialization, ending condition check and counter update are all done in one place in the for loop on line 20.  The version below takes this an additional step, using a starting and ending number:

/* multiplicationTableStartStop.java
 *     Display a multiplication table from some start value to some end value for some base.
 * Output:
 *     Please enter the base, start and stop values: 2 4 8
 *     8 10 12 14 16 
 */
import java.util.Scanner;

public class multiplicationTableStartStop
{
	public static void main(String[] args)
	{
		Scanner keyboard = new Scanner( System.in);
		int base, start, stop;

		System.out.print("Please enter the base, start and stop values: ");
		base = keyboard.nextInt();
		start = keyboard.nextInt();
		stop = keyboard.nextInt();

		//Now display the output
		for( int counter = start; counter <= stop; counter++) {
			System.out.print(counter * base + " ");
		}
	}//end main()
	
}//end class

The last version displays rows and columns of a full multiplication table, and allows selecting all or part of it to be computed and displayed:

/* multiplicationTableFull.java
 *     Display a multiplication table from some start value to some end value for some base.
 * Output:
		Please enter the start and end columns, start and end rows: 1 10 1 10
		1 2 3 4 5 6 7 8 9 10 
		2 4 6 8 10 12 14 16 18 20 
		3 6 9 12 15 18 21 24 27 30 
		4 8 12 16 20 24 28 32 36 40 
		5 10 15 20 25 30 35 40 45 50 
		6 12 18 24 30 36 42 48 54 60 
		7 14 21 28 35 42 49 56 63 70 
		8 16 24 32 40 48 56 64 72 80 
		9 18 27 36 45 54 63 72 81 90 
		10 20 30 40 50 60 70 80 90 100 
 */
import java.util.Scanner;

public class multiplicationTableFull
{
	public static void main(String[] args)
	{
		Scanner keyboard = new Scanner( System.in);
		int startRow, endRow, startColumn, endColumn;

		System.out.print("Please enter the start and end columns, start and end rows: ");
		startColumn = keyboard.nextInt();
		endColumn = keyboard.nextInt();
		startRow = keyboard.nextInt();
		endRow = keyboard.nextInt();

		// Now display the output.
		// The outer loop handles each row
		for( int row = startRow; row <= endRow; row++) {
			// the inner loop handles the columns on each row
			for( int column = startColumn; column <= endColumn; column++) {
				System.out.print(row * column + " ");
			}//end for( int column...
			System.out.println();	// new line of output
		}//end for( int row...
		
	}//end main()
	
}//end class
To get the output to line up nicely we can use printf rather than print.  The new output statement would be:
    System.out.printf("%4d", row * column);  // %4d is placeholder for result of the multiplication
 where the resulting table for a range of values would then look like:
Please enter the start and end columns, start and end rows: 3 12 2 12
   6   8  10  12  14  16  18  20  22  24
   9  12  15  18  21  24  27  30  33  36
  12  16  20  24  28  32  36  40  44  48
  15  20  25  30  35  40  45  50  55  60
  18  24  30  36  42  48  54  60  66  72
  21  28  35  42  49  56  63  70  77  84
  24  32  40  48  56  64  72  80  88  96
  27  36  45  54  63  72  81  90  99 108
  30  40  50  60  70  80  90 100 110 120
  33  44  55  66  77  88  99 110 121 132
  36  48  60  72  84  96 108 120 132 144


[CS Dept] [UIC] [Prof. Reed]

Comments