Looping

Looping#

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

  • while

  • foreach

while statement#

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

var solution = 84;
Console.WriteLine("Guess the number!");
var guess = int.Parse(Console.ReadLine());

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

Console.WriteLine("🎉");

Activity 17

Draw a flowchart for the code above.

foreach#

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

Console.WriteLine($"We have {inventory.Length} part(s)!");
foreach (var part in inventory) Console.WriteLine(part);
Output
We have 3 part(s)!
hydraulic pump
PLC module
servo motor
🤔 Question to ponder

How can foreach help in our problem?

Activity 18 (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.

  2. Search for a part in the inventory.

  3. Count how many parts have steel in their name.

  4. 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#