C# For Loop

      for (int i = 0; i < 5; i++) 
      {
        Console.WriteLine(i);
      }    

A For loop is best used for when you know how many times you want to iterate through something or how many times you want to do something.

A for loops syntax is broken up into 3 simple parts.

for(initializer, condition, incremental)

  • Initializing variable which is executed one. Example: int i = 0;
  • Condition definition. This is what tells the loop how many times to go through the loop sequence. Example: i < 5;
  • incremental condition. This is executed every time the loop is executed. Example: i++

So with this we now will have:

      for (int i = 0; i < 5; i++) 
      {
        Console.WriteLine(i);
      }    

This will result in an output of: 0 1 2 3 4. Since we are writing the int variable of “i” to the console which start at 0.

Now we could implement other code we want instead of the Console.WriteLine(i);
We are able to have other methods called, run other snippets or code, or almost anything your imagination could imagine.

ForEach

Now that we have basic loops, what if we have a list of items we want to iterate over? Could we do the same thing? Is there a better method?

First off, let’s say we have an array we want to use of some names. Example:
string[] names = {"Jim", "Bob", "Will", "Steve", "Frank"};

Now let’s use our for loop to iterate over the array of names. Instead of using “i < 5”, we can get the length of the array.
for (int i = 0; i < names.Length; i++)

And finally, lets write which name we want to print to the console: Console.WriteLine(names[i]);

The end result would look like:

string[] names = {"Jim", "Bob", "Will", "Steve", "Frank"};
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine(names[i]);
}

Instead of using a “for” lets use “foreach”. And the syntax is a little different.
foreach(type variable in array)

So using the same example as above, we can simply now use:

string[] names = {"Jim", "Bob", "Will", "Steve", "Frank"};
foreach (string name in names)
{
Console.WriteLine(name);
}

Leave a Reply

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