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.
Contents
- 1 Examples
- 1.1 QBasic or Visual Basic
- 1.2 C or C++
- 1.3 Python
- 1.4 Java, Csharp
- 1.5 JavaScript
- 1.6 Perl
- 1.7 Pascal
- 2 Equivalence with while loops
- 3 See also
|
Examples
These for loops will calculate the factorial of the number five, 5!, by iterating through all the numbers 1 through 5 and keeping a running product:
QBasic or Visual Basic
Dim factorial As Long : factorial = 1
Dim counter As Integer
For counter = 1 To 5
factorial = factorial * counter
Next
Print factorial
C or C++
unsigned long factorial = 1;
for (unsigned int counter = 1; counter <= 5; counter++)
factorial *= counter;
printf("%i", factorial);
Python
factorial = 1
for counter in range(1, 6): # range() gives values to one less than the second argument
factorial *= counter
print factorial
Java, Csharp
The syntax for the for loop is the same for Java and Csharp
long factorial = 1;
for (int counter = 1; counter <= 5; counter++)
factorial *= counter;
Output of the result in Java
System.out.println(factorial);
In Csharp
System.Console.WriteLine(factorial);
JavaScript
var factorial = 1;
for (var counter = 1; counter <= 5; counter++){
factorial *= counter;
document.write(factorial);
}
Perl
my $factorial = 1;
for ( my $counter = 1; $counter <= 5; $counter++ ) {
$factorial *= $counter;
}
print $factorial;
Pascal
program Factorial
var
Counter, Factorial: integer;
begin
Factorial := 1;
for Counter := 1 to 5 do begin
Factorial := Factorial * Counter;
end;
Write(Factorial);
end.
Equivalence with while loops
A for loop can always be converted into an equivalent while loop by incrementing a counter variable directly. The following pseudocode illustrates this technique:
factorial := 1
for counter from 1 to 5:
factorial := factorial * counter
is easily translated into the following while loop:
factorial := 1
counter := 1
while counter <= 5:
factorial := factorial * counter
counter := counter + 1
See also
- While loop
- Do while loop
- Loop counterde:For-Schleife
ja:For文
Categories: Programming constructs