Kinetic Code Camp - Bring your skills, or lack thereof.. :dumpster_fire:

Loops

There comes a time in everyone’s life where you can’t just act upon one infinitesimally small object, but you must reach out into the ether, and take hold of many, or each and every object, and act upon it with great passion. It is written. It is known. The author is ridiculous.
KL - The Art of Overdoing a Bit Suspicious Monkey GIF by MOODMAN

Loops you say?

I do, and by loops, I mean iterating. This is a pretty simple concept, so I will basically just point out some of the different kinds of loops you can do in C#, since that is what is most relevant here, but first, a slight bit more explanation.

A loop at its core is a control structure used in programming that is done multiple times until a condition is met (or while a condition is true, depending on how you look at it…). This condition can be simple or complex, and take many forms, here are some:

FOR loop

The FOR loop is composed of the following structure:

for( [ init statement ] ; [ condition statement(evaluates to boolean) ] ; [ iteration statement ])
{
[ This is the code block ]
Code you want to run until your condition is false goes here…
}

  • init statement: This statement runs once before the loop
  • conditon statement: This statement needs to evaluate to a boolean (true/false). While this statement is true, your loop will continue to run. (Unless you exit manually, or error…)
  • iteration statement: This statement will run every iteration of the loop, after the code in the code block.

With the above rules in mind, you can do the simplest and most traditional form of the FOR loop…

for(int x = 0; x < 5; x++) // 'x++' is a shorthand for 'x = x + 1' or 'x += 1'
{
    Console.WriteLine("The value of x is " + x.ToString() + " ...");
}

Explanation:

  • Here, in the init statement, we defined a variable, x as an integer.
  • In the condition statement, we want to loop or iterate while x is less than 5.
  • In the iteration statement, we add 1 to x, and store it in x, so x is literally one more than it was.
  • Each time it looped, the code in the code block was executed, and we did an action. We also have access to the variable x inside the code block, which is very useful.

Output:

The value of x is 0 ...
The value of x is 1 ...
The value of x is 2 ...
The value of x is 3 ...
The value of x is 4 ...

And that is the traditional for loop.
Those of you a little more advanced readers may be seeing how I described the above rules, and either know or suspect that that is not the end of the story, and indeed
The Next Generation Star GIF
it is not, which I will cover in a snippet, as it is a more advanced topic…


WHILE loop

The WHILE loop is composed of the following structure:

while( [ condition statement(evaluates to boolean) ] )
{
[ This is the code block ]
Code you want to run while your condition is true
}

  • conditon statement: This statement needs to evaluate to a boolean (true/false). While this statement is true, your loop will continue to run. (Unless you exit manually, or error…)

With the above rule in mind, you can do the simplest and most traditional form of the WHILE loop…

int x = 0; //I needed something to check for my condition

while( x < 5)
{
    Console.WriteLine("The value of x is " + x.ToString() + " ...");
    x++; // 'x++' is a shorthand for 'x = x + 1' or 'x += 1'
}

Explanation:

  • I made a variable x, as an integer, as I needed something to check in my condition statement, and a way to exit the loop.
  • The entire time the condition statement is true, my heart will go on the code block will execute.
  • I wrote the output of my variable x to the console again, and since this is a simpler form of loop, I added my own iteration statement to increment x by one.
  • When x gets to 5, my condition is no longer true, so the loop is complete, and we move on.

Output:

The value of x is 0 ...
The value of x is 1 ...
The value of x is 2 ...
The value of x is 3 ...
The value of x is 4 ...

Note: A WHILE loop is very simple, but very powerful. Be careful out there.
Example…

string letsCrash = "ok...";
while(true) //forever, unless YOU exit manually
{
    letsCrash += letsCrash;
    //This code has no way to exit the loop, see you at the out of memory error bar.
}

DO / WHILE loop

The DO / WHILE loop is composed of the following structure:

do
{
[ This is the code block ]
Runs at least once.
Code you want to run while your condition is true
Also known as until your condition is false…
}
while( [ condition statement(evaluates to boolean) ] )

  • conditon statement: This statement needs to evaluate to a boolean (true/false). While this statement is true, your loop will continue to run. (Unless you exit manually, or error…)
  • This code will ALWAYS run the code block once BEFORE checking if the condition is true.

With the above rule in mind, you can do the simplest and most traditional form of the DO / WHILE loop…

int x = 0; //I needed something to check for my condition

do
{
    Console.WriteLine("The value of x is " + x.ToString() + " ...");
    x++; // 'x++' is a shorthand for 'x = x + 1' or 'x += 1'
}
while( x < 5);

