# Looping

Repeating an operation in a fast manner is a superpower of a computer. Will look into:

- `while`
- `foreach`

<!--
- `for`
- `do-while`
-->

(while)=
## `while`{l=cs} statement

`while` repeats a block of operations as long as the given condition is `true`.

```cs
var solution = 84;
Console.WriteLine("Guess the number!");
int.TryParse(Console.ReadLine(), out var guess);

while (solution != guess)
{
    Console.WriteLine($"Is {(solution > guess ? "greater" : "less")}. Try again.");
    int.TryParse(Console.ReadLine(), out var guess);
}

Console.WriteLine("🎉");
```

:::{activity}
Draw a flowchart for the code above.
:::

<!--
- `do-while` already executes some statement before testing the looping condition.
-->

<!--
:::{activity}
1. Is a `do-while` loop better suited for the program above? Why? Why not?
1. Rewrite the code as a `do-while` loop and compare your results.
:::
-->

(foreach)=
## `foreach`{l=cs}

```cs
string[] inventory = { "hydraulic pump", "PLC module", "servo motor" };

Console.WriteLine($"We have {inventory.Length} part(s)!");
foreach (var part in inventory) Console.WriteLine(part);
```
:::{dropdown} Output
```text
We have 3 part(s)!
hydraulic pump
PLC module
servo motor
```
:::

<!--
## `for`{l=cs}

```cs
string[] inventory = { "hydraulic pump", "PLC module", "servo motor" };

Console.WriteLine($"We have {inventory.Length} part(s)!");
for (var i = 0; i < inventory.Length; i++) Console.WriteLine($"{i + 1}. {inventory[i]}");
```
:::{dropdown} Output
```text
We have 3 part(s)!
1. hydraulic pump
2. PLC module
3. servo motor
```
:::
-->

:::{card} 🤔 Question to ponder
<!--
1. Which differences do you observe between `for` and `foreach`?
2. Which one could be useful in our problem, and why?
-->
How can `foreach` help in our problem?
:::

:::{activity} Which loop for which scenario?
For each scenario below, choose one loop type and explain why.

1. Keep asking until the user enters a valid part name.
1. Search for a part in the inventory.
1. Count how many parts have `steel` in their name.
1. You have a list of part requests that need to be processed in order. After processing a part, it is removed from the list. You process, until the list is empty.
:::

## Appendix

- [Iteration statements - `for`, `foreach`, `do`, and `while`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/iteration-statements)