Learning Loops

Loops in C# are wonderful and powerful statements that you can utilize when programming. These statements allow you to execute code or groups of code several times until a threshold has been reached or a condition is satisfied. On this page we will be talking about two of the most popular loop types – The for and while loops. To frame your intuition on loops, let me first present you a problem that a loop would solve.

Let us suppose for a moment that we want to – for some reason- arbitrarily have the console print out the numbers 1-5. Given your current knowledge you might presume to write the following code:

static void Main(string[] args)
{
     Console.WriteLine("1");
     Console.WriteLine("2");
     Console.WriteLine("3");
     Console.WriteLine("4");
     Console.WriteLine("5");
     Console.ReadLine();
}

Honestly, this could be a valid way to go about it – if your only standard is to have a desired output. I would raise a few concerns, though. First, it seems a bit cumbersome to type a Console.WriteLine 5 different times. Second, if we wanted to add in a new number we would have to, again, create a new Console.WriteLine with a new value. When you are programming you should always ask yourself if the way you are coding allows you to easily make changes – this case does.

The following way will show you why using a for loop DOES  satisfy this.

static void Main(string[] args)
{
     for(int i = 0; i < 5; i++)
     {
          Console.WriteLine(i);
     }
     Console.ReadLine();
}

Don’t get nervous if this looks weird to you. It’s actually quite simple. A for loop has parentheses where we provide it some values, as you would with a function/method. In this loop we create an integer called i and instantiate it to 0. We then have conditional logic that checks if i is less than 5. If the condition is considered true it will then execute i++ and also the logic within our for loops scope(Curly braces). When this logic is executed it will call a Console.WriteLine and provide it with the current integer value of i. Every time this statement loops, our i integer will increase by 1. Once i is greater than or equal to 5 the statement will be satisfied and will break our loop and continue to the Console.ReadLine.

Solved: Repeating Code

We know only have to type Console.WriteLine once and instead provide a new value each time.

Solved: Easy Changes

Now if we wish to change the value of how much our console counts to, we simply change the number in our conditional of i < 5 to the desired count. Whether we want it to count to 7, 15, 25 or 100. By simply changing this one value we are able to count as high as we want.

 

Take Note: Using for loops must maintain this format, but the method in which it is implemented it not concrete. The values regulating the for loop could just as easily be integer variables within the scope of the loops declaration. The following is also appropriate:

static void Main(string[] args)
{
     //Number we count to
     int _maxValue = 5;
     //Current number counted
     int _currentValue;

     //Write a line on value increase
     for (_currentValue = 0; _currentValue < _maxValue; _currentValue++)
     {
          Console.WriteLine(_currentValue);
     }
}

 

While Loop

The while loop, and loops in general, is a similar concept. For loops are designed for looping in specific lengths. A While loop is designed for a true/false value. This means we can continue to execute logic indefinitely, until a provided condition is satisfied. This example is not very practical, but I found it a fun concept to help explore this topic. Basically, we have a Boolean value that allows us know if our computer is angry. While our computer is angry, we are asked to press Enter to calm our computer down.

static void Main(string[] args)
{
     //Bool for whether the computer is currently angry
     bool isComputerAngry = true;
     //Anger level of the computer
     int angerLevel = 5;

     //Run this loop while the computer is angry
     while (isComputerAngry)
     {
          //Print anger level
          Console.WriteLine("Anger Level(0-5):{0}", angerLevel);
          //Inform the user how to calm the computer down
          Console.WriteLine("Press Enter to calm down...");
          //Wait for input
          Console.ReadLine();

          //Reduce anger level on each input until anger level reaches zero
          if (angerLevel > 0)
          {
               angerLevel--;
          }
          else
          {
              isComputerAngry = false;
              Console.WriteLine("Computer has calmed down!");
              Console.ReadLine();
          }
     }
}

We see in this example that we accomplish what we did before. In fact, with a few changes we could have even used a for loop to do this as well. The importance I wanted to show here is that we use While loops to continue until something is satisfied. In contrary to a For loop that is designed to loop for a specific count.

 

<< Previous Episode

Next Episode >>

 

Leave a Reply

Your email address will not be published. Required fields are marked *