Lesson 2.3.3 The "for" statement
I won’t lie to you; this is not the prettiest looping technique. The block of code below performs the same task as in the previous examples. It prints the numbers from zero to ten.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Loops3
{
class Program
{
static void Main(string[] args)
{
for (int x = 0; x < 11; x++)
{
Console.WriteLine(x);
}
System.Console.ReadKey(true);
}
}
}
This way of doing things is a little more hardcore than the others. As you can see, it uses fewer lines. It’s certainly compressed the whole loop down a bit. There is still the loop’s logic enclosed by a set of {} braces. The bit that is messy is the opening for statement. The way to understand it is to break it down to its three parts.
The initialisation
for (int x = 0; x < 11; x++)
This type of loop can create and initialise its own indexing variable. In the case of the example above, the indexing variable is called x. It is set to zero. Changing the value will make the count up go from your new value to 10. (As long as the value you change it to be is less than 10 of course!)
The condition
for (int x = 0; x < 11; x++)
This is the condition that must be true for the loop to carry on. In this case, I am asking the loop to go round all the while x is less than 11.
The change
for (int x = 0; x < 11; x++)
This change statement is the way that the indexing variable will be altered when it goes round.
Remember the incrementing statement from the previous loop? x = x + 1? This is a very common operation. C#, like most languages in its family has a shorthand for this statement; x++. Naturally there’s an opposite, an equivalent of x = x - 1, it is x--. Who didn’t see that coming? To make things a little more fun, you can place the symbols before the variable name. Yes, ++x does the same thing, apparently though it is one CPU clock cycle quicker although I have heard arguments querying it. My attitude is that it doesn’t hurt to use it.
The numbers don’t necessarily need to go up. You could make it count down if you alter the “for” statement to that below.
for (int x = 10; x >= 0; x--)
But what if you wanted to increase your indexing variable by more than 1 each time? What if you had a need to show all of the even numbers between 0 and 10? The more perceptive amongst you would say what’s wrong with x = x + 2? Actually, nothing’s wrong with that. But if typing all of those letters is a bit of a chore then it can be reduced into shorthand too: x += 2. Swap it out for x -= 2 to make it go in the opposite direction.
The best way to learn is to tinker with the code and see what you get.