Website development and design blog, tutorials and inspiration

Looping and Iteration in C#

Loop control in C#

By , 6th November 2007 in C#

When programming, it is often necessary to repeat a task many times. This is a process known as iteration or looping. C# has a number of methods for looping: Do, While, For and Foreach and in this article, we take a look at each of them and how you use them.
 

The type of iterative loop is governed by how it should perform and what data types are involved. Some loops check the exit condition before they exit the loop, while others guarantees at least one pass.

The While Loop

The simplest loop is the while loop. This is a loop that executes a code block while the condition is true.

  1. int i = 1;
  2. while (i <= 10)
  3. {
  4. Console.WriteLine("Loop {0}", i);
  5. i++;
  6. }

This will output:

Loop: 1
Loop: 2
Loop: 3
Loop: 4
Loop: 5
Loop: 6
Loop: 7
Loop: 8
Loop: 9
Loop: 10

There is a danger however that you will get caught in an infinite loop.

An infinite loop occurs when the exit condition is never met, an example of which would be if you forgot to increment i within the loop. The exit condition will always be less than 10, so the loop will never exit.

A while loop will check the condition before entering the loop, and if the condition is met first time there will be no loop.

  1. int i = 12;
  2. while (i <= 10)
  3. {
  4. Console.WriteLine("Loop {0}", i);
  5. i++;
  6. }

 

The Do... While Loop

The do while loop is similar to the while loop, except that it does not check the condition until the end of the first iteration. You are guaranteed to have a minimum of one iteration every time.

  1. int i = 1;
  2. do
  3. {
  4. Console.WriteLine("Loop {0}",i);
  5. i++;
  6. } while (i <= 10);

Again, you must increment the loop counter yourself to avoid being caught in an infinite loop.

 

The For Loop

The for loop is one of the most common type of loop. It will loop from a starting count to a ending count then stop. For example you can loop through numbers 1 to 10. The basic format for a for statement is:

  1. for (start value; end condition; increment counter)
  2. {
  3. // Code to repeat
  4. }

Looping from 1 to 10 as our first example will be coded as follows:

  1. for (int i = 1; i <= 10; i++)
  2. {
  3. // Code to repeat
  4. }

It looks a bit complicated, so we'll go through each aspect in turn.

int i = 1: Declares a variable called i and initiates the value to 1. This is the loop starting value.
i<=10: The program will loop as long as i <= 10. Once this condition is no longer met the loop will exit. i++: Increment the value of i by 1 for the next iteration.

You cannot change the value of i within the code to repeat, but you can access its value:

  1. for (int i = 1; i <= 10; i++)
  2. {
  3. i = 67; // This line will ERROR!
  4. Console.WriteLine("Loop: {0}", i);
  5. }

Once the line in error is removed, the program will output:

Loop: 1
Loop: 2
Loop: 3
Loop: 4
Loop: 5
Loop: 6
Loop: 7
Loop: 8
Loop: 9
Loop: 10

The ending condition does not have to be a fixed value; you can use a function that returns an int. For example, you can loop through all the values in an array (these will be in detail covered later) using the count function to return the number of elements in the array. You can then use the value of i to access the array element.

  1. string[] daysOfWeek = new string[] {
  2. "Monday",
  3. "Tuesday",
  4. "Wednesday",
  5. "Thursday",
  6. "Friday"
  7. };
  8.  
  9. for (int i=0; i <= daysOfWeek.Length; i++)
  10. {
  11. Console.WriteLine("Day of Week: {0}", daysOfWeek[i]);
  12. }

Will output:

Day of Week: Monday
Day of Week: Tuesday
Day of Week: Wednesday
Day of Week: Thursday
Day of Week: Friday

 

Foreach

The for statement has many individual statements that implement the loop mechanism to iterate through the items of an array. It isn't particularly intuitive and it is prone to error, such as forgetting that the an array index starts from 0 and the array length starts from 1. A foreach statement is a better in terms of readability and is less error prone, however there is a slight performance decrease compared with a for loop.

To iterate through the daysOfWeek array from the previous code, the for loop can be replaced with a foreach:

  1. foreach(string Day in daysOfWeek)
  2. {
  3. Console.WriteLine("Day: {0}", Day);
  4. }

It is much easier to understand what is happening in this example. We declare a value Day of type string (must be the same as the array data type) and it automatically gets assigned the value of daysOfWeek. On the next iteration we get the next array item, and so on until the end of the array is reached.

You cannot assign to the value of Day in this example as it is read only, nor can you modify the daysOfWeek collection.

 

Loop Control

There are two statements that you can use to control the loop from the inside. The first will skip processing the current iteration and continue onto the next. Both of these keywords can be used in a while, for or foreach loop.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication4
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. for (int i = 1; i <= 10; i++)
  13. {
  14. if (i == 5)
  15. continue;
  16.  
  17. Console.WriteLine(i);
  18. }
  19. }
  20. }
  21. }

This will output:

1
2
3
4
6
7
8
9
10
Press any key to continue . . .

As you can see once the continue statement is reached, no other code in that iteration will run, the loop counter gets incremented and the loop continues.

The other control keyword is break, and this is used to break out of the loop altogether.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication4
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. for (int i = 1; i <= 10; i++)
  13. {
  14. if (i == 5)
  15. break;
  16.  
  17. Console.WriteLine(i);
  18. }
  19. }
  20. }
  21. }

Will output:

1
2
3
4
Press any key to continue . . .

Summary and Conclusions

We have seen the four iterative loops, while, do while, for and foreach, and we have seen how they can be used to repeat an action many times on certain types of data.

Comments

There are no comments for this post. Be the first!

Leave a Reply

Your email address will not be published.