For loop
In most computer programming languages, a for loop is a control structure which allows code to be executed iteratively. For loop, unlike while loops, are usually passed three arguments, although this varies heavily by programming language: a statement to be executed before the first iteration of the loop, a boolean condition, and a statement to be executed following every iteration of the loop. Any code within the loop is executed until the condition given in the second argument of the loop evaluates to false. Evaluation is typically done before the next iteration of a loop, but after the statement in the third argument is executed. Note that it is possible, and in some cases desirable, for the loop condition to always evaluate to true, creating an infinite loop. When such a loop is created intentionally, there is usually another control structure (such as a break statement) that controls termination of the loop.
These for loops will calculate the factorial of a number:
In QBasic or Visual Basic:
Examples
Dim Factorial as Long
Factorial = 1
In C or C++:
For Counter = 5 to 1 Step -1
Factorial = Factorial * Counter
Next
Print Factorial 'Prints out the result.
int main() {
unsigned int Counter; /* In C99 and C++, you can make this declaration inside the for loop */
unsigned long Factorial = 1;
for (Counter = 5; Counter > 0; Counter--)
Factorial *= Counter;
printf("%i", Factorial);
return 0;
}
See also