In C#, every statement is executed sequentially, but there may be a scenario where we need to execute a certain piece of code several times. To handle such situations, C# offers loops like While, do while, for and for each, which allows the program to run a block of code multiple times. C# offers different loop mechanisms to handle different iterations of code execution, each with their own purpose. Developers will learn how to use these loops in today’s C# programming tutorial.
How to Use Loops in C#
Below are some examples and code snippets showing how to use loops in C#.
How to Use the while Loop in C#
We will begin by learning how to use the most basic loop in C# – the while loop. This loop executes the code block as long as the condition defined in it evaluates to true. Here is an example of how to use while loops in C#:
while(Boolean Condition) { //code }
How while Loops Work
while loops in C# work and function in the following manner:
The code within the curly braces { } of the while loop braces get executed only if the Boolean condition evaluates to true.
The condition in the loop is validated first, before executing the code
Once the code block is executed, the control returns to the Boolean condition for evaluation
If the Boolean condition always returns a true value then it will become an infinite loop – something we want to avoid. Essentially, the code block will loop for eternity, unless the user exits the program.
To get a better understanding, consider the following code:
using System; namespace LoopExampleApplication1 { class MyProgram { static void Main(string[] args) { int num = 0; while(num < 10) { Console.WriteLine(num); num = num + 1; } Console.WriteLine(“After the execution of while loop…”); Console.ReadLine(); } } } //Output 0 1 2 3 4 5 6 7 8 9 After the execution of the while loop…
while Loop Code Explanation
If you run the above code, you will get a nice listing of numbers from 0 to 9. We have initialized a variable named num with the value 0 and each time the loop is executed, it is incremented – or increased – by 1.
You may be asking yourself: why does it print the values only up to 9? This occurs because the while loop will continue to execute the block of statements as long as the value of num is less than 10. Once the value of num reaches 10, the loop will stop execution as the Boolean condition becomes false. Once the Boolean condition evaluates to false, the control will exit the out of the loop and start executing the statements outside the loop.
Read: Tips for Writing Clean C# Code
How to use the do while Loop in C#
The do while loops is very similar to the while loop, with the difference being that the Boolean condition is evaluated at the end of the loop rather than at the beginning. It has a unique feature where it will execute the code block at least once. Here is how to use a do while loop in C#:
do { //code } while( Boolean expression );
How do while Loops Work
The text and example code below explain in further detail how do while loops work in C#.
do while works similar to the while loop. The do keyword is placed at the beginning, while the while keyword is placed after the code block.
Executes the code block at least once, meaning the code will execute at a minimum of one time, regardless of criteria.
using System; namespace LoopExampleApplication1 { class MyProgram { static void Main(string[] args) { int num = 5; do { Console.WriteLine(num); num = num + 1; } while(num < 10); Console.ReadLine(); } } }
In the above code, we have declared a variable named num with an initial value of 5. We have started the loop by placing the keyword do in the beginning, and inside that do block we have defined the code that we want to execute. Here, we are printing the value of num and also incrementing its value by 1 after each iteration through the loop.
After processing this block of code, the control moves to the while statement, where the condition is evaluated while the value of num is less than 10. Once the value of num reaches 10, the condition will become false, as the value of num is no longer less than 10. This causes the control to escape the loop and execute the next line of code outside the loop. The above code example produces the following output:
5 6 7 8 9
Read: Working with Strings in C#
How to use the for Loop in C#
In C#, the for loop is a bit different than a while loop. The for loop is quite useful in situations where you know in advance how many iterations you want to be performed.
The for loop has three parts, separated by a semicolon (;). The first part is an initialization, then we have a Boolean condition to check, followed by the increment/decrement counter. Here is how that looks in code:
for(initializer; Boolean condition; iteration counter) { // code }
The following are some points to remember when working with for loops in C#:
Defines how many times iterations will be performed.
The for loop is useful in situations where we know in advance how many times the iteration will be performed.
Initialization occurs at the beginning and start of the loop.
After initialization, the control is passed to the second part of the loop to evaluate the Boolean condition.
If the Boolean expression evaluates to true, then the code within the curly braces { } gets executed, and the control then goes back to the top of the loop to perform increment (adding) or decrement (subtracting) to the variable.
Once the variable is incremented or decremented, then the control re-checks the Boolean expression and the loop continues to iterate if it returns true or it will exit out of the loop if it returns false.
Here is another example a simple for loop in C#:
using System; namespace LoopExampleApplication1 { class MyProgram { static void Main(string[] args) { for(int i=0; i<5; i++) { Console.WriteLine("value of i is "+ i); } Console.ReadLine(); } } }
How C# for Loops Work
In the above code, we have initialized an integer named i with a value of 0. Then, we have set-up the Boolean condition to check if i is less than 5 and an increment operator to increase the value of our variable by one each iteration through the loop.
At the very first, initialization is done. This initialization is executed only once before the loop starts. Next, the condition is evaluated; if the condition evaluates to true, then the code inside the curly braces is executed. After that, the control is passed to the increment counter at the top (in the third part) which increments the counter by 1 during each iteration. The last two parts of the loop are executed for each iteration of the loop.
Thus, the above code snippet will produce the following output:
//Output value of i is 0 value of i is 1 value of i is 2 value of i is 3 value of i is 4
How to use the for each Loop in C#
In C#, a for each loop is used when we need to iterate through the content of a collection like a list of arrays:
foreach(item i in list_type) { //code }
Points to remember when working with for each loops in C#:
foreach executes the code block against each element in the collection.
You cannot modify the iteration value during execution. It is a read-only value.
It fetches a new value from the list in each iteration and that value is put into the read-only variable.
Here is another example of how to iterate over an array in C#
using System; namespace LoopExampleApplication1 { class MyProgram { static void Main(string[] args) { int[] list = {1,2,3,4,5,6,7,8}; foreach (int item in list) { Console.WriteLine("Numbers present in list are "+ item); } Console.ReadLine(); } } }
How for each Loops Work in C#
In the above code, we have defined an array list. In the next line, we have used the foreach loop to iterate all the items in the array and print them.
In the loop statement, we have declared an integer named item, followed by the in keyword, which is then followed by the array list. As you can see, we have declared item as an integer, as we are telling foreach that we want to pull-out integer values from the collection.
You are very likely to be using the foreach loop when working with collections because it is simpler than any other loop and is a preferred method for such types of operations.
The the output of the above code is:
Numbers present in list are 1 Numbers present in list are 2 Numbers present in list are 3 Numbers present in list are 4 Numbers present in list are 5 Numbers present in list are 6 Numbers present in list are 7 Numbers present in list are 8
Read: Debugging Tools for C#
Infinite Loops in C#
A loop can iterate an infinite number of times if the Boolean condition defining the loop never returns a false value. You can use a while loop or for loop for such operations, in order to avoid getting stuck in an infinite loop. Below is an example scenario of a for loop working as an infinite loop.
for Loop as an Infinite Loop
The for loop can be used as an infinite loop. As none of three statements in the loop are mandatory, if we leave all those three parts empty then the loop will go an infinite number of times:
for (; ;) { Console.WriteLine("This is an infinite loop”); } Or int x = 1; while(x > 0) { Console.WriteLine("This is an infinite loop”); x++; }
The above code will print “This is an infinite loop” an infinite number of times in the console.
Conclusion of Loops in C# Tutorial
The loops in C# allow you to iterate a block of code multiple times. The language uses different keywords for different iteration requirements like while, do while, for, etc.
Normally, a loop continues to execute code until the condition remains true however you can use control statements such as ‘continue’ or ‘break’ statements to change its execution flow.
It is also possible to create infinite loops. ‘for’ or ‘while’ loops can be used to perform an iteration over a block of code infinite number of times. These code blocks will keep on executing as the condition defined in the loop will always return true.
Read: C# Data Types Explained