AP Computer Science Java: Lesson 3.5 Repetitive Statements - The while Loop |
|||||||||||
Here is the format: while(condition) You will probably note that a while loop looks a lot like an if statement. In fact a while loop is an if statement that can repeat. In other words, it keeps asking the question until it gets an answer of false. So as long as the condition is true, it will continue to do the list of statements. Time for an example: Suppose we want to enter an unknown number of positive integers and then find the average of those integers. We can't use a for loop because we don't know how many numbers there are. We can use a while loop though, and have a negative value represent the signal to stop entering numbers. Here is how we will do it: int number=0, sum=0, count=0; In this example, once a negative number is entered, the condition number>=0 becomes false and the loop is terminated. The computer always checks the condition first before entering the loop. If the condition is true, the loop is entered. If not, it skips to the next line of code that follows the while loop. While in Place of For If there were no for loop in Java, we could mimic its function with a well-crafted while loop. Take note of the following example: int count=1; for(count=1; count<=10; count++) System.out.println(count); Infinite Loops It is possible to write a while loop that may not stop - meaning its condition never reaches a false state. Take note of the following example: int count=1; The value of count starts at 1, then becomes 3, 5, 7, etc.... Thus count is always an odd number, making it impossible to equal 10. So the condition count!=10 will always be true. An always true condition makes this loop go on forever, causing a crash as the computer can only take so much of such nonsense! We call this phenomenon an infinite loop. |
|||||||||||
© DanShuster.com