If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

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:
Flowchart that starts with diamond that says "condition". Arrow labeled "TRUE" goes from diamond to rectangle that says "instructions". Arrow labeled "FALSE" goes from diamond to rectangle that says "exit loop". Unlabeled arrow goes from "instructions" rectangle back to "condition" diamond.
Let's see a simple while loop:
var i = 1;
while (i <= 10) {
    println(i);
    i++;
}
📝 See similar code in: App Lab | Snap | Python
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++;
}
📝 See similar code in: App Lab | Snap | Python
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!
📝 See similar code in: App Lab | Snap | Python

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. 😉
Check your understanding
See if you can spot the infinite loops. Which of these programs has one?
Choose all answers that apply:

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?

  • spunky sam blue style avatar for user mayakotek
    "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.
    (17 votes)
    Default Khan Academy avatar avatar for user
  • leaf red style avatar for user layaz7717
    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!
    (5 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user Niraj Chaudhary
    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?
    (3 votes)
    Default Khan Academy avatar avatar for user
    • blobby green style avatar for user ARMY_7
      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)
      (2 votes)
  • leaf green style avatar for user Coach Yarbrough
    Under the Conditional Loops in Pseudo-code Section, I think there is a typo.

    It says:
    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.

    However, inverting I less than or equal to 10 is to make i greater than 11 - not greater than or equal to.

    Also, just wondering... for a case where i increments by one, we could just pseudocode UNTIL i = 11. In other words, we could exit the loop at the first instance where it's false and don't have to mention all instances where it's false.

    Is that right?
    (1 vote)
    Default Khan Academy avatar avatar for user
    • starky ultimate style avatar for user KLaudano
      The article is correct; it is not a typo. If we invert "less than or equal to 10" we get "greater than 10". Assuming we are dealing with only integers, "greater than 10" is equivalent to "greater than or equal to 11".

      Yes, if you are incrementing by 1, you could stop the loop when i equals 11. In theory, this would work. However, there are a couple of reasons you would still want to check if i is greater than or equal to 11. First, if you later change the amount i is incremented by, it would skip from 10 to a number greater than 11, and the loop will never stop. Second, if you are using floating point numbers (non-integers), it may not equal exactly 11 due to the limited precision of floating point representations. Since it takes no additional effort to check whether i is "greater than or equal to 11" vs "equal to 11", it is better to include the "greater than" in the condition.
      (3 votes)
  • blobby green style avatar for user sharadkajva
    In a Rabbit program, line 4, when I increase/Decrease the space between 100 and ) the answer changes. Why?? Weird??
    (1 vote)
    Default Khan Academy avatar avatar for user
    • blobby green style avatar for user luke.wang
      The program re-runs the code after every time you change something in it (adding a space, adding println, etc). Since there's a random chance for each rabbit to be either male or female, the output will also be random. Every time you change something in the code (doesn't have to be line 4) you're running it again, so you're guaranteed to get a changed answer.
      (2 votes)
  • leaf green style avatar for user Maria Litvin
    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.
    (1 vote)
    Default Khan Academy avatar avatar for user
  • male robot donald style avatar for user fly6guys
    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)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user cldmitry
    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 the var numFemales to zero, the program crashes.
    (0 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user Khanh Tran
    In the rabbit reproducer code, the condition inside function while is (numFemales + numMales)<100
    Why can the result exceed that number?
    (0 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user Mahroo2010
    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)
    Default Khan Academy avatar avatar for user
    • orange juice squid orange style avatar for user Schuck
      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)