4.1 while Loops
while
loops are a way to change the flow of control by repeating a block of code so long as some condition remains true. The condition is written in the form of a boolean expression.
The basic structure of a while loop is shown below.
As long as the boolean expression remains true, code within the while loop will be executed. The moment that the boolean expression becomes false, code outside of the while loop will be executed; the loop is done. This behavior can be summarized in the following flowchart below:
Notice in the example above that the boolean expression evaluates before the loop executes each time, including the first time. It is possible that the condition is false initially and the loop body is never executed.
Here is a basic example of a countdown.
You first declare a variable i
and set it equal to 5. Before the while
loop, you print out a message letting the user know that the countdown is about to begin. Your while
loop starts by checking to see if the boolean expression, i >= 0
, is true
. The current value of i
is 5. 5 >= 0
is true
, so the code within the while loop gets executed. It prints out the number 5 and then decrements it by subtracting 1.
i
is now set to 4. Our while
loop then checks to see if 4 >= 0
. Since this condition is still true
, the code within the while
loop gets executed again. This will continue until i
gets down to 0. After 0 gets printed to the screen, you decrement i
so that it is now set to -1. Your while
loop tests to see if -1 >= 0
. Since -1 is not greater than or equal to 0, the boolean expression is false.
The code within the while loop is skipped. The while
loop has finished its execution.
After you run the above program, this is what gets printed to the screen:
You must exercise caution when using while loops to avoid the dreaded infinite loop. An infinite loop is a loop that always evaluates to true
and therefore, never terminates. It never finishes its execution. It will continue to repeat until the end of time! Infinite loops will often cause a program to freeze and crash.
The countdown program above has been rewritten below, but it is missing an essential line of code. This will cause an infinite loop:
But why? Why does this cause an infinite loop?
With the omission of i--
, you are no longer changing our variable. i
will forever be set to 5. Our while
loop will repeatedly check to see if 5 >= 0. Since this condition is always true
, the code within the while
loop body will execute forever. The while
loop will never terminate.
Your program will just keep printing a value of 5 over and over again. Thus, after running the program, your output will look something like this (assuming the browser does not freeze and crash):
[NOTE: This will continue printing “5…” forever!]
In the CodeHS editor, you can manually stop the program by clicking on the “STOP” button next to the “RUN CODE” button. Otherwise, it will continue spamming the number 5 at us until the end of time.
One way to break out of a loop, infinite or otherwise is to execute a return statement. If a while loop is set up to run in a method and a return statement is placed inside the while
loop, executing the return statement will return the program to the original calling point, thus exiting the loop.
Here is an example:
In the example above, notice that you potentially have an infinite loop since true
will always evaluate to true
. The loop will not continue forever though. Once sum
is greater than num
the return statement will execute and exit the loop and the method.
As you start writing more and more programs, you will find many applications of while
loops. You saw one application above where the while
loop was used to sum numbers. Similar loops can be used to calculate average, mode, minimum, or maximum for a set of numbers.
Another application that is typically used with a while
loop is to split out individual digits of a number. Here is an example of a loop that can do that.
In the example above, notice how you can use mod and division to separate out each digit. If you start with the number 345, mod 10 returns the 5. When you then use integer division and divide 345 by 10, you get 34. Since 34 is greater than 0, the while loop executes again. Now the mod function splits off 4 and the division function reduces the number to 3. The program then enters the while
loop again, printing out 3. When it divides 3 by 10, it gets zero. Now zero is no longer greater than 0, so the loop is complete.
Other uses of while
loops include identifying if an integer is or is not evenly divisible by another integer and determining the frequency with which a specific criterion is met.
-
Incorrect
Correct
No Answer was selected
Invalid Answer
What will this
while
loop do?
Write a program that has a user guess a secret number between 1 and 100.
Store the secret number in a variable called secretNumber
and allow the user to continually input numbers until they correctly guess what secretNumber
is.
Complete the method guessMyNumber
that uses a while loop to ask the user for their guess and compares it againist secretNumber.
For example, if secretNumber
was 16, an example run of the program may look like this:
Note: In order to pass the test cases, you must set the secretNumber
to 16.