AP Computer Science :: Lessons :: Loops
For Loops
A for loop runs a series of statements as long as its termination condition is true. A variable that can be embedded in the for loop is updated each time the loops executes. For loops are essential for situations where you need to run a series of code statements a set numbers of times.
For example, you may need to use a for loop to create an ASCII Christmas tree like the following:
\ / -->*<-- /_\ /_\_\ /_/_/_\ /_\_\_\ /_/_/_/_\ /_\_\_\_\ /_/_/_/_/_\ /_\_\_\_\_\ /_/_/_/_/_/_\ /_\_\_\_\_\_\ /_/_/_/_/_/_/_\ [___]
This is the general form of a for loop:
for (initialization; termination condition; update statement) { statements }
The termination condition determines when to stop the loop. It is tested before the statements are executed. The update statement updates the value of the loop variable and is executed after the statements in the for loop. Below are some example for loops.
// Outputs 1 2 3 4 for (i = 1; i < 5; i++) System.out.print(i + " ");
The loop variable is the variable i. Note that is doesn't have to be declared inside the loop, but it is initialized by the first statement of the loop. After the initialization step the termination condition is checked. If the statement is true the loop statements are executed. After the statements are executed the update statement runs. The termination condition is then checked again. This pattern continues until the condition evaluates as false.
// Outputs 20 19 18 17 16 15 for (int j = 20; j >= 15; j--) System.out.print(j + " ");
In this loop the loop variable j is declared inside the loop statement. This means that the variable scope will end once the loop ends. This loop also counts down instead of up showing you do not always have to use ++ in the update statement.
// Outputs 2 4 6 8 10 for (int k = 2; k <= 10; k+=2) System.out.print(k + " " );
This loop counts up by 2 showing that you do not have to increment or decrement by 1 in the update statement. In fact, you can use any valid constants variables, or expressions in the update statement and termination condition.
While Loops
A while loop is similar to a for loop, but it does not automatically update a loop variable. It simply runs while a boolean test is true. While loops should be used in situations where you are not sure how many times you need to execute the code statements in your loop.
while (test) { statements }
It is much easier to create an infinite loop using a while loop than it is with a for loop so you have to make sure the boolean test will change somehow based on the statements in the loop body. Below are some example while loops.
// Outputs 3 6 18 int i = 1, mult3 = 3; while (mult3 < 20) { System.out.print(mult3 + " "); i++; mult3 *= i; }
The boolean test of a while loop is run before the statements in the loop body. It is checked again whenever the compiler reaches the end of the loop body.
// Infinite Loop int power2 = 1; while (power2 != 20) { System.out.println(power2); power2 *= 2; }
The above while loop results in an integer overflow because the loop variable power2 can never equal 20. This shows that you can create an infinite loop even when you remember to update the loop variable.
Nested Loops
There are a number of situations in programming where you may want to place a loop within another loop, which is called a nested loop. The code below uses nested loops to output all the prime numbers in a given range. It continues to run until the user enters "-1" for the lower part of the range.
int lower = Integer.parseInt( javax.swing.JOptionPane.showInputDialog( "INPUT LOWER LIMIT (-1 to quit)","0")); while (lower != -1) { int upper = Integer.parseInt( javax.swing.JOptionPane.showInputDialog("INPUT UPPER LIMIT","0")); int i,j,innerLimit; for (i = lower; i <= upper; i++) { innerLimit = (int)Math.sqrt(i); for (j = 2; j <= innerLimit; j++) { if (i % j == 0) break; } if (j > innerLimit) System.out.println(i + " is prime"); } lower = Integer.parseInt( javax.swing.JOptionPane.showInputDialog( "INPUT LOWER LIMIT (-1 to quit)","0")); }
The while loop continues to run while the lower limit does not equal -1. This ensures the program continues to run as long as the user wants.
The first for loop starts at the lower limit of the range and goes up to the upper limit by 1s so all the numbers within the range will be checked.
The innerLimit variable takes the square root of the current number. None of the numbers above this innerLimit will evenly divide into the current number so they do not need to be checked.
The second for loop starts at 2 since it is the lowest number that would cause a number to not be prime and we count up to the innerLimit we calculated. If we find a number that divides into our current number we use the break statement to exit the second for loop.
Finally, if the j loop variable is greater than innerLimit it means we went through the entire second for loop without finding a number that could divide into our current number, which makes the current number prime. The first for loop then moves on to the next number.