For loop
Many programming languages define a for loop as a control structure with which a group of instructions (block) can be executed with a certain number of repetitions or arguments.
The definition of what a for loop should look like ( syntax ) differs from programming language to programming language. The meaning of a for loop ( semantics ), i.e. the way in which it is executed, also differs from language to language. The elements that make up a For Loop are almost always the same.
Numerical loop
The number of repetitions is already fixed when entering the loop . There is a loop variable that is set to the start value at the beginning and is then changed by the increment until the target value is reached. The loop variable, the start value, the step size and the end value must be numeric. This form of the loop is therefore also known under the term counting loop .
In most programming languages , the start, end and increment are limited to whole numbers. In some languages the step size is limited to 1 (or −1 with downto instead of to ).
The basic structure of these for loops is as follows (here using the BASIC example ):
For Zähler = Start To Ende Step n
' zu
' wiederholende
' Anweisungen
Next
Expression-oriented loop
The expression-oriented loop allows you to work with non-numeric loop variables. For example, linked lists can also be edited.
In C-like programming languages , a for loop has the form:
for (Initialisierung; Test; Fortsetzung) Anweisung
And this is how it is carried out (according to ISO / IEC 9899: 1999 ):
- The expression initialization is evaluated. If this is a declaration , the variables defined in it are only valid within the for loop.
- The expression test is evaluated as a Boolean expression. If the value is false , the for loop is ended.
- The statement statement is executed.
- The expression continuation (usually an instruction ) is evaluated.
- It continues with 2..
Example of use as a non-numeric loop:
struct Liste {
struct Liste *next;
int element;
};
for (p = liste; p != NULL; p = p->next) {
…
}
Example of use as a numeric loop:
for (i = 0; i < length; i++) {
…
}
Nested for loops
There can be one or more other for loops within a for loop. These are nested for loops.
Examples
The Bubblesort sorting method uses two nested for loops. In the inner loop , neighboring elements are swapped.
public void Bubblesort(object[] elements)
{
for (int i = elements.Length - 1; i > 0; i--)
{
for (int j = 0; j < i; j++)
{
object element1 = elements[j];
object element2 = elements[j + 1];
if (element1 > element2)
{
elements[j] = element2;
elements[j + 1] = element1;
}
}
}
}
The following method computes the binomial coefficients in Pascal's triangle and returns a two-dimensional array :
public int[][] Binomial(int n)
{
int[][] binomials = new int[n][];
binomials[0] = new int[1];
binomials[0][0] = 1;
for (int i = 1; i < n; i++)
{
binomials[i] = new int[i + 1];
for (int j = 0; j <= i; j++)
{
int left = 0;
if (j > 0)
{
left = binomials[i - 1][j - 1];
}
int right = 0;
if (j < i)
{
right = binomials[i - 1][j];
}
binomials[i][j] = left + right;
}
}
return binomials;
}
Foreach loop
Some programming languages (for example C ++ , C # , Java , Perl , Python , PHP ) offer a construct to assign all elements of a list to a variable one after the other . This construct is usually called a foreach loop in accordance with its usual keyword . However, notation and keyword differ depending on the programming language. The foreach loop is called a for-in loop in Object Pascal and JavaScript . In JavaScript, contrary to the description above, only the index or key is assigned to the variable and not the element itself, because the For-Of loop is used for the latter.
C ++
From version C ++ 11 are available in C ++ , the range-based for-loop (Engl. Range-based for ). This simplifies iterating over any container and other objects for which the functions std::begin
and have been std::end
overloaded , e.g. B. all containers of the standard library , but also via built-in arrays ( C-style arrays ) or user-defined container data types :
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec(5); // Initialisiere vec mit 5 Zellen
// range-basierte for-Schleife über Initialisiererliste (std::initializer_list) und Zuweisung an die Vektorelemente
for (auto i: {1, 2, 3, 4, 5}) {
vec[i-1] = i;
}
// range-basierte for-Schleife über Vektor
for (auto i: vec) {
std::cout << i << " ";
}
}
The keyword used here auto
causes the compiler to automatically use the required type (would be for both loops int
).
C #
In C # , the foreach loop has the following form:
foreach (datatype element in enumerable)
{
…
}
In the following example, the foreach loop goes through all the countries in the generic list and outputs all countries with names ending in "land":
// Generische Liste der Länder
List<string> countries = new List<string>();
// Liste füllen
countries.Add("Germany");
countries.Add("Austria");
countries.Add("Switzerland");
countries.Add("France");
countries.Add("Poland");
countries.Add("United States");
// Die foreach-Schleife durchläuft der Reihe nach alle Elemente der Liste
foreach (string country in countries)
{
if (country.EndsWith("land"))
{
Console.WriteLine(country);
}
}
Ada
A foreach loop in Ada has the form:
for Variable_1 in Variable_2'Range loop
Anweisungen
end loop;
Example:
A : array (3..5) of Integer := (5, 9, 10);
for I in A'Range loop
Put (A(I));
end loop;
Pearl
A for or foreach loop (both keywords are synonymous in Perl ) has the form:
foreach Variable (Werte) { Anweisungen }
Example:
foreach $name ("Anna", "Heinz", "Sebastian")
{
print("Hallo, $name.\n");
}
$ name is the variable that is assigned the values in brackets one after the other.
If the loop block contains only one command, the following form can also be used, which however does not allow a self-named run variable:
say "Hallo, $_." for qw/Anna Heinz Sebastian/;
Use as in C is also possible:
for ($i = 0; $i < $length; $i++)
{
…
}
PHP
A foreach loop in PHP has the form:
foreach (Array as Schluessel => Wert)
{
…
}
Key and value are assigned a key-value pair from the array in each loop pass. PHP arrays differ from many other programming languages in that each entry can be a key-value pair, not just a simple value.
In contrast to Perl , the syntax is not based on the mathematical reading, so it sounds strange when you read the code out loud. This can lead to problems, especially for those who are new to programming or those who switch. In most other programming languages, the keyword foreach is followed by the name of the variable that takes on the various values one after the other.
Example:
<?php
$namen = array (
"Albert" => "Einstein",
"Rasmus" => "Lerdorf",
"Stephen William" => "Hawking"
);
foreach ($namen as $vorname => $nachname)
{
print("Hallo, $vorname $nachname\n");
}
?>
Historical: The for-loop of "Superplan"
From 1949 to 1951, Heinz Rutishauser developed the simple algebraic programming language “Superplan”. Rutishauser was familiar with Konrad Zuse's work on programming languages; H. Zuse's Plankalkül and chose the name based on Zuse's designation "calculation plan" for a single program.
Rutishauser's simple language had only one control structure: the For statement or For loop.
Für i=2(1)n: + 3 =
means z. For example, in an array a, a 3 is added to all (i.e., incremental increments of 1 ) elements from index start value 2 up to index target value n.
See also
- Loops (while loop, do-while loop, etc.)
- Infinite loop
Web links
- Listing of the syntax of programming language constructs
- The New C Standard: An Economic and Cultural Commentary . English-language book that deals with C in great detail and compares it with other languages. The for loop is explained on page 1428 (Section 6.8.5.3) in the PDF document.
Individual evidence
- ↑ research.att.com
- ↑ cppreference.com initializer lists