Explanation:

  • I made a variable x, as an integer, as I needed something to check in my condition statement, and a way to exit the loop.
  • The code block will execute first, and when it is done, the condition is checked, if it is true, the loop continues
  • The entire time the condition statement is true, the code block will execute.
  • I wrote the output of my variable x to the console again, and since this is a simpler form of loop, I added my own iteration statement to increment x by one.
  • When x gets to 5, my condition is no longer true, so the loop is complete, and we move on.

Output:

The value of x is 0 ...
The value of x is 1 ...
The value of x is 2 ...
The value of x is 3 ...
The value of x is 4 ...

FOR EACH loop

The FOR EACH loop is composed of the following structure:

foreach( [ Type ItemName ] in [ SomeTypeOfCollection ] )
{
[ This is the code block ]
Code you want to run until all of your items (ItemName) have been iterated through
}


  • This will iterate over all the items in a collection, and run some code for each one, and continue when done.
List<string> lstRadioHeadSongs = new List<string>(){"Karma Police", "Creep", "Fake Plastic Trees", "Paranoid Android"};

foreach(string niceSong in lstRadioHeadSongs)
{
    Console.WriteLine($"I like the song {niceSong} by Radiohead."); //This is string interpolation
}

Explanation:

  • I created a list of strings, and I added some text to it.
  • In the loop, for each item in my list, I printed some text
  • When I ran out of items, the loop is done

Output:

I like the song Karma Police by Radiohead.
I like the song Creep by Radiohead.
I like the song Fake Plastic Trees by Radiohead.
I like the song Paranoid Android by Radiohead.

BREAK / CONTINUE (Controlling a loop manually)

BREAK
To jump OUT of a loop completely, you can use the break keyword.
Example:

for(int x = 0; x < 5; x++) // 'x++' is a shorthand for 'x = x + 1' or 'x += 1'
{
    if(x == 3) break; //This will exit this loop right here

    Console.WriteLine("The value of x is " + x.ToString() + " ...");
}

CONTINUE
To jump OUT of a loop for ONE iteration, you can use the continue keyword.
Example:

for(int x = 0; x < 5; x++) // 'x++' is a shorthand for 'x = x + 1' or 'x += 1'
{
    if(x == 3) continue; //This will exit this loop right here, but keep running the loop

    Console.WriteLine("The value of x is " + x.ToString() + " ...");
}

Note: If you are inside multiple loops, both of these keywords apply to the closest enclosing loop statement. Maybe an example would help:

List<string> lstRadioHeadSongs = new List<string>(){"Karma Police", "Creep", "Fake Plastic Trees", "Paranoid Android"};

foreach(string niceSong in lstRadioHeadSongs)
{
    Console.WriteLine($"I like the song {niceSong} by Radiohead."); //This is string interpolation
    for(int x = 0; x < 5; x++)
    {
        Console.WriteLine("Woot"!);
        if(x == 2) break; //This only exits THIS loop, the regular for loop in this example
    }
    //You exited to here
}
//You did NOT exit here

Bonus → GOTO loop

I’m going to get some :fire: heat :fire: for this one, but I don’t care. :dumpster_fire:
The goto keyword has a bit of a bad rep, but the keyword itself is not inherently bad. Improper use however can be um, let’s just say detrimental. We can have the goto discussion more later. As for now, it’s mentioned here as it can be used for looping, and in some (very) early programming languages, it was pretty much the only way before other control structures were introduced.

  • A loop with goto is completely manual.
  • The goto keyword is an unconditional jump instruction. (Again, if you want conditional, you’ll have to do it.)
  • The goto keyword changes execution flow to a label in your code, which could be almost anywhere, so it needs to make sense. (ah I’m getting off topic)

Anyway, on to the bonus example:

    int x = 0; //I needed something to check for my condition

    loopStart:
        Console.WriteLine("Yo");
        x++;

        if(x > 2) goto loopEnd;
        goto loopStart;
    loopEnd:        

    Console.WriteLine("Adrian");

Explanation:

  • I made a variable x, as an integer, as I needed something to check in my condition statement, and a way to exit the loop.
  • I added a label loopStart:, so I could jump back to it.
  • I did my work inside, writing “Yo” and incrementing x.
  • I checked a condition on x, and if it was true, I would jump to my label at the end of the loop: loopEnd:
  • If my condition was not met, it continues to the next line, which jumps back to loopStart:, thus looping
Yo
Yo
Yo
Adrian
4 Likes