C# Looping – Part 4

The beauty of code is the ability to do the same task in a repetitive nature with very little work. You could argue this is largely why computers were invented, to perform tedious calculations over and over. Looping allows us as programers to execute blocks of code multiple times until a condition is met. Lets look at some of these techniques and talk about their exit conditions.

For Loop – The for loop is probably the most common, its typically used when you need to execute a block of code X amount of times. Here’s an example:

for (int i = 0; i < 5; i++)
    Console.WriteLine("Hello World");

In the above loop we start by initializing a variable i and setting its value to 0, then we check if i is less than 5, then we increment i by 1 and output Hello World to our console. Since i is still less than 5, we continue the process. When i reaches 5, the entire block will be skipped as it does not meet the condition to execute the block inside the braces. As mentioned above, the for loop shines when you know how many times you need to execute the block of code, hence the number 5 in the looping condition. This type of loop is also known as a counting loop, it counts up or down until its exit condition is met. What happens when you don’t know how many times you need execute a loop? Well that’s a great segue into while loops.

While Loop – The while loop checks a condition and if its true executes a block of code. This happens continuously until that condition state changes. Lets look at an example:

bool isSunny = true;

while(isSunny) {
    Console.WriteLine("Sunny skies today!");

First we need a condition, so we created a boolean value isSunny. Since the sun is out today, we set it to TRUE. The while loop is checking to see if isSunny == True. Since this condition is met, it outputs to the console “Sunny skies today!”. This will continue to happen until isSunny is set to false. Inside the braces you would have additional logic that would flag isSunny to false so the loop would end once you’ve accomplished whatever task you need. While loops can be a problem for novice programmers, its very easy to setup an infinite loop and crash your IDE while working with these. Use caution when implementing while loops.

Its important to note that this block of code is exactly the same as the previous:

bool isSunny = true;

while(isSunny == true) {
    Console.WriteLine("Sunny skies today!");

The double equals is implied in the previous version, you can use this shorthand notation when doing if statements and while loops.

Do..While Loop – The do while loop is similar to the while loop except that it checks the condition of the loop at the end of the block. What this means is, the code inside the block will run at-least once, then it checks the condition and could run again. Lets look at an example:

bool isSunny = true;
do {
    Console.WriteLine("Sunny skies today!");
} while (isSunny);

As you can see, this code is going to be problematic. What if isSunny = false? The loop is first going to tell us its sunny, then exit the loop because the condition is false. So we’ve basically told the user its sunny outside without checking to see if it is sunny. While this type of loop has its use cases, it’s not widely used. Just know that the body of the code will always run once, then check to see if it needs to loop.

Nested Loops Nested looping is taking any of the previous loops and then nesting another loop inside of it. This commonly used for many different reasons. Lets say you’re building a 2D game that requires a battle grid. You could use nested for loops to create an xy grid. Here’s the structure of a nested loop:

for ( int i = 0; i < 5; i++ ) {
   for ( int j = 0; j < 5; j++ ) {
      //do something when i is at 0
      // and j is at 0

     // next iteration would be i=0, j=1. Then i=0, j=2.
     // once j = 5, then i would increment to 1 and j would start at 0 again

Write a program that loops over the numbers from 0 to 100 and write to the console any number that is divisible by 3. Post your code here! Good luck and feel free to ask questions.

Leave a Reply