In most imperative computer programming languages, a for loop is a control structure which allows code to be executed iteratively. For loops, unlike while loops, are typically used when the number of iterations is known before entering the loop.
Examples
These for loops will calculate the factorial of a number:
In QBasic or Visual Basic:
Dim Factorial as Long
Factorial = 1
For Counter = 5 to 1 Step -1
Factorial = Factorial * Counter
Next
Print Factorial
In C++:
int factorial = 1;
for (int i = 1; i <= 5; i++)
factorial *= i;
std::cout << factorial;
In Python:
f = 1
for i in xrange(1, 10):
f *= i
print f
In Java:
int factorial = 1;
for (int i = 1; i <= 5; i++) {
factorial = factorial * i;
}
System.out.println(factorial);
A for loop can always be converted into a while loop.
See also
- While loop
- Do while loop
- Loop counter