C# For Loops

Dec 2011

Basic C# for

The C# for statement is used to loop through a series of items. This is referred to as "iteration". The most basic version uses a simple index variable that is incremented once per iteration. It's very common in for loops to name this variable "i". Let's look at an example of a basic C# for loop:

int total = 0;
for (int i = 1; i <= 3; i++)
    total += i;

The line total += i; is executed 3 times. The first loop i is equal to 1, the next loop it is equal to 2, the last loop it is equal to 3. When the for loop is all done the total variable will be equal to 6 (1+2+3). The three parts of the for statement are separated by semi-colons and are named "initialization", "condition" and "step": for (initialization; condition; step). They have the following purposes:

  1. "initialization" (int i = 1) defines the iteration variable and sets its intial value.
  2. "condition" (i <= 10) defines the end-condition. The for loop ends when this condition evaluates to false.
  3. "step" (i++) defines what happens to the iteration variable at the end of each iteration.

Sequentially here's what happens in the above code:

  1. int total = 0
  2. int i = 1
  3. evaluate (i <= 3), not false for i=1 so we continue looping
  4. total += i, add 1 to total
  5. i++, i now equals 2
  6. evaluate (i <= 3), not false for i=2 so we continue looping
  7. total += i, add 2 to total
  8. i++, i now equals 3
  9. evaluate (i <= 3), not false for i=3 so we continue looping
  10. total += i, add 3 to total
  11. i++, i now equals 4
  12. evaluate (i <= 3), false for i=4 so we stop looping

A great way to learn how the for statement works is to step through the code line-by-line with the Visual C# debugger. Keep a watch on the value of i.

Let's run our for loop in reverse (3 to 1):

int total = 0;
for (int i = 3; i > 0; i--)
    total += i;

Make sense?

break and continue

We can control for loop iteration (and iteration in general) with the break and continue statements. break terminates iteration and continue skips to the next iteration cycle. To demonstrate:

for (int i = 1; i <= 10; i++)
{
    if (i == 2) continue;
    if (i == 4) break;
}

This code will execute like so:

  1. int i = 1
  2. evaluate (i <= 10), not false for i=1 so we continue looping
  3. evaluate (i == 2), not true for i=1 so we don't execute the continue statement
  4. evaluate (i == 4), not true for i=1 so we don't execute the break statement
  5. i++, i now equals 2
  6. evaluate (i <= 10), not false for i=2 so we continue looping
  7. evaluate (i == 2), true for i=2 so we execute the continue statement
  8. i++, i now equals 3
  9. evaluate (i <= 10), not false for i=3 so we continue looping
  10. evaluate (i == 2), not true for i=3 so we don't execute the continue statement
  11. evaluate (i == 4), not true for i=3 so we don't execute the break statement
  12. i++, i now equals 4
  13. evaluate (i <= 10), not false for i=4 so we continue looping
  14. evaluate (i == 2), not true for i=4 so we don't execute the continue statement
  15. evaluate (i == 4), true for i=4 so we execute the break statement and stop looping

Notice how, after step #7, the rest of the code in the for loop doesn't execute. That's what the continue statement does - skips the current iteration and goes on to the next. The other thing to notice is that we've enclosed the loop statements in curly braces {}. It's OK to omit the braces when the for loop has only one iteration statement. As soon as you have more than one you need to wrap them in the braces.

Looping Through An Array

Suppose we have an array of things and we would like to loop through them, examining each item as we go. The following example demonstrates how loop through the characters in a string using C# for.

char c;
string alphabet = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < alphabet.Length; i++)
    c = alphabet[i];

For each iterate of the for loop the c variable will be set to the next letter of the alphabet. There are a couple things to note here. First, arrays in C# start with index 0. alphabet[0] equals the letter 'a'. Second, arrays have a property called Length that returns the number of items in the array. So, alphabet.Length will return 26. The loop goes from i equals 0 to i equals 25, then ends.

We keep using "i" as the name of our for-loop variable but we can actually use anything we want. For example:

string alphabet = "abcdefghijklmnopqrstuvwxyz";
for (int letter = 0; letter < alphabet.Length; letter++)
    c = alphabet[letter];

There is another way to loop through an array - we can use the foreach statement. It is actually a bit simpler than C# for statement. Example:

foreach (char letter in alphabet)
    if (letter == 'q') break;

Notice that we don't have to specify the end-condition and iterate-action like we did with for. And we get the item in the array directly each iteration - we don't have to use letter to index alphabet, letter already contains the char. This is simpler but we lose a bit of the control we had with the classic for statement. We can't chose to iterate in reverse or start at index other than zero.

Nested for Loops

C# allows for loops to be nested. You typically do this when you have to iterate through an array with more than one dimension. Example:

char c;
string[] reservedKeywords = new string[] { "for", "foreach", "break", "continue" };
for (int i = 0; i < reservedKeywords.Length; i++)
    for (int j = 0; j < reservedKeywords[i].Length; j++)
        c = reservedKeywords[i][j];

The first for loop iterates through the strings in the reservedKeywords array. The second for loop iterates through the characters in each reservedKeywords string. The c variable will equal, sequentially, 'f', 'o', 'r', 'f', 'o', 'r', 'e', 'a', ..., 'u', 'e'. Make sense?

Off-By-One

It's not uncommon to be off by one when figuring out where to begin and/or end a for loop. Here's an example that is coded with an error:

char c;
string s = "A C# for statement tutorial.";
for (int i = 0; i <= s.Length; i++)
    c = s[i];

See it? The end-condition (i <= s.Length) is allowing i to equal s.Length on the last iteration. Since arrays start at zero the last character of s is at index s.Length - 1. Calling s[s.Length] will result in a runtime error "Index was outside the bounds of the array." Not good!

Infinite Loops

An infinite loop is a loop that never ends. This is usually, but not never, a bad thing. It's also very easy to do. Example:

for (int i = 0; ; i++)
{
    // do something here
}

We've omitted the end-condition so the loop will never end. Note that i won't increase to infinity, it will increment to int.MaxValue and then increment from there to int.MinValue.

for Alternatives

The most common loop statement alternative to for is probably while. while is really just a for without the "initialization" and "step" parts. To recode our first example:

int i = 0;
int total = 0;
while (i <= 3)
    total += i++;

while is commonly used for unbounded iteration. Like so:

bool b = true;
while (b)
{
    // code that eventually sets b to false
}

The latest versions of C# have an even more interesting alternative to the for-loop. It's called LINQ and it is a way to avoid loops altogether. LINQ makes particular sense when you're writing a for loop that is searching for a item (or items), counting items of a certain kind, translating data, or querying a collection. We won't go into detail on LINQ here but we'll provide some examples that demonstrate how to replace for loops with LINQ equivalents.

// for loop that counts the occurrences of the letter 'a'
int count = 0;
string s = "LINQ can be used to replace for loops";
for (int i = 0; i < s.Length; i++)
{
    if (s[i] == 'a')
      count++;
}
// equivalent LINQ
int count = (from a in "LINQ can be used to replace for loops" where a == 'a' select a).Count();

The LINQ version is much more concise and easier to maintain. One more example:

// for loop that finds the first letter of each word
string[] words = new string[] { "LINQ", "can", "be", "used", "to", "replace", "for", "loops" };
List<char> firstLetters = new List<char>();
for (int i = 0; i < words.Length; i++)
    firstLetters.Add(words[i][0]);
// equivalent LINQ
char[] fls = (from s in words select s[0]).ToArray();

Summary

That about covers everything you need to know to get programming with the C# for statement. Happy looping.

Comments Add a Comment Name: Comment: Enter the text in the image below:
w3 enterprises