The C# For Loop: Iterate Through a Number of Values

csharpdatatypesC# is one of the prime languages used in Microsoft’s ASP.NET suite of programming languages. Most programmers lean towards either C# or VB.NET. C# is easiest to learn if you are familiar with C-style languages. With C#, you can later dive into C++, Java and other C-derived languages. One aspect of all programming languages you need to know is the “for” loop. The C# for loop iterates over a set number of values, and it’s an essential part of being a full-time, well-versed programmer in any language.

Learn how to get started with C#.

What is a For Loop?

Every new programmer learns loops and conditional statements. There are several types of loops, but the for loop is probably the most common with the “do while” and “while” loops being the second most common. For loops are typically used when you have a specific number of iterations you want to use.  The iteration can be a static value such as hard coded into a static, constant variable or you can dynamically set a variable’s integer value and loop through the assigned number of values.

There are two types of for loops: the regular “for” with numerically assigned iterations or the “foreach” loop that iterates through an enumerated collection. C# supports both types of loops, and they are essential in C# web forms or MVC applications.

MVC is the latest Microsoft programming technique. Get started to keep current in the industry.

The Regular For Loop

When you’re designing an application, you typically write down the business logic for the application before coding. From the business logic, you design the code. You use for loops when you have a set of values you need to manipulate. For loops work closely with array variables, such as iterating through a number of values stored in a string or integer array. For instance, if you have an ecommerce site, you might want to iterate through a number of products to display the product information. This would be accomplished using a for loop.

To get started with for loops, you first need an array. The following example is how you define a string array with five colors assigned:

string[] colors = new string[5];
colors[0] = “red”;
colors[1] = “green”;
colors[2] = “pink”;
colors[3] = “purple”;
colors[4] = “orange”;

Notice the brackets after the “string” variable data type definition. This indicates to the compiler that you are defining an array of type “string” with the name “colors.” When you define the array, you must instantiate it. The “new string[5]” defines the number of values the array can hold. A common misunderstanding for new programmers is the difference between the number of values the array can hold and the array’s index. In this example “string[5]” holds five values, but these values are indexed from 0 to 4. Therefore, when you work with the for loop, you manipulate these values using index numbers 0 through 4 and not 1 through 5.

Learn for, foreach, while and do while loops for C#.

With the array initiated to 5 values, the next lines of code assign a color to each array index. There are several ways you can do this step, and you can even add another for loop to assign values. The way you assign the values is either static or dynamic. In this example, static values are assigned to the array, but you can later assign values dynamically.

The next step is to set up the for loop template. The for loop has a specific syntax in order to loop through each value. The following C# code is the for loop syntax without any business logic or function (we will add that later):

for (int i = 0; i <= colors. Length – 1; i++)
{
}

Notice the for loop has three logic and variable definitions. The first definition is stored in the variable “i.” In this example, the variable i is not only initiated with the “int” data type, but it’s also given a value (the value 0). You can start a for loop with any integer value, but most for loops start with 0, because an array starts with the index 0. For instance, if you only want to iterate through the last 3 values of the array, you assign the value 2 to the i variable.

The second logic section defines the number of times the for loop will iterate through the array. The logic in this section basically says “loop through this array based on the length of the array.” In this example, “colors” contains five values, so “colors.Length” returns the number 5. Notice, however, that length is returned but decremented by 1. This, again, is because of the way arrays index values. If the length was not decremented by 1, then the logic would say to iterate until the loop reaches the fifth index element. An array with 5 values has an index from 0 to 4, so the number 5 would throw an error since the fifth index does not exist.

The third for loop logic element is a simple increment assignment. Each time the for loop performs one iteration, the i variable is incremented by one. You aren’t limited to only incrementing by one. You can decrement by one, increment by two or more values or decrement by two or more values. The way you increment or decrement the for loop is dependent on your business logic.

Now that you have the for loop set up, you add your business logic. In this example, we display the colors to the user. Here is the total for loop logic that iterates through the “colors” array and prints out each color to the screen:

for (int i = 0; i < colors. Length – 1; i++)
{
         string color = colors[i];
         Console.WriteLine(color);
}

In this example, the value of each iteration is stored in the variable “color.” Each value of i is incremented, so a new value is obtained using “colors[i].” For instance, the variable i is assigned the value 0 for the first iteration. Therefore, the first iteration assigns the color “red” to the variable “color,” because “red” is stored in the index 0 (color[0]).

After 5 colors are printed out, the for loop exits and the next line of code after the closing bracket is execute.

There are two ways to control the execution and iterations of the for loop. The “continue” and “break” keywords are important to understand. If you want to exit the for loop prematurely, you use the “break” keyword. If you want to skip an iteration, you use the “continue” keyword.

For instance, if you want to exit the for loop after the third iteration, the following code applies:

for (int i = 0; i < colors. Length – 1; i++)
{
         string color = colors[i];
         Console.WriteLine(color);
         if (i == 2) // notice it’s not 3. When i = 2, it’s the third iteration
         {
                  break;
         }
}

In some cases, you might just want to skip one iteration. For instance, if you don’t want to print out the color “red” but you want to print all remaining colors, the following code applies:

for (int i = 0; i < colors. Length – 1; i++)
{
         string color = colors[i];
         if ( color == “red”)
         {
                   continue;
         }
         Console.WriteLine(color);
}

The break and continue keywords let you control how you manipulate and print data within the for loop, so you don’t need to iterate over values that you don’t want to use.

The Foreach Loop

As you can see, the regular for loop relied heavily on an iteration value. In this example, the “i” variable was used to control the number of iterations and the values assigned from the array. The other type of common variable used in C# for loops is a collection. A collection is a type of key-value pairs or list of values that contain several types. For instance, you can have a collection of a certain class or object. A collection of strings would have a generic list of string values. With enumerated collections, you can loop through each key-value pair without the hassle of the control variable such as “i” in the previous examples.

To get started, you first need to create the collection. In this example, the collection is a generic list. Generic list data types contain a collection of values based on the defined collection type. For instance, you can create a collection of strings. The following example creates a list of colors, and instead of using an array, the colors are assigned to the collection list:

var colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("pink");
colors.Add("purple");
colors.Add("orange");

Notice there is no predefined number of index values. Instead, the list lets you continue to add values without worrying about index assignment.  There is one alternative to assigning values to the collection. The following syntax performs the same assignment, except you eliminate some lines of code:

var colors = new List<string> { " red ", " green ", " pink ", " purple ", “orange” };

The next step is setting up your foreach loop. The foreach loop is slightly different than the regular for loop. The following syntax sets up the template for your foreach loop:

foreach (var color in colors)
{

}

Notice the foreach loop is much simpler than the regular for loop. There’s no control integer, and the foreach loop knows exactly where to start and where to end without any logic operations.

In the above example, each value is assigned to the variable “color” without manually assigning the colors. The “var” keyword does not assign a value data type, and it’s often used when looping through more complex collections. You could use “string” in place of “var” in this example, because you know the return value is always a string. However, most loops use the “var” keyword to avoid data type assignment errors.

After you’ve set up the foreach control structure, you perform your business logic. In this example, we perform the same function as the regular for loop and display the colors assign in the collection. The following code completes the foreach loop:

foreach (var color in colors)
{
        Console.Write(color + “, “);
}

In addition to the syntax being somewhat similar to the regular for loop, the foreach loop also supports the use of the “break” and “continue” keywords. In the same way you exit the loop or continue with the next iteration, you use these same keywords in the foreach loop. For instance, if you want to skip the iteration when the color is red, you can use the following syntax:

foreach (var color in colors)
{
         if (color == “red”)
                    continue;
         Console.Write(color + “, “);
}

The foreach loop is much easier to work with. Most programmers avoid using foreach with arrays, but it is possible to use this loop with arrays as well.

Regular For versus Foreach

For new developers, you might have a question of when to use the regular for loop and when to use foreach. There are two reasons to use foreach:

1)      If you don’t know the underlying data type, foreach is more forgiving. As long as the variable (array or collection) can be enumerated, then you can use foreach. You can also use foreach with complex data types such as classes and dictionary key-value types.

2)      The foreach loop eliminates the possibility of going out of index scope. If you aren’t sure how many iterations you need and you can’t calculate it in the code, use foreach.

3)      When you need to iterate based on other factors besides index value. If you need to jump around the array or collection and add and remove values, a foreach loop makes it easier to avoid jumping to an undefined index value.

The C# for loop isn’t the only control structure in the C# language, but it’s by far one of the most commonly used loops. Almost every application has a for loop you’ll need to work with at some point in your programming career. With a better understanding of how these work, you can design and engineer clean code that’s streamlined, more efficient, and has better performance value. After you learn the for loop, you can get a better grasp of other loops such as “do while” and “while,” which are somewhat more complex than the for loop.

Expand your programming languages with C# functions and terminology.