For...Loop
A count-controlled loop that runs for a certain number of iterations.
Last updated
A count-controlled loop that runs for a certain number of iterations.
Last updated
There is probably a programming language out there that does not have some sort of implementation of the for loop, but they are few and far between. It is almost a requirement in order to have the computer do code repeatedly a certain number of times.
The loop contains a counter or index that the programmer defines. The code will run and loop back to the top as long as the "continue condition" is true. Each loop iteration needs to modify the index somehow or else you have an infinite loop. Typically you increase the index by 1 but you can do any sort of mathematical operation on the index.
The syntax is fairly simple:
Here is an animation of a for loop in action. The code prints the powers of 2 from a power of zero to ten (inclusive). It also keeps track of a running total and prints that at the end.
For a faster animation, click here (and for a really fast one, click here).
While most examples and definitions show i++
to increment the index, it does not need to be counting up. You can decrement (subtract one), add 2, multiply by a value... it all depends on the needs of the programmer. Here is an example of a for loop that counts down by 1:
Because a for loop can contain any amount of code (scope block { }
), you can write another for loop inside (and another inside that, etc). This is called nested looping. An example would be printing a multiplication table or other 2-dimensional work: