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ść

Numerowane powtórzenie instrukcji

Świat jest pełen powtórzeń: naukowiec powtarzający eksperyment 100 razy i zapisujący wyniki, ogrodnik sadzący starannie ułożone rzędy główek sałaty w odległości 5 cm od siebie, drukarka 3D wielokrotnie drukująca warstwa po warstwie.
Programy komputerowe są również pełne powtórzeń, ponieważ nasze programy automatyzują i symulują świat wokół nas. Programiści używają pętli for, aby powtórzyć zestaw instrukcji określoną liczbę razy.

Potrzeba stosowania pętli

Wyobraźmy sobie, że tworzymy program, który generuje listę wielokrotności liczby 9.
Możemy zaprogramować 13 pierwszych wielokrotności w ten sposób:
println(9 * 0);
println(9 * 1);
println(9 * 2);
println(9 * 3);
println(9 * 4);
println(9 * 5);
println(9 * 6);
println(9 * 7);
println(9 * 8);
println(9 * 9);
println(9 * 10);
println(9 * 11);
println(9 * 12);
To działa, ale to podejście ma pewne wady. Co jeśli chcemy wyświetlić pierwsze 100 wielokrotności? To kolejne 87 linii kodu! Co jeśli wtedy zdecydujemy się dodać jakiś tekst do każdego z wyświetlanych elementów? Musielibyśmy zmienić 100 linijek kodu!
Dzięki pętli for możemy nakazać komputerowi, aby powtórzył instrukcję, aby nie trzeba było jej powtarzać w kodzie.
Możemy ponownie napisać ten kod za pomocą pętli for w JavaScripcie:
for (var i = 0; i < 13; i++) {
  println(9 * i);
}
Każda pętla for zaczyna się od 3-częściowego nagłówka wewnątrz nawiasów. Nagłówek jest zgodny z tym szablonem:
for (inicjalizacja; warunek; inkrementacja/dekrementacja)
W tych częściach używana jest zmienna licznikowa. Zmienna ta śledzi aktualne powtórzenie i zazwyczaj nazywana jest i.
The initialization part initializes the counter variable to a starting value.
In this case (var i = 0), the initial value is 0, because we first display 9 multiplied by 0.
The condition part tells the computer whether to keep repeating or not. The computer evaluates the condition each time, and if the expression is true, it executes the inside instructions. If not, it exits the loop entirely.
In this case (i < 13), the condition checks whether the counter variable is less than 13, because we want our final multiple to be 12.
The increment/decrement part modifies the counter variable after each repetition.
In this case (i++), we simply want to add one to the variable, since we're stepping through the integer values of 0 to 12.
After the for loop header, there are always curly brackets with instructions for the computer to execute each time. The instructions often reference the counter variable, but not always.
✏️ The program below displays the squares of the numbers from 0 to 5. Try changing it to display more squares and display the cubes of each number instead.
📝 See similar code in: App Lab | Snap | Python

Warianty pętli

The most common loop you'll see in programming will start at 0, stop before a certain number, and increment by one each time. However, by varying the parts of the loop, we can create loops that repeat in many other ways as well.
For example, this program uses a for loop to count down from 10 to 1:
for (var i = 10; i > 0; i--) {
   println(i);
}
Notice the differences:
  • In the initialization, we set the counter variable to 10.
  • In the condition, we check whether the counter variable is greater than 0. That means the final repetition will be when the counter variable is 1, and the computer will exit the loop then.
  • In the last part, we subtract 1 from the counter variable.
Here's another example, a for loop that displays the even numbers from 0 to 20:
for (var i = 0; i <= 20; i += 2) {
    println(i);
}
This loop starts off at 0, but differs otherwise:
  • The condition checks whether the counter variable is less than or equal to 20. That means that this loop will display 20. If it was only less than, it would stop at 18.
  • The last part adds 2 to the counter variable, not 1 like usual.
The flexibility of the for loop means that we can program many kinds of repetition with it. Be warned, that flexibility also makes it easier to make mistakes! See if you can spot the mistakes in these examples.
Sprawdź swoją wiedzę
This for loop should display the numbers from 1 to 10:
for (var i = 0; i < 10; i++) {
    println(i);
}
The code isn't quite right, however.
Which of these code snippets correctly display the numbers from 1 to 10?
Zaznacz wszystkie odpowiedzi, które pasują:

Zagnieżdżone pętle

A nested loop allows us to repeat along two dimensions.
Let's explore that in a coding example. We made a multiplication table for the number 9 earlier. What if we need to learn all the other numbers from 1-10? Nested loops to the rescue!
This JavaScript code uses a nested for loop to display the multiplication tables for the numbers 1-10:
for (var i = 1; i <= 10; i++) {
  for (var j = 1; j <= 10; j++) {
    println(i * j);
  }
}
Run code | 📝 See similar code in: App Lab | Snap | Python
The outer for loop starts at 1, stops at 10, and adds 1 each time. The inner for loop does the exact same, but with a different counter variable name. The instructions display the product of the two counter variables.
It's important to understand the order that the computer executes the looped instructions. For each iteration of the outer for loop, the computer will go through 10 iterations of the inner for loop. In those first 10 iterations, the outer counter variable i will be 1 the whole time, and only the inner variable j will change, incrementing from 1 to 10.
For a more in-depth explanation, this video talks over a visualization of the computer executing the nested loop. You can play with the visualization yourself on JSTutor.
Sprawdź swoją wiedzę
In the example above, how many times will println() be called?
  • Prawidłowa odpowiedź to:
  • liczba całkowita, taka jak 6
  • właściwy uproszczony ułamek, taki jak 3/5
  • niewłaściwy uproszczony ułamek, taki jak 7/4
  • liczba mieszana, taka jak 1 3/4
  • dokładny ułamek dziesiętny, taki jak 0,75
  • wielokrotność pi, taka jak 12 pi lub 2/3 pi

When the computer is done executing both loops, what values will the variables i and j store?
Wybierz 1 odpowiedź:

We often use nested loops to visualize and operate on data that comes in rows and columns.
Imagine a field with rows of lettuce heads: each row has a repeatedly planted lettuce head, and then the rows are repeated to fill the entire field. One row of lettuce heads is a single loop; a whole field of rows is a nested loop.
✏️The program below plants a 5 x 5 field of snowmen. Change it to 5 rows of 10 snowmen, and then 10 rows of 5 snowmen.
📝 See similar code in: App Lab | Snap | Python

Pętle w pseudokodzie

The syntax of for loops varies across languages, and not all languages have for loops. However, all languages have some way of repeating code a certain number of times.
This pseudocode represents repeating instructions n number of times:
REPEAT n TIMES
{
   <instructions>
}
This is the equivalent pseudocode for displaying the multiples of 9, from 1 to 12:
i ← 1
REPEAT 12 TIMES 
{ 
   DISPLAY(9 * i)
   i ← i + 1
}
Since REPEAT does not have a 3-part header, we need to initialize the counter variable before the REPEAT header, and we increment the counter variable at the end of the body.
For one more example, here's the pseudocode for displaying a countdown from 10 down to 1:
i ← 10
REPEAT 10 TIMES
{
   DISPLAY(i)
      i ← i - 1
}

🙋🏽🙋🏻‍♀️🙋🏿‍♂️Masz pytania związane z tym zagadnieniem? Możesz zadać swoje pytanie poniżej!

Chcesz dołączyć do dyskusji?

Rozumiesz angielski? Kliknij tutaj, aby zobaczyć więcej dyskusji na angielskiej wersji strony Khan Academy.