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

Numbered repetition of instructions

AP.CSP:
AAP‑2 (EU)
,
AAP‑2.K (LO)
,
AAP‑2.K.1 (EK)
,
AAP‑2.K.2 (EK)
The world is full of repetition: a scientist repeating an experiment 100 times and recording the results, a gardener planting neat rows of lettuce heads 2 inches apart, a 3D printer repeatedly printing layer after layer.
Computer programs are also full of repetition, since our programs automate and simulate the world around us. Programmers use for loops to repeat a set of instructions a specific number of times.

The need for loops

Imagine we're making a program that outputs the multiplication table for the number 9.
We could code the first 13 multiples like this:
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);
That works, but this approach has some drawbacks. What if we want to display the first 100 multiples? That's another 87 lines of code! What if we then decide to add some text to each of the displays? We'd have to change 100 lines of code!
With a for loop, we can tell the computer to repeat an instruction so that we don't need to repeat it in code.
We can rewrite that code using a for loop in JavaScript like so:
for (var i = 0; i < 13; i++) {
  println(9 * i);
}
Each for loop starts with a 3-part header inside the parenthesis. The header follows this template:
for (initialization; condition; increment/decrement)
A counter variable is used throughout those parts. That variable keeps track of the current repetition, and is typically named 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

Loop variations

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 19.
  • 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.
Check your understanding
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?
Choose all answers that apply:
Choose all answers that apply:

Nested loops

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.
Check your understanding
In the example above, how many times will println() be called?
  • Your answer should be
  • an integer, like 6
  • a simplified proper fraction, like 3, slash, 5
  • a simplified improper fraction, like 7, slash, 4
  • a mixed number, like 1, space, 3, slash, 4
  • an exact decimal, like 0, point, 75
  • a multiple of pi, like 12, space, start text, p, i, end text or 2, slash, 3, space, start text, p, i, end text

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

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

Loops in pseudocode

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
}

