While
A while
loop is a command in computer programming that executes another set of commands repeatedly until a certain condition is met. The while
loop and the for
loop are often called control statements because they control the flow of the program.
A simple example of a while loop would be a simple counter. If you wanted to have a program count from 1 to 10, you might write something like this (this code is in Python):
1 2 3 4 |
|
This code will start with the counter equal to 1. The condition of the while
loop is that the counter must be less than or equal to 10 to execute the code within the while
loop. Initially this condition is met, so the code is executed. The counter is printed and then the counter is increased by 1, and the while
loop continues. The while
loop will only stop once the condition stops being met. In this case, after the \(10^\text{th}\) iteration of the while
loop, the counter is increased to 11, so the condition is no longer met, and the while
loop stops. The specific condition of the while
loop is known as a halting condition since it "halts" the loop.
Though the above example has a determined number of steps, while
loops are often used when the number of steps is not known beforehand. Suppose we want a simple app to measure the physiological response time of users. The goal is for the user to press a button twice, and the program will record the time elapsed between the button pushed. The program could work by having the first push of a button initiate a while
loop. Inside the loop, a counter will start like the one above and then measures the elapsed time. The halting condition could be when the second button press occurs. In this way, the loop would count how long it ran between button pushes, and thus the response time.
Contents
While Loop Overview
While Loop
A while loop operation is a process which repeats steps incessantly under a well-defined condition, the halting condition, until the condition fails to hold.
The halting condition of a while loop is a boolean statement that invokes Boolean logic. These statements make an assertion that is either true or false. If the statement is true, the while loop proceeds. If it is not, the while loop does not and the program continues execution below the while loop.
Unlike for loops, the while loop declaration does not initialize any variables for the loop. It simply defines the halting condition. Any changes to the variables must take place inside of the loop code.
Halting conditions can also be concatenations of Boolean statements. For example, the following while loop is valid in Python:
1 2 3 4 5 6 7 |
|
For this while loop, there are really two halting conditions. If lower_counter
ever gets above 14, or if upper_counter
ever gets below 9, the while loop will stop.
Before a while
loop is run in any language, the program checks the condition first to see whether it is true or not. If it is true it will execute the steps in the while
loop, and then return to the condition. If the condition is still true, it will again execute the body of the while
loop. This will continue until the condition becomes False
, at which point the while
loop will be terminated.
For Loops vs While Loops
for
loops are very similar to while loops. They both define a block of code to be run a repeated amount of times. However, there are few main differences between the two.
The number of times a for
loop iterates is well defined. That means that before the code even runs, we know how many times the loop will execute. while
loops, on the other hand, can run indefinitely.
while
loops do not have a loop control variable like for
loops do. This makes sense because the loop control variable defines the number of times the loop's code will execute, and that number is not well defined for while
loops.
The halting condition for for
loops and while
loops do similar things. They both are evaluated using a Boolean statement. When that halting condition is met, the loop stops executing.
As an example, here are two loops in Python that do the same thing. They print out all of the numbers between 1 and 100 that are divisible by 7.
for
loop
1 2 3 |
|
while
loop
1 2 3 4 |
|
These loops look very similar, but a variable, x
, was needed in the while
loop to facilitate the halting condition. For this example, for
loops are more appropriate.
Infinite Loops
While loops have the interesting and dangerous property that they can run forever! This is not good, and in computer science it is called an infinite loop. The following example shows an infinite loop in Python:
1 2 3 |
|
The code inside of the while loop does not modify the variable counter
, so the halting condition will never evaluate to false. This loop will run forever (or until the program is stopped).
Infinite loops cause headaches for programmers and users alike because the program itself can never move forward. It's a little like watching the loading sign on your computer spin (although that will probably stop at some point). The program can never reach the code after the while loop because it's preoccupied with the code inside the while loop. As a programmer, it is very important to avoid infinite loops.
While Loop Examples
Add 'em up
Suppose you want to compute the sum from 1 to any natural number \(n\in\mathbb{N}\). You will have to add all of the numbers from the range \(\left[1,10\right]\) to the sum in every step until you reach \(n\).
1 2 3 4 5 6sum = 0 counter = 1 while counter <= n: sum += counter counter = counter + 1
Investing 101
Assume that you have $5000 and you want to invest it. The bank offers you a 10% interest annually.
- Write a function that calculates your new balance after 3 years.
- Write another function that tells you how many years do you have to wait to get $10,000.
Example solution for finding the new balance in Python:
1 2 3 4 5 6def find_balance(years, interest_rate, balance): counter = 1 while counter <= year: balance += balance * interest_rate counter += 1 print "Your balance after %d years will be %d dollars" % (years, balance)
Example solution for finding the time to maturity in Python:
1 2 3 4 5 6def find_time(interest_rate, balance, target_balance): years = 0 while balance < target_balance: balance += balance * interest_rate years += 1 print "Your balance will reach %d after %d years" % (target_balance, years)
While Loop in Various Languages
The while loop can take on different syntax from language to language. Here are some examples of a while loop in popular languages. All of these while loops do the same thing in their respective languages.
Python
1 2 3 |
|
Java
1 2 3 4 |
|
C and C++
1 2 3 4 |
|
Note: Go does not have while loops or do while loops. To make one of your own, you need to use for loops.
Do While Loop
As stated above, the halting condition is executed first when the program initially comes to the while loop. So, this code will have the following output (it is in JavaScript because Python does not have a do while loop):
1 2 |
|
However, there is another similar control flow command called a do while loop. The do while loop will evaluate the halting condition at the bottom of the while loop code. This means that the code will execute at least once before terminating.
1 2 3 4 |
|
The do while loop can often be circumvented by altering your halting condition, but it is still an option in some languages.
Control Statements in a While Loop
Sometimes it will be necessary to break or change the execution of the while loop early. Each language has its own ways of doing so. In Python, you can break, or stop, the execution of the code with the break
statement.
1 2 3 4 5 6 |
|
This will stop the while loop.
You can also decide to skip part of the loop code and go right to the next iteration of the loop using the continue
statement. For example,
1 2 3 4 5 6 |
|
In this code, the variable counter
will increase by 2 until it gets above 10, at which point it will only increase by 1 until it hits 20 and the loop terminates.
Exercises with While Loops
- Write some code that will take in an array whose length is greater than or equal to 5. Using a while loop, return an array that contains the first 5 elements of the input array.
In Python, an answer to this might look like this.
1 2 3 4 5 6 7def while_loop_answer(A): answer = [] index = 0 while len(answer) != 5: answer.append(A[0]) index += 1 return answer
References
- A, D. Wikipedia While Loop. Retrieved June 7, 2016, from https://en.wikipedia.org/wiki/While_loop