Loops
Intro
Loops were first introduced in the languages ALGOL and Fortran. In C# we use four different loops.
for
The for loop has the most time-consuming declaration. We differ between loop-head, -body and -tail.
- head and tail: controls the repetitions
- body: code to repeat
The for loop only contains of a head and body:
for (int i = 1; i < 5; i++) {
Console.Write(i + " ");
} // Output: 1 2 3 4
Definition of a for loop
for (initializer; condition; iterator) {
body
}
- initializer: declaration and initialization of a local loop variable, executed only once, before entering the loop.
- condition: determines if the loop is executed, must be true.
- iterator: usually an increment or a decrement expression.
while
The while loop is also made up of af a head and body.
A while loop continues, until it's condition is false. The while loop is the most easiest to declare:
bool boolean = true;
while (boolean) { // This loop runs once
boolean = false;
}
do while
The do while loop contains of a body and a tail.
The "do while" loop works like the while loop, except the loop-body is executed before the loop condition is checked.
bool boolean = false;
do {
Console.WriteLine("Runs at lease once in any case");
} while (boolean);
foreach
When you get used to utilizing all loop types, the foreach loop becomes the most easiest to code.
We like the foreach loop for iterating through arrays and other collections.
string[] texts = { "alf", "bert", "carl" };
foreach (string item in texts) {
Console.Write(item + " ");
}
// Output: alf bert carl
break and continue keywords
Can be used to control loops but I consider using them like using a spoon for eating spaghetti in italy - avoid if possible. (For exams where time is of the essence, it can be useful, so you should master it anyway)
Right now at our college goto and continue are not to be used during an exam..
while (true)
{
if (++i > 10)
break;
}
break will exit the loop, continue will skip the current iteration.
When to use which loop.
When I ask myself, which loop I should use, I consider if the loop-condition is determined before the first iteration or not.
If i already know how often the loop will be executed before executing the loop I use the for or foreach loop.
If the essential condition comes from within the loop and i do not know, how often the body will be executed, I use the while or do while loop.