Professor Mustard Programming
 

Programming 101 - Unit 02 - Flow Control

02c) For Loop
 
As with any language, human or machine, there are many different ways to say the same thing. The "for" loop is an example of that. There's nothing a "for" loop can do that a "while" loop can't, but the "for" loop is specifically designed for counting. Here's a basic example:

for(int count = 1; count < 6; ++count)
{
  Console.WriteLine("Count is " + count);
}



The above code actually does the same thing that our earlier "while" loop did... namely, it counts from 1 to 5.

There's a lot more going on in that line than we had in the "while" loop, but that's because it's handling three things: declaring a variable to count with, defining the expression that has to be true for the loop to continue, and incrementing the variable. It takes all those little bits and pieces that we had to use with our "while" loop, and groups them onto one line. Still, if you're having trouble peering through all those punctuation marks, let me summarize where everything goes:

for(Declare_Variable ; Boolean_Expression ; Increment)


We use semicolons to separate the three main parts of the "for" loop expression, but that's really the only complexity that this statement adds. By the way, did you ever think of having a loop within a loop? It's as simple as this:

for(int y = 1; y < 10; ++y)
{
  for(int x = 1; x < 10; ++x)
  {
    Console.Write(x*y + "\t");
  }

  Console.Write(Environment.NewLine);
}



For each run through the "y" loop, the entire "x" loop will also run. So that little "Console.Write()" line in the middle will get run 81 times (the "y" loop runs the "x" loop 9 times, and each time, the "x" loop runs the Write() line 9 times). That second Write() statement starts a new line at the end of each run through the "y" loop. What's the end result of all this? A nice, neatly formatted grid that displays a times table, up to the number nine:

1  2  3  4  5  6  7  8  9
2  4  6  8  10 12 14 16 18
3  6  9  12 15 18 21 24 27
4  8  12 16 20 24 28 32 36
5  10 15 20 25 30 35 40 45
6  12 18 24 30 36 42 48 54
7  14 21 28 35 42 49 56 63
8  16 24 32 40 48 56 64 72
9  18 27 36 45 54 63 72 81



Oh, and if you ever needed to declare or increment multiple variables in one for loop, you can do this:

// Declare two variables, "i" and "j"
for(int i= 0, j = 0; i < 0; ++i)
{
}

// Declare and increment two variables, "i" and "j"
for(int i= 0, j = 0; i < 0; ++i, ++j)
{
}



All you do is separate each declaration/increment with a comma. Honestly, though, I've never encountered a situation where I needed to do this. It makes the "for" loop's main line much harder to read, anyway (you wouldn't think a few extra commas would throw it off by much, but it does).

You might also be wondering, what's with this "i" business? Why is the "for" loop variable always named "i"? Well, "i" is really just shorthand for "index". This is an excellent variable name for these cases, because that's exactly what the variable represents - the index in the array that we are currently looking at. In most other cases, having single-letter variable names is a very bad thing, because they mean absolutely nothing, and it can get horribly confusing after you have a few of them swimming around in the same chunk of code. Highly professional programmers will urge you not to use variables with names like "i", even in your loops. I'm not exactly adamant about this, simply because I've encoutered times when "i" actually improved the readability of a small code block by a significant margin (it's really small, and easily recognised for what it is). Nonetheless,  these professionals make a good case. Make a habit of using meaningful variable names.

Anyways, we haven't even shown you the true power of "for" loops, yet. To understand how useful these things really are, we'll have to introduce another new concept: the array. Before that, however, here is a code sample that uses "for" loops:



using System;

namespace C_For
{
  class Class1
  {
    [STAThread]
    static void Main(string[] args)
    {
      // Simple "for" loop
      for(int count = 1; count < 6; ++count)
      {
        Console.WriteLine("Count is " + count);
      }

      Console.Write(Environment.NewLine);

      // Complex "for" loop
      for(int count = 1, power = 2; (count < 6) && (power < 9); ++count, power *=2)
      {
        Console.WriteLine("Count is " + count + ", power is " + power);
      }

      Console.Write(Environment.NewLine);

      // Nested "for" loop
      for(int y = 1; y < 10; ++y)
      {
        for(int x = 1; x < 10; ++x)
        {
          Console.Write(x*y + "\t");
        }

        Console.Write(Environment.NewLine);
      }

      // Prompt for exit
      Console.Write(Environment.NewLine + "Program complete! Hit enter to exit...");
      Console.ReadLine();
    }
  }
}