Introduction to for loops in C#

C# Programming Guide

In C#, loops are used to perform repetitive tasks. For example, a developer might want to display all integers between 1 and 10. In this case, you would need a loop to iterate and display the integers. The C# programming language provides support for several types of loops. These include for, do while, while and foreach loops.

In this programming tutorial we will examine the for and foreach loops, and how each of these work with relevant code examples in each case to illustrate the concepts discussed.

Looking to learn how to program in C# in an online environment? We have a list of the Best Online Courses to Learn C# Development.

What is the for Loop in C#?

The for loop is a kind of repetition where we iterate over a sequence of items. This may be a sequence of numbers, characters, or anything else you can think of. It allows programmers to repeat an action for each item in this sequence. The syntax of a for loop in C# is as follows:

for(initialization; condition; increment) {
// Write your code here. This is the body of the loop 
}

A for loop contains three parts: the initializer, the condition evaluator, and the re-initializer. The following are the three sections of a for loop in C#:

  • Initialization: This will initialize the loop control variable, which is used to maintain the state of the loop. This is the section where the loop control variables are initialized. Note that you can use multiple variables here.
  • Condition: The condition determines whether the loop will execute or not. If this expression evaluates to true, then it will execute another iteration of the loop body, but if it is false, the execution of the loop will be terminated.
  • Iteration: This is the section that is used to re-initialize the loop control variable before evaluating the loop condition again in order to decide if we need another round of execution of the loop body or not.

What are for Loops Used for in C#?

The primary benefit of for loops is that they make it very easy to iterate through the elements of an array or collection; programmers simply declare some variables and then use them to initialize each element as they iterate through the loop.

Developers do not have to worry about how many elements there are in the array or the collection; you can just keep iterating the elements until you get to the end of the array or the collection.

How to Use the for loop in C#: Code Example

The initialization section is where you declare and initialize any variables that will be used in the loop. Every time the loop is iterated, the body of the loop is executed if the specified condition is true for each iteration.

When the condition in the loop evaluates to true, the body of the loop will run. Whenever the condition of the loop is false, the loop terminates, (i.e., the loop body does not execute any further). The increment section is where you update your variables.

Here is example code of a for loop in C# that prints out the numbers 1 through 10:

for(int i=1; i<=10; i++) 
{ 
    Console.WriteLine(i); 
}

Note that the re-initialization section is optional; if you omit it, your variables will not change on each iteration of the loop. However, you must specify how the variable is re-initialized in the condition section to avoid an endless loop.

Programmers can also write the preceding code as shown below:

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

Note that the re-initialization section has been omitted (it is optional) here. You can also use the for loop to iterate over a string or an array. For example, you can use the following code example to display each character of a string using a for loop in C#:

string str = "Hello world";
for (int i = 0; i < str.Length; ++i) 
{ 
   Console.WriteLine(str[i]); 
}

As another example, here is some code showing how you can print all items in an array using a for loop in C#:

int[] arr = new int[] { 1, 2, 3, 4, 5 };
foreach (int item in arr)
{
    Console.WriteLine(item);
}

Read: Top 10 Version Control Systems

What is the foreach Loop in C#?

The foreach loop is a variation of the for loop in which you can traverse the elements of the loop in one direction only. The foreach loop allows you to repeat a block of code, or a series of statements, for each element in a list or any collection. The C# foreach loop can be used with all collections, including arrays, dictionaries, and lists. The foreach loop is helpful because it allows you to work with each collection element sequentially without explicitly using an index variable.

How to Use the foreach Loop in C#

The syntax for using a foreach loop in C# is:

foreach (item in collection) 
{ 
  // Write your code here (This is the body of the loop) 
}

Here is how you would use a foreach loop to iterate through an array in C#:

int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers) {
 Console.WriteLine(number);
}

What are the Benefits and Downsides of the C# foreach Loop

The main benefit of using the foreach loop is that it saves programmers time: you do not have to write any additional code to access each element within the collection separately. Traditional for loops can be useful for programs that require more control over how elements are accessed (e.g., for programs that skip elements or perform actions only on other items).

The biggest drawback is that you can not traverse the elements in the collection in the reverse order. Additionally, you are constrained to use the foreach loop with any type of collection that implements the IEnumerable or IEnumerable interfaces.

Final Thoughts on for Loops in C#

Once the loop condition is satisfied, the for loop will execute one or more statements several times. If the loop condition is true, the body of the for loop is executed. Otherwise, the control flow continues to the following statement after the for loop and runs it. In this programming tutorial we discussed the different types of for loops (i.e., for and foreach loops) in C# and how to work with each of them.

Read more C# programming tutorials and software development tips.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read