Looping or iteration is when a program repeatedly runs the same lines of code. A loop is created when the programmer specifies that the program need to jump back to a previous instruction instead of continuing to the next instruction.
The most fundamental loop structure in C++ is a while statement. It says βWhile the condition is true, do the body. Once the condition is false, continue with the code after the body.β Here is a simple example to watch in Codelens:
Reading the code in English sounds like this: βSet with n set to 3. While n is greater than 0, print the value of n, and reduce the value of n by 1. After n is 0, print Blastoff!β
The test of the loop almost always has a variable as part of the expression it tests. Without a variable, there is no way for the loop to terminate once it starts. This variable is referred to as a loop control variable. The body of the loop must change the value of that variable so that, eventually, the condition becomes false and the loop terminates. Otherwise, the loop will repeat forever, which is called an infinite loop.
When you make an infinite loop on an ActiveCode problem, it will display Compiling and running your program for ~10 seconds until the server decides to stop your program. If you run an infinite loop on your own computer, you will need to stop the program manually. You can generally do this by pressing Ctrl+C in the terminal window where the program is running. That sends a βkillβ signal to the program, which should stop it.
It is also possible for the body of a loop to never end up executing. Notice in this sample that the condition is false the first time we reach it. That means the body will never get a chance to execute:
The loop will run as long as n is positive. In this case, we can see that n will never become non-positive as the while statement condition will never be met.
The answer starts at 1 and is incremented by n each time, so it will always be positive.
Setting a variable so the loop condition would be false in the middle of the loop body does not stop execution of statements in the rest of the loop body.
After n becomes 5 and the test would be False, but the test does not actually come until after the end of the loop - only then stopping execution of the repetition of the loop.