🙋🏽🙋🏻‍♀️🙋🏿‍♂️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?

  • leaf red style avatar for user layaz7717
    Hello.
    I was having a bit of trouble understanding this code:
    for (var i = 0; i < 5; i++) {
    var row = "";
    for (var j = 0; j <5; j++) {
    row += " ☃ ";
    }
    println(row);
    }
    Firstly, why is there i< 5 and j< 5, rather than i<= 5, j<= 5? I've been playing with the code, and the former results in 5 lines of snowmen, while the latter results in 6. I would have expected that i< 5 and j< 5 would just stop at 4.

    Furthermore, what is the purpose of the following lines:
    var row = "";
    row += " ☃ ";
    I was doing some Googling to check what += means, and apparently it's "a += 1; is equal to a = a + 1;." I just wasn't sure how this would apply to our code.
    Thank you in advance!
    (4 votes)
    Default Khan Academy avatar avatar for user
    • leaf green style avatar for user Shane McGookey
      Your first question comes down to an idiosyncratic convention in computer science. In computer science, we start indexing from 0 rather than 1 - this doesn't match the convention that most people are used to following, which is starting at 1 (such as in traditional counting). Therefore, when the loop you specified runs, it will run...

      i = 0; 1 time...
      i = 1; 2 times...
      i = 2; 3 times...
      i = 3; 4 times...
      i = 4; 5 times...
      i = 5; iteration ends.

      so, five total times / iterations. If you wanted to use i <= 5, then your initial expression would need to be i = 1, but we always start our loops from 0 in computer science unless there's a good reason not to.

      As for your second question, we have two loops - the first loop enacts var row = "", which creates a variable named "row" initialized with the empty string. The inner-loop will then populate that empty string with five snowmen and print the row. The process then returns to the first loop (outer loop), which creates another variable row with the initial value of an empty string and repeats the process (on a newline since we used println). This process prints the neat snowman grid that you end up with in the exercise.
      (2 votes)
  • winston default style avatar for user Joon
    As a beginner, I am struggling to grasp an intuitive understanding of programming. The problem is that beginner tutorials tend to start off easy then become harder in increasingly large increments, as they assume or expect you to know content no mentioned previously, creating minor lapses in knowledge that add up over time. I get to this point where I know the fundamentals but I struggle with taking the next step. Furthermore, the practice doesn't align with the content of the articles, in this case, creating even more confusion. There is a lack of intuitive, "instinctual" understanding. There are no video demonstrations - just articles - which I feel inhibits me from visualizing and conceptualizing ideas as a visual learner. I feel like memorizing instead of learning concepts. I've spent three hours on the section alone, but, every time I go back to fundamentals, I already know them. Once I come back to concepts I've struggled, I continue to struggle because of those lapses in knowledge. This pattern pretty much applies to every other learning platform I have used. I'm in this awkward gray area. In other words, I am programming from what I have memorized, but I don't know what I am doing, why the code is written the way it is, and what the code is exactly doing. What do I do?
    (4 votes)
    Default Khan Academy avatar avatar for user
  • duskpin tree style avatar for user T̷h̷e̷  L̷e̷g̷e̷n̷d̷
    How do you do loops in an ellipse code?
    (1 vote)
    Default Khan Academy avatar avatar for user
    • hopper cool style avatar for user Iron Programming
      If you reference how to loop a group of ellipses, you can do that a variety of ways, depending on the language.

      If you are dealing with Processing.js, a Java Script library used on Khan Academy, then you can do that like so:
      // this "for" loop has a starting index of "0", loops until "5", by increment states of one (++ means increase by one)
      for (var i = 0; i < 5; i++) {
      var x = (i * 25); // we are defining a variable x to be dependent on the looping variable i
      ellipse(x, 50, 25, 25); // draw the ellipse at (x, 25) for each iteration
      }


      Hope this helps!
      (1 vote)
  • blobby green style avatar for user Vishwa
    Hi,

    I think that there is an error with the second practice problem. I chose i=10, j=10 and it said that the correct answer is i=11, j=11. When I ran the code in your editor, it said i=10, j=10. Here is the code that I ran:

    // Same as code snippet, but with more info displayed
    for (var i = 0; i < 10; i++) {
    for (var j = 0; j < 10; j++) {
    var product = i * j;
    println(i + " * " + j + " = " + product);
    }
    }
    println(i); //Displays final value of "i"
    println(j); //Displays final value of "j"
    (1 vote)
    Default Khan Academy avatar avatar for user
    • leaf green style avatar for user Shane McGookey
      The practice problem is referring to this code snippet:

      for (var i = 1; i <= 10; i++) {
      for (var j = 1; j <= 10; j++) {
      println(i * j);
      }
      }

      In this code snippet, both loops will iterate from 1 to 10, inclusive. When i == 10, the loop will persist; the loop will also persist when j == 10. The loop will only exit after the final increment (of i for the outer loop and j for the inner loop), where each variable is set to 11 and will be compared against the condition <= 10, which would then fail, causing the loop(s) to terminate.
      (1 vote)
  • blobby green style avatar for user Leonard Wang
    What does the "var i" do in the 5X5 snowmen? And I think there should be 25 lines of code based on the calls of Println, but there just five lines. Thanks in advance!
    (0 votes)
    Default Khan Academy avatar avatar for user
    • aqualine ultimate style avatar for user Martin
      That's the power of loops, they allow you to compress a lot of instructions down to a few.
      var i is a variable that the loop uses to keep track of it's repetitions.

      I would actually encourage you to experiment with the code (it won't break anything :^) ). Start by changing the fives to different numbers (maybe 10 to start?).

      The i++ and the j++, are shorthand for i = i + 1 or j = j + 1. Knowing that you should be able to play with that part of the loop as well.
      (0 votes)
  • blobby green style avatar for user pepperoni
    hi,i have some problem understanding this code.
    for (var i = 0; i < 5; i++) {
    var row = "";
    for (var j = 0; j < 5; j++) {
    row += " ☃ ";
    }
    println(row);
    }

    first, there're i and j in the code which represent number
    so how come the result can come out as snowman in it? which part tells the machine each line has 5 snowman and 5 rows?
    because the number i and j didn't equal to anything in the code.so how does the machine understand it? i'm so confused with this for loop code.
    (0 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user Adrienne McLaughlin
    I'm learning a lot, but I had particular trouble with this lesson. In my opinion, the lesson did not provide enough explanation to be able to understand the practice questions, which were in pseudocode. I have found this to be a problem throughout the course so far. One other note: It would be great if there was an option in this program to be able to save the questions and answers to the practice questions and quizes. Maybe there already is an option and I can't locate it?
    Thanks!
    (0 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user theresa.choe
    Where is the output (above)? I would have to agree with Adrienne. Learning pseudocode is pretty useless these days. Developers don't use it, waste of precious time. I'm not taking the AP exam but I'm assuming they test with pseudocode otherwise why would there be this outdated material presented here. I would suggest that whoever the governing body is that updates the AP CS course make some serious changes to reflect current best practices in CS.
    (0 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user Muhammad  Ahmed
    I understand loops from this lesson but I wanted to ask would it be possible for me to run a loop that after each run stores the answer differently so for example if I were to ask what is your age. the code would run three times and each time remember and print the three different ages
    (0 votes)
    Default Khan Academy avatar avatar for user