Five Minute C# — Lesson 10

Further loops and implementation

Alexander Laurence
Five Minute C#
3 min readOct 31, 2018

--

Lessons: 12345678910 ・ 11 ・ 12 ・ 13 ・ 14

Conditions to the left of me, counting variables to the right, here I am, stuck in the middle of a loop

Welcome back to my bad jokes. I see you are hungry for more loops. Let’s get to work!

We now know 2 types of loops. Let’s learn another 2!

For Each Loop

For each is probably one of the easier loops. It iterates the code through a collection of items. Think of it as an extension of the for loop. However, foreach does not use indexes unlike the for loop. This saves us from having to count the number of elements, and iterating through the length of the array.

Let me show you an example of how to write a foreach loop! Start by writing:

Now we have to specify the parameter. Here we want to specify exactly what we want to collect, this is your datatype (strings, integers, floats, etc) and give it a name. Then specify where you want to collect that from, this can be an array or a list.

Let’s say we want to collect fruits from the array fruitArray:

Your foreach loop should look like this:

This applies the same for lists too!

Let’s say we want to skip out pears… Let’s use control statements!

You can even break the loop using the break statement in the same way as we learnt. So there’s no need to write a for loop, use counters, conditions, array lengths, etc… Just use a foreach loop! It’s as simple as that.

Next! The do while loop.

Do While Loop

Remember the while loop? It runs the code based on a boolean value of true or false. So as long the condition is true, the while loop will indefinitely loop the code.

Now, the do while loop is slightly different in the sense that anything specified in the do block of the code will run at least once, while the code within the while block will be dependent on the boolean value of true.

So what we mean is that, even if the while loop is false, it will at least run the do portion of the code at least once. It’s better to demonstrate this than to explain it…

This is the syntax for the do while loop:

Let’s make it so that it displays (Console.WriteLine()) the value of i (int i), which increases by 1 (i++), while it is less than 10 (i<10). It will look something like this:

This will give us the output of:

I hope this makes sense! They’re very easy right?

--

--

Alexander Laurence
Five Minute C#

Alex graduated from the University of Edinburgh with a Masters degree in Neuroscience. He spent 3 years teaching and now runs his own tech venture.