To appreciate the value of loops, take a look at the following example. This program will calculate the average of 10 numbers input by the user. Without a loop, the three lines of code that prompt the user for input, get the input, and add the input to the running sum would need to be repeated 10 times for a total of 30 lines of code. This is only for getting the input and does not include any of the other necessary lines of code. Average Ten Numbers: int sum = 0; System.out.println("Enter number: "); number = keyboard.nextint(); sum = sum + number; System.out.println("Enter number: "); number = keyboard.nextint(); sum = sum + number; //...[ 28 statements deleted ]... System.out.println("Enter number: "); number = keyboard.nextint(); sum = sum + number;... average = sum / 10; The following code example has exactly the same functionality as the previous example; however, it only uses three lines of code to accomplish the same task. The code begins with i equal to 0. While i is less than 0, the code block within the brackets runs. With each iteration of the code, i is incremented by 1 (i ++ is shorthand for I equals I plus 1). The code will be repeated unit i equals 9 (10 times). Once i equals 10, the loop test is false. Ten is not less than 10. When the test is false, the code moves to the next 1
line following the loop block. In this example, the next line run is average = sum / 10; for (i=0; i<10; i++) System.out.println("Enter number: ); number = keyboard.nextint(); sum = sum + number; } average = sum / 10; Using a looping structure is more efficient and less prone to errors created by having to repeat lines of code over and over again. The While Loop Following is the basic structure of the while loop. Within the parentheses following the keyword while is an expression that evaluates to true or false. The lines of code that should be repeated are enclosed in curly brackets. while( loop-test ) //answer is true or false, repeats on True //Statements to be repeated }f Here is the flowchart for the while loop. The loop test expression is entered in a diamond or decision shape. From the true exit path are the steps that are to be repeated as part of the loop. After the steps are processed, the loop test is repeated. The false path leads to the lines of code, and the program continues. 2
In the following example, n equals the number of intended iterations. It is essential that this variable have a starting value before the loop test is encountered the first time. Counter is given a starting value of 1. While counter is less than or equal to n, the code in the brackets will run. The first time this test is processed, counter has the value of 1, and n has the value of 6. The user will be asked to enter a number. The input number is added to the running sum, then the counter is incremented by 1. The counter must be incremented to move the loop one step closer to termination. The condition is tested again. Counter is now 2. Two is less than 10, so the loop is run again. Eventually, the counter will become 11. Eleven is not less than or equal to n. The loop will stop, and the program will continue with the next line of code following the loop block. 3
(Answer: This code will display 1, 2, 3, and 4 each on its own line) Do-While Loop This is the basic structure for the do-while loop. Notice the loop test is at the bottom following the block of code. The code will always be run at least once 4
with a do-while loop because the code is run before the condition is tested. do iterative-part } while ( loop-test ) ; The flowchart for the do-while is very similar to the while flowchart, except the steps are listed before the loop test. In the following code example, a menu is displayed to the user. The do-while loop is used here because the menu should always be displayed at least once. Based on the user s choice, it may be displayed again. This loop is used for error handling. If the user does not enter one of the offered choices, the menu is displayed again, and the user is given another opportunity to enter 5
an appropriate choice. public char MenuOptionSelection() Scanner keyboard = new Scanner(System.in); char Option = ; do System.out.println("Enter N)ew, O)pen, S)ave: ); Option = keyboard.nextchar(); } while (Option!= 'N' && Option!= 'O' && Option!= 'S'); return Option; } For Loop The for loop structure consists of a start, a test, an action, and the code block of statements to be repeated. When the for loop is executed, the initial statement is executed. The loop test is then executed. If the loop test is false, the loop is terminated. If the loop test is true, the code block is executed, then the action is processed. The test is then executed again. for( start; test; action) //the for loop statements to be repeated 6
} Following is the general flowchart for the for loop. The initial statement is processed only once and before the loop test is encountered. Following the loop test, the true path includes the code block and the repeated statement or action. The false path continues the program. In the following example, the user is prompted for the number of iterations to be performed and sum is initialized to zero. When the for loop is first encountered, a counter variable is declared and given the starting value of 0. Counter is then compared to n as the loop test. Assuming the user entered a number greater than 0, the user will be prompted to enter a number that is stored in the variable Value. Value is added to the running sum. The action is then performed: Counter is increased by 1, and the new value is stored in counter. The condition is then tested again. Counter, which is now one higher, is compared to n. As long as it is still less than n, the user is again asked to enter a number that is added to the running sum. Counter is again increased by one before the condition is tested again. Once counter is not less than n, the loop terminates. The next lines of code to be executed 7
calculate the average and output it to the screen. //Example of a for loop that produce an average of user-supplied values: Infinite Loops One of the most important steps in loop design is bringing the loop one step closer to termination. This must be included to avoid an infinite loop-a-loop that never terminates. Examples include incrementing a counter by 1 or using 8
a decision within the code block to set the loop condition to false. The final step in designing a loop is to prime for the initial test as necessary. This means making sure all variables used in the loop test have valid data before the test is performed. In the following example, the variables j and n need to be initialized before the loop is executed: i nt j; int n; float x; float sum; while(j <= n) System.out.println( Enter a number: ); x = keyboard.nextint(); sum = sum + j; j++ } An infinite loop is one that never terminates. In the example, below the output "Do we ever get here?" will never be printed. Counter is not changed in the code block. J is incremented, but j is not used in the loop test. The only way to terminate an infinite loop is Control-Alt-Delete and end the task. int counter = 1; 9
int j = 0; int n = 3; while(counter <= n) j = j + 1; System.out.println(counter); } System.out.println("Do we ever get here? ); The following code example is another example of producing an endless loop: int Count = 1; while(count > 0) System.out.println( Enter your answer ); Ans = keyboard.nextint(); Count++; } For each of the following code examples, study the code and determine what the output is or what the code is supposed to be doing. The answers are at the end of the document. 10
11
12
13