108 lines
1.7 KiB
Markdown
108 lines
1.7 KiB
Markdown
In C#, loops are called iteration statements. We need to master both, recursion and loops. There are 3 kinds of loops in C# :
|
|
- while and do (...) while
|
|
- for
|
|
- foreach
|
|
> For the rest of the document, something between `<>`is something mandatory and something between `[]`is something optionnal
|
|
## While loop
|
|
```cs
|
|
while (<condition>)
|
|
{
|
|
// repeat stuff
|
|
}
|
|
```
|
|
The ``condition`` is a boolean
|
|
**Example**
|
|
```cs
|
|
unit SumWhile(unit n)
|
|
{
|
|
uint loop = 0;
|
|
while (n > 1)
|
|
{
|
|
loop += 1;
|
|
n = n - 1;
|
|
}
|
|
return loop;
|
|
}
|
|
```
|
|
### Iteration statements - do (..) while
|
|
```cs
|
|
do
|
|
{
|
|
// Repeat stuff
|
|
} while (condition)
|
|
```
|
|
Same thing that the other one but return in a different way
|
|
**Example**
|
|
```cs
|
|
uint SumDoWhile(uint n)
|
|
{
|
|
uint loop = 0;
|
|
do
|
|
{
|
|
loop += 1;
|
|
n = n - 1;
|
|
} while (n > 1):
|
|
return loop;
|
|
}
|
|
```
|
|
|
|
## For loop
|
|
```cs
|
|
for ([initialize]; [condition]; [iterator])
|
|
{
|
|
// Repeat stuff
|
|
}
|
|
```
|
|
**Example:**
|
|
```cs
|
|
uint SumFor(uint n)
|
|
{
|
|
uint res = 0;
|
|
for (uint i = 1; i < n; ++i)
|
|
{
|
|
res += 1;
|
|
}
|
|
return res;
|
|
}
|
|
```
|
|
**Comparaison with the while loop**
|
|
```cs
|
|
for ([initialize]; [condition]; [iterator])
|
|
{
|
|
// Repeat stuff
|
|
}
|
|
|
|
[initializer]
|
|
while ([condition])
|
|
{
|
|
// Repeat stuff
|
|
[iterator]
|
|
}
|
|
```
|
|
|
|
**We can also doo like the while loop**
|
|
```cs
|
|
for ( ; [condition] ; )
|
|
{
|
|
// repeat stuff
|
|
}
|
|
```
|
|
|
|
## Foreach loop
|
|
```cs
|
|
string test = "ABCD";
|
|
foreach (char c in test)
|
|
{
|
|
Console.WriteLine(c);
|
|
}
|
|
```
|
|
|
|
## Jump statements
|
|
Jump statements is something that can change the behaviour of a loop inside itself.
|
|
It's possible to change the behaviour of the loops using the following keyworkds:
|
|
- ``break``
|
|
- ``continue``
|
|
- ``return``
|
|
> ⚠️ It's not a good idea to use them, but rather to rework your loop correctly instead
|
|
|
|
### Jump statements - break |