Main content
AP®︎/College Computer Science Principles
Conditional repetition of instructions
Sometimes we don't know how many times we want to repeat an instruction, but we do know that we want to stop it when a certain condition is true. In a case like that, programmers repeat code using a programming construct like the while loop.
The while loop
This is the general template of a
while
loop in the JavaScript language:while ( <condition> ) {
<instructions>
}
While the
<condition>
is true, the computer keeps repeating the <instructions>
. Conceptually, a
while
loop is very similar to an if
conditional, except that a while
is continually executed until it's no longer true and an if
is only executed once. We sometimes visualize a
while
loop using flow charts, similar to how we visualize conditionals:Let's see a simple
while
loop:var i = 1;
while (i <= 10) {
println(i);
i++;
}
That code will print out the numbers 1 to 10, and then once
i
becomes 11 and is thus no longer less than or equal to 10, the computer will stop printing out the value of i
.This example is simple but is also very similar to all uses of
while
loops. Our code often starts off by initializing a variable (or more than one) before the while
, then references that variable (or a related one) in the condition, and then modifies that variable in some way in the instructions. This particular
while
loop example would typically be programmed as a for
loop, since we know ahead of time how often we want the code to repeat. There are many times when we don't know an exact number of times to repeat the code. Let's explore one of those now.The rabbit reproducer
Imagine that a farmer decides to raise rabbits, but she's worried that the rabbits will reproduce too quickly. The farmer only has room for 100 rabbits and wants to know much time will pass before her 2 rabbits become too many rabbits for the pen.
We can build a program that continually simulates rabbits reproducing as long as the population is under 100 and keeps track of how many years it takes.
Here's a first draft of that program:
var numRabbits = 2;
var numYears = 0;
while (numRabbits <= 100) {
numRabbits += (numRabbits/2 * 30);
numYears++;
}
This program starts off by initializing the rabbit population to 2 (a mating pair) and the number of years passed to 0. The
while
loop checks if the number of rabbits is less than 100. As long as that condition is true, the code inside the loop increments the number of rabbits (according to an estimate of how many babies the females can have each year), and then increments the number of years.After running the program, we can see that it's estimated to only take 2 years, and after those 2 years, there will be 512 rabbits. Yeesh! The farmer better build a bigger pen or consider some cute furry sheep.
✏️ We can also combine
while
loops with our other programming skills. The program below is a more advanced rabbit reproducer that uses a nested for
loop and an if
to randomly decide whether a rabbit has a female or a male baby. Play around with it and see how the numbers change each time!Beware the infinite loop
The computer will only exit a loop once the condition inside the
while
loop is false. But what if it never becomes false? Take a look at the program below:
var i = 0;
while (i < 100) {
println("It's the loop that never ends.");
println("Oh yes, it goes on and on, my friends…");
println("A computer started running it, not knowing what it was...");
println("And it will continue running it forever just because...");
}
What do you think will happen? Try it yourself! No, wait, don't! That's an infinite loop right there, and it's hard to know how a computer will handle it. We try to detect and prevent infinite loops in the KA programming environment—but we don't always succeed—so it's best to avoid them.
Why is that loop infinite? The program starts by initializing
i
to 0 and the while
loop checks if i
is less than 100. While that's true, it displays the lyrics to a rather catchy song. Nothing inside the loop ever changes the value of i
, so that condition will be true forever.You will likely program at least one infinite loop in your journey as a programmer. When you do find yourself staring at a long stream of output while listening to an increasingly loud computer fan, you can celebrate the milestone of your first infinite loop. After you're done celebrating (and nursing your computer back to health), you can take note of what not to do in the future. 😉
Conditional loops in pseudo-code
The AP CSP exam pseudocode does not include a
while
loop, but instead includes a construct that's very similar: REPEAT UNTIL
.REPEAT UNTIL (condition)
{
<instructions>
}
This code will repeat the instructions until the condition is finally true.
To port from a
while
to a REPEAT UNTIL
, we typically just need to invert the condition.Here's a port of the simple loop that displays the numbers 1 to 10:
i ← 1
REPEAT UNTIL (i ≥ 11)
{
DISPLAY(i)
i ← i + 1
}
When it was a
while
, we checked whether i
was less than or equal to 10. Now that we're using UNTIL
, we check whether i
is greater than or equal to 11. In this case, we could even simplify that to just checking if it's equal to 11, since there's no way for i
to become greater than 11 in this code.Let's see the rabbit reproducer in pseudocode now:
numRabbits ← 2
numYears ← 0
REPEAT UNTIL (numRabbits > 100)
{
numRabbits ← numRabbits + (numRabbits/2 * 30)
numYears ← numYears + 1
}
With the while loop, our condition checked for
numRabbits <= 100
. Now that we're using UNTIL
, we're checking that numRabbits > 100
.🙋🏽🙋🏻♀️🙋🏿♂️Do you have any questions about this topic? We'd love to answer— just ask in the questions area below!
Want to join the conversation?
- "The computer will only exit a loop once the condition inside the while loop is false. But what if it never becomes true?"
Shouldn't it say "But what if it never becomes false?"? An infinite loop occurs when the computer can't exit the loop, which would only happen if the condition never became false.(14 votes)- You are right, an infinite loop only occurs when the condition never becomes false. If the condition never becomes true, the code will never run. That's just a typo in the lesson.
Hope this helps! :)(5 votes)
- Hello,
What does this code mean: "for (var i = 0; i < numFemales * 30; i++)"? Why is our i, repetition number, depending on the number of females times 30? Won't i always be less than this number anyway?
Thank you so much!(4 votes)- Basically it's telling the computer to run the code inside the for loop 30 times for each female (because each female gives birth to 30 babies each year).
Hope that helps!(3 votes)
- var numRabbits = 2;
var numYears = 0;
while (numRabbits <= 100) {
numRabbits += (numRabbits/2 * 30);
numYears++;
}
println(numRabbits);
println(numYears);
i am confused;
(numRabbits/2 * 30); in this line where came from /2 or *30 and
println(numYears); 2 how? any one can explain to me?(2 votes)- I just saw a comment, it said "In "numRabbits/2 * 30" we divide by 2 because we need a pair of rabbits (both a male and a female) to produce offspring, and we are multiplying by 30 because we are having each pair produce 30 babies." (not my comment)(1 vote)
- When it says "The farmer only has room for 100 rabbits and wants to know much time will pass...", shouldn't it be "The farmer only has room for 100 rabbits and wants to know how much time will pass", or I'm I missing something here?(0 votes)
- https://www.khanacademy.org/computing/ap-computer-science-principles/programming-101/repetition-with-loops/a/conditional-repetition-of-instructions
In both "while" and "repeat until" you should stop the loop earlier, at least to: while numRabits < 100. Reason: when there are exactly 100 rabbits, that's all the pen can fit.(0 votes) - There should be a check for the initial value of
var numMales
to be a positive integer greater than zero. If you set it to zero, the program still runs. If you set thevar numFemales
to zero, the program crashes.(0 votes) - In the rabbit reproducer code, the condition inside function while is (numFemales + numMales)<100
Why can the result exceed that number?(0 votes)- Loop exits if it exceeds the value of 100,
No matter if it was 101 or 200 it exceed it.
as shown in while loop code adds babies to numMale and female and that how loop exit when it surpaassed 200 - My understanding(1 vote)
- When we use the "math.random" in our code it gives us the different results for each time while we run it, how is it acceptable?
For example, if we need the exact number of males and females to schedule something, What should we do?(0 votes)- If you need an exact number, why would you use random? The whole point of random is to not make something exact. You want it to change every time it is used. So, this does not make sense if you want an exact number.(0 votes)
- Hello, I would like to know why we multiply with 30(for i in range (0, num_females*30).
And then also "while (numRabbits <= 100) {
numRabbits += (numRabbits/2 * 30);"
how to get this formula (numRabbits/2 * 30)?(0 votes)- In "numRabbits/2 * 30" we divide by 2 because we need a pair of rabbits (both a male and a female) to produce offspring, and we are multiplying by 30 because we are having each pair produce 30 babies.(0 votes)
- I am wondering why should we put the code " for (var i = 0; i < numFemales * 30; i++)" there, would there be any difference if we just delete this line of code? Thank you in advance for answering this question.(0 votes)
- Yes, deleting "for (var i = 0; i < numFemales * 30; i++)" would change how the code functions. Without that line, the program would only make one new baby rabbit each year, regardless of the number of female rabbits.(0 votes)