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

Jeżeli jesteś za filtrem sieci web, prosimy, upewnij się, że domeny *.kastatic.org i *.kasandbox.org są odblokowane.

Główna zawartość

Warunkowe powtórzenia instrukcji

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 true?
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. 😉
Sprawdź swoją wiedzę
See if you can spot the infinite loops. Which of these programs has one?
Zaznacz wszystkie odpowiedzi, które pasują:

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.

Chcesz dołączyć do dyskusji?

Na razie brak głosów w dyskusji
Rozumiesz angielski? Kliknij tutaj, aby zobaczyć więcej dyskusji na angielskiej wersji strony Khan Academy.