C# Iteration Control - while, do, for and foreach loops Tutorial
In this tutorial we learn how to repeat sections of code in C# with loops like the while, do while, for and foreach loops.
We also cover how to nest loops, break out of a loop and how to skip to the next iteration of a loop.
What is iteration control (loops)
Iteration control structures allow us to repeat certain sections of code in our application.
As an example, let’s consider an email subscription. We use a loop to go through each user in a database one by one, and send them the email.
C# has the following iteration statements:
- while
- do while
- for
- foreach
The while loop
A while loop statement in C# repeatedly executes a statement as long as a given condition is true.
If our condition is true, whatever is inside the code block will be executed repeatedly. Until our condition is false, the while loop will continue to execute the code.
while(condition)
{
// code to execute while
// condition is true
}
using System;
namespace ControlFlow
{
class Program
{
static void Main(string[] args)
{
int i = 0;
while(i <= 10)
{
Console.WriteLine("i : {0}", i);
i++;
}
Console.ReadLine();
}
}
}
In the example above our variable i will start at 0 and increment with 1 each time the loop runs. When i gets past 10, the condition will be false and the loop will stop.
In this case we specified a number of times to loop but usually a while loop is used when we don’t know the amount of times we want to loop.
The do/while loop
The do while loop is almost the same as the while loop. We can think of a do/while loop as a reverse while loop.
Where a while loop tests the condition at the start of the loop, the do/while loop will check the condition at the end. This guarantees that the code will execute at least once.
The compiler will execute whatever is inside the do code block, then check if the while condition is true. If the condition is true, loop again. If not, stop the loop.
do
{
// code to execute
}
while(condition);
Because the condition is at the end, we must terminate the do/while loop with a semicolon.
using System;
namespace ControlFlow
{
class Program
{
static void Main(string[] args)
{
int i = 11;
do
{
Console.WriteLine("i : {0}", i);
i++;
}
while(i <= 10);
Console.ReadLine();
}
}
}
In the example above our variable i has the value of 11 so the condition is false, but the code still executes.
A do/while loop is used when we don’t know the amount of times we want to loop and we want the code to execute at least once.
The for loop
A for loop in C# will loop through and execute its code a set number of times.
In a for loop we have a counter variable, a condition and a counter increment. Each of these are separated with a semicolon.
for(counter; condition; increment counter)
{
// code to execute
}
The condition is usually done on the counter itself. For example, if we want to loop 5 times, we will check if the counter variable number is below 5. Then, each time the loop runs, the counter is incremented by 1.
using System;
namespace ControlFlow
{
class Program
{
static void Main(string[] args)
{
// counter condition increment the counter
for(int i = 0; i <= 10; i++)
{
Console.WriteLine("a : {0}", i);
}
Console.ReadLine();
}
}
}
The for loop in the example above reads like this:
- i is 0
- If i is less than or equal to 10, add 1 to i and execute the code in the block
- Go back to the top of the loop
- i is 1
- Repeat the process until i is 10, then exit the loop
A for loop always has a counter that controls it, as opposed to a while loop that does not need a counter and can be controlled by something else, like a boolean.
A for loop is used when we know the number of times we want to loop, like the size of an array.
The foreach loop
A foreach loop in C# is used to loop over elements in an enumerable object. Something that has some kind of list or array nature.
As an example let’s use the word “Hello”. Each character in the word is separate, but stored in the same container.
H | e | l | l | o |
Let’s look at the syntax before we explain.
foreach(tempVar in enumerable)
{
// code to execute
}
A foreach loop will go through each character separately and assign it to the temporary variable. The compiler will then move into the execution block where we can work with the temporary variable.
Once the loop moves to the next iteration, the value is lost and the next character in the word is assigned to the temporary variable.
using System;
namespace ControlFlow
{
class Program
{
static void Main(string[] args)
{
string message = "Hello World";
foreach (var character in message)
{
Console.WriteLine(" {0}", character);
}
Console.ReadLine();
}
}
}
The example below will show both a for and a foreach loop doing the exact same thing. Even though we can do the same thing with a for loop, the foreach loop makes it much easier to read and work with.
using System;
namespace ControlFlow
{
class Program
{
static void Main(string[] args)
{
string message = "Hello World";
Console.WriteLine(" For:");
for (var i = 0; i < message.Length; i++)
{
Console.WriteLine(" {0}", message[i]);
}
Console.WriteLine("\n Foreach:");
foreach (var character in message)
{
Console.WriteLine(" {0}",character);
}
Console.ReadLine();
}
}
}
In a foreach loop, you don’t need to initialize a counter, or keep track of that counter, it’s done for you.
Nested loops
In C# we can nest one loop inside another loop. The loops will be executed hierarchically, which means the compiler will run an inner loop fully, before it moves on to the next iteration of the outer loop.
As an example, let’s consider a nested loop with 3 iterations in both the inner and outer loop. For each iteration of the outer loop, the inner loop will run 3 iterations. So, the inner loop will run 9 times in total.
while(condition)
{
while(condition2)
{
// code to execute
}
}
do
{
do
{
// code to execute
}
while(condition2)
}
while(condition)
for(counter; condition; increment counter)
{
for(counter2; condition2; increment counter2)
{
// code to execute
}
}
foreach(tempVar in enumerable)
{
foreach(tempvar2 in enumerable2)
{
// code to execute
}
}
If we need to nest loops 3 levels deep, we should consider trying to find a different solution.
Loop control - How to break out of a loop
We can manually break out of a loop any time we wish with the break keyword.
The break statement will break out of the loop and move on to whatever code comes after and outside of it.
while(condition)
{
// condition to break
// out of loop here
break;
}
Typically, a break statement is used with a conditional check, like an if statement.
using System;
namespace ControlFlow
{
class Program
{
static void Main(string[] args)
{
int i = 0;
while (i <= 10)
{
// break at iteration
if (i == 5)
break;
Console.WriteLine(" {0}", i);
i++;
}
Console.WriteLine("\ncode outside of the loop");
Console.ReadLine();
}
}
}
In the example above, the loop is supposed to run until i becomes 10. But, we manually break out of the loop when it i gets to 5.
The compiler then moves on to the print statement after and outside of the loop.
Loop control - How to skip to the next iteration of a loop
A continue statement will skip to the next iteration of the loop. Any code after the continue statement will not be executed.
while(condition)
{
// condition to go
// back to the top
continue;
}
using System;
namespace ControlFlow
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i <= 10; i++)
{
// skip iteration
if (i == 5)
continue;
Console.WriteLine(" {0}", i);
}
Console.WriteLine("\nloop done");
Console.ReadLine();
}
}
}
In the example above, when the loop got to number 5, it skipped back to the start. The loop couldn’t get to the Console.WriteLine() function on the fifth iteration so it didn’t print the number 5.
Then, the loop continued on as normal to print the rest of the numbers.
Summary: Points to remember
- Loops are used to repeat sections of code.
- The while loop will keep looping as long as a given condition is true and is used when we don’t know how many times we have to loop.
- The do while loop will run through the execution code before checking the condition. We use a do while loop when we don’t know how many times we have to loop , but the code has to execute at least once.
- The for loop will loop for a set number of times. We use it when we know how many times we have to loop.
- The foreach loop is used on collection items like arrays or dictionaries to iterate through all the elements in the collection.
- We can nest any loop inside another.
- We can stop and break out of a loop by using the break keyword.
- We can skip to the next iteration of a loop by using the continue keyword.