Loops
How to run the same code without copy-pasting it
Suppose you wanted to print the numbers 0-9. Here’s one way you could do it:
Code:
print("0")
print("1")
print("2")
print("3")
print("4")
print("5")
print("6")
print("7")
print("8")
print("9")
Output:
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
Code:
System.out.println("0");
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
System.out.println("5");
System.out.println("6");
System.out.println("7");
System.out.println("8");
System.out.println("9");
Output:
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
Code:
cout << "0" << "\n";
cout << "1" << "\n";
cout << "2" << "\n";
cout << "3" << "\n";
cout << "4" << "\n";
cout << "5" << "\n";
cout << "6" << "\n";
cout << "7" << "\n";
cout << "8" << "\n";
cout << "9";
Output:
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
The “\n” puts the subsequent output on the next line.
While this code works, it doesn’t scale- If you wanted to instead print the numbers 0-999, it would take a lot of time, effort, and characters to repeatedly print using the same method.
What we can do instead is use a loop. Loops are another method to control the flow of a program when you want to run the same block of code multiple times, but only want to write it once. This code does the exact same thing as the previous 10 lines.
Code:
for i in range(10):
    print(i)
Output:
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
Code:
for(int i = 0; i < 10; i++) {
    System.out.println(i);
}
Output:
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
Code:
for(int i = 0; i < 10; i++) {
   cout << i << "\n";
}
Output:
> 0
> 1
> 2
> 3
> 4
> 5
> 6
> 7
> 8
> 9
Note: In Java and C++, the operation
++
is equivalent to
+= 1
or adding 1 to the variable. The
++
operator doesn’t exist in Python!
For-loop
The previous example used a type of loop called a for-loop. The syntax to a for-loop that executes a block of code
x
times looks like this:
Code:
for i in range(x):
    # code block
Code:
for(int i = 0; i < x; i++) {
    // code block
}
Code:
for(int i = 0; i < x; i++) {
   // code block
}
In Java and C++, the more general form of a for-loop is this:
Code:
for(/* statement 1 */; /* statement 2 */; /* statement 3 */) {
    //code block
}
Code:
for(/* statement 1 */; /* statement 2 */; /* statement 3 */) {
    //code block
}
In these languages, the three statements control the flow of the program in the following steps:
  1. Statement 1 is executed, and it is used to define a variable that is referenced and modified in statements 2 and 3.
  2. Statement 2 is a boolean dependent on the variable defined in statement 1, and if statement 2 is True, continue to step 3. If it is false, the for-loop stops.
  3. Execute the code block.
  4. Statement 3 is executed, and it is used to modify the variable defined in statement 1. Return to step 2.
Note: The for-loop will not stop executing the code block if statement 2 is never false. This behavior is called an infinite loop because your program runs until your computer is out of power, the program is terminated, your computer runs out of memory, or some other external cause of program failure.
Let’s follow those steps and take a look at how the code in this example is executed:
Code:
for(int i = 0; i < 2; i++) {
    System.out.println("The code block was executed");
}
Output:
> The code block was executed
> The code block was executed
Code:
for(int i = 0; i < 2; i++) {
   cout << "The code block was executed";
}
Output:
> The code block was executed
> The code block was executed
  1. The computer is on step 1. Statement 1 is executed, which means the variable i is declared with an initial value of 0.
  2. The computer is on step 2. The variable i is currently 0, so the boolean i < 2 is true, and we can proceed to step 3.
  3. The computer is on step 3. The code block is executed, and “The code block was executed” is printed to the console.
  4. The computer is on step 4. Statement 3 is executed, which means the variable i is incremented by 1 and now has value 1. We then return to step 2.
  5. The computer is on step 2. The variable i is currently 1, so the statement i < 2 is true, and we can proceed to step 3.
  6. The computer is on step 3. The code block is executed, and “The code block was executed” is printed to the console.
  7. The computer is on step 4. Statement 3 is executed, which means the variable i is incremented by 1 and now has value 2. We then return to step 2.
  8. The computer is on step 2. The variable i is currently 2, so the statement i < 2 is false, and we exit the for-loop.
In Python, the for-loop’s code block is simply executed the number of times specified between the parentheses of the range function.
Python uses a variation of the for-loop similar to the for-each loop in Java and C++. Because its behavior is more advanced and very different from a normal for-loop, going into additional depth is outside the scope of this event.
While loop
While loops are simpler to write and understand compared to for-loops.
The syntax for a while loop look like this:
Code:
while statement:
    # code block
Code:
while(statement) {
    // code block
}
Code:
while(statement) {
    // code block
}
A while loop executes the code block repeatedly while the statement is true. It controls the flow of a program in two steps:
  1. Check if the statement is true. If the statement is true, proceed to step 2. If the statement is false, exit the while loop
  2. Execute the code block and return to step 1
Let’s follow how a while loop executes a similar program to our for-loop demonstration.
Code:
int i = 0;
while(i < 2) {
    System.out.println("The code block was executed");
    i++;
}
Output:
> The code block was executed
> The code block was executed
Code:
int i = 0;
while(i < 2) {
    cout << "The code block was executed";
    i++;
}
Output:
> The code block was executed
> The code block was executed
  1. The computer runs all the code before the while-loop, which creates a variable i that will determine when we exit the while-loop.
  2. The computer is on step 1. i currently has value 0, so the boolean i < 2 is true, and we proceed to step 2.
  3. The computer is on step 2. The code block is executed. This prints “The code block was executed,” and i is incremented by 1 (now has value 1). The computer returns to step 1.
  4. The computer is on step 1. i currently has value 1, so the boolean i < 2 is true, and we proceed to step 2.
  5. The computer is on step 2. The code block is executed. This prints “The code block was executed,” and i is incremented by 1 (now has value 2). The computer returns to step 1.
  6. The computer is on step 1. i currently has value 2, so the boolean i < 2 is false, and we exit the while-loop.
Statement 2 in a for-loop and the statement in a while-loop have the same purpose- they define precisely when a program should stop executing the code block. However, the difference between them is that a for-loop forces the programmer to explicitly define conditions under which a program should stop running a code block.
Common Mistake: The simplicity of while loops comes at a cost: it is much easier to accidentally create an infinite loop using a while loop since it doesn’t force you to create exit conditions. Functionally, however, for-loops and while-loops are about the same.
In some cases, you may want to create an infinite / very long loop intentionally. For example, video games need to constantly update your screen with new calculations, rendering, and special effects. In cases like these, a while-loop that runs for a very long time is necessary.
Nested Loop
Like the if-statements we looked at in the “Booleans” article, loops can be placed inside one another. A loop inside another loop is called a nested loop. For example, this code prints the numbers 0-2 three times.
Code:
for i in range(3):
    for j in range(3):
        print(j)
Output:
> 0
> 1
> 2
> 0
> 1
> 2
> 0
> 1
> 2
Code:
for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
        System.out.println(j);
    }
}
Output:
> 0
> 1
> 2
> 0
> 1
> 2
> 0
> 1
> 2
Code:
for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
        cout << j;
    }
}
Output:
> 0
> 1
> 2
> 0
> 1
> 2
> 0
> 1
> 2
You can play with all the code we've used in this article on Replit:
Copyright ©2023 Howard County Hour of Code