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

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:

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/5
  • a simplified improper fraction, like 7/4
  • a mixed number, like 1 3/4
  • an exact decimal, like 0.75
  • a multiple of pi, like 12 pi or 2/3 pi

When the computer is done executing both loops, what values will the variables i and j store?
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?

  • 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!
    (65 votes)
    Default Khan Academy avatar avatar for user
  • 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!
    (7 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.
      (16 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?
    (12 votes)
    Default Khan Academy avatar avatar for user
  • eggleston green style avatar for user Eliezer Ramirez
    Is there a video explaining the answers to the questions in the test after this lesson? Im having trouble understanding the looped psudocode in one of the questions
    (3 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user dvalladolid
    the quiz is absolutely nothing like this lesson
    (3 votes)
    Default Khan Academy avatar avatar for user
  • female robot ada style avatar for user DedeLily
    I don't get it. What's "result" used for in this code? What's its value? What will finally be output?
    result ← 1
    i ← 6
    REPEAT 6 TIMES
    {
    result ← result * i
    i ← i + 3
    }
    (2 votes)
    Default Khan Academy avatar avatar for user
  • piceratops ultimate style avatar for user Gina
    Does anyone have any tips for understanding the questions in the quiz with the cats and pixels? I can’t find an easy way to break down the code snippets.
    (2 votes)
    Default Khan Academy avatar avatar for user
  • blobby green style avatar for user M2
    I'm also struggling to get a good grasp on this concept. I am especially confused as to what the increment/decrement does and how it correlates with the counter variable. Also, how do you determine what value is being stored after the computer executes both loops? Actually, I think the nested loops might be the topic I'm just not able to understand. If anyone can give a clear explanation, I will be willing to listen.
    (2 votes)
    Default Khan Academy avatar avatar for user
  • blobby blue style avatar for user 202508
    Hii! This is an AP CSP college board practice question, I asked my teachers but they are not able to explain it. May anyone help explaining it for me? I'm actually so confused about the questions. What is it asking for to be as a"reasonable time"??
    Q:
    Consider the following algorithms. Each algorithm operates on a list containing n elements, where n is a very large integer.
    An algorithm that accesses each element in the list twice
    an algorithm that accesses each element in the list n times
    an algorithm that accesses only the first 10 elements in the list, regardless of the size of the list which of the algorithms run in reasonable time?
    Thank you so much for anyone who replies.
    (2 votes)
    Default Khan Academy avatar avatar for user
  • 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.
      (2 votes)