Main content
AP®︎/College Computer Science Principles
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.
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.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);
}
}
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.
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.
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?
- 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!(53 votes) - 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!(6 votes)- 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 usei <= 5
, then your initial expression would need to bei = 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 enactsvar 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 variablerow
with the initial value of an empty string and repeats the process (on a newline since we usedprintln
). This process prints the neat snowman grid that you end up with in the exercise.(12 votes)
- 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?(8 votes)
- I agree. Articles. Are hard to understand but KA also has video tutorials of programming:
https://www.khanacademy.org/computing/computer-programming(0 votes)
- the quiz is absolutely nothing like this lesson(2 votes)
- 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.(1 vote)
- 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)- 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. Wheni == 10
, the loop will persist; the loop will also persist whenj == 10
. The loop will only exit after the final increment (ofi
for the outer loop andj
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)
- How do you do loops in an ellipse code?(1 vote)
- 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)
- I think I'm missing something, but I'm not sure what. Everything made sense in JS (which I don't know, I don't know any coding languages), but when they gave a couple examples in pseudocode I had a really hard time figuring out what was going on. I was able to get 100% on the quiz after a few attempts but had to rely on educated guesses and method of elimination. I don't feel like I have a good hold on the pseudocode, and it seems like there's a massive leap from the lesson to the quiz. Is there somewhere I should go to learn more about it, or am I missing some obvious connection? Any advice would be great.(1 vote)
- I've learned looping through flowcharts in class and that helped a bit with visualizing the process.(1 vote)
- 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) - 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)
- Yes, if you do more into coding you will learn more ways to generate the answer as well. Using things either from user input in HTML or a random # generator you could do that.(1 vote)