Loops in C# Allow the Program to Run a Block of Code Multiple Times. This Tutorial Explains Various Loops Such as While Loops, For Loops, etc with Examples:
In our previous tutorial, we learned about different C# Operators than can be used in conjunction with the decision making statements to follow a required execution flow.
In this tutorial, we will be discussing the C# Loop statements that allow the program to execute iterative logic.
=> Check For Our Ultimate C# Training Guide Here
Table of Contents:
Loops In C#: A Complete Overview
All the statements written in the C# are executed sequentially, but there can be a scenario where the program needs to execute a certain code snippet several times, to handle this kind of situation, C# offers control statements that can be used to handle complicated execution flows.
A loop allows the program to run a block of code multiple times by following a general statement in C#. C# offers different types of loops to handle different programming execution requirements.
Control Statement
Before we start working on loops we need to know what a control statement is. A control statement allows the loop to change its course from its normal sequence. The C# programming language offers the following basic loop control statements.
Continue Statement
Continue statement in C# is used for the following reasons:
- To execute the next iteration of the loop while skipping any code in between.
The syntax of the continue statement is “continue;”
Break Statement
Break statement in C# is used for the following reasons:
- It is used to terminate a loop so that the program can continue with the next loop statement. In nested loops it can be used to stop the execution of the inner loop, thereby providing the program control to the next statement after the current code.
- It can be used to terminate a statement in the Switch Case.
The syntax of the break statement is “break;”
While Loop
The while loop validates a condition and then executes the code block as long as the condition defined in the while stands true.
Syntax
While(Boolean Condition) { //code block// }
Important Pointers:
- The boolean statement is validated before the execution of the code.
- If Boolean expression validates as true, only then the code is executed.
- Once the code block has been executed, the control will return to a Boolean statement for evaluation.
- The loop will keep on executing as long as the Boolean expression evaluates true.
- If the Boolean expression evaluates to false, then the code block is skipped and the next line of the code outside the while loop is executed.
- Always make sure to update the variable used with a Boolean expression, so that it recognizes the end of the loop at the expected iteration.
- If the variable associated with the while loop is not updated or always returns a true value, then it will become an infinite loop.
Example Of A Simple While Loop:
int a = 0; while (a < 5) { Console.WriteLine(“The value of a is :”+a); a++; } Console.WriteLine(“The while block has been executed”);
Code Explanation
In the above program, we have provided the Boolean expression as (a<5) for “while”. It means that the loop will continue to execute the code snippet as long as the value of “a” is less than 5.
In the code block, we are printing the value of “a” and then we have added the increment operator. As we discussed earlier in our previous tutorial increment operator is used to increase the value of the integer by 1. Hence, once the value of “a” is printed to console, the control will pass through the increment operator, which will increase its size by 1.
Now, the control will move to evaluate the Boolean expression. For the current example as we have already defined the initial value of a as “0”, it will get incremented by “1”. So, the Boolean expression will become (1<5) which will evaluate to “true” and the code block inside the loop will get executed.
Once the value of “a” reaches 5, the execution will stop as the Boolean expression will now read as false. Once the Boolean expression returns false, the control will exist loop and will execute the next line of code outside the while block.
If the program is executed the output will be as shown below:
Output
The value of a is: 0
The value of a is: 1
The value of a is: 2
The value of a is: 3
The value of a is: 4
The while block has been executed
Do While Loop
Do while loop is similar to while loop with one difference, the condition is evaluated at the end of the loop instead of beginning as we discussed it in the case of a while loop. This gives a unique feature to this loop i.e. it will execute the statement inside the loop boundary at least once.
While on the other hand, other loops evaluate the Boolean expression at the beginning which means if the expression is false loop will not execute.
Syntax
do { //code block for execution// } while( Boolean expression );
Important Pointers:
- “Do while” works similar to a while loop. Do keyword is placed at the beginning of the code block and the while is placed after the code block.
- The Boolean expression is evaluated at the end of the loop instead of the beginning. If the condition returns as true then the loop continues. If the expression returns false, then the loop ends there itself.
- “Do while” executes the code block inside the loop boundaries for at least once.
Example Of A Simple Do-While Loop:
int nmbr = 5; /* do loop starts*/ do { Console.WriteLine("value of nmbr is "+ nmbr); nmbr++; } while (nmbr &amp;lt; 10); Console.ReadLine();
Code Explanation
In the above code, we have declared an integer, “nmbr” with value 5. Then we have started the loop by placing the “Do” keyword. After the Do and inside the curly braces we have defined the code that we want to execute. Here, we are just printing the value of the nmbr integer to console. You can write your own complex code inside the brackets.
As we can see, after we have printed the value of nmbr, we are incrementing it. Once the code block is processed, the control moves to “while”, where the Boolean expression is evaluated. Here, till the nmbr have a value less than 10, it will keep on iterating the loop.
So, if we execute this code snippet, then the following output can be observed:
Output
value of nmbr is 5
value of nmbr is 6
value of nmbr is 7
value of nmbr is 8
value of nmbr is 9
Once, the value of the nmbr has reached 10 (by incrementing with each iteration). Then the while condition will return a false value as it is no longer less than 10. This will cause the control to exit the “Do while” loop and control will pass to the next line of code.
For Loop
For loop in C# follows a syntax quite different than the “while” loop. The condition of the “for” loop contains initialization and modification of condition inside the syntax itself. The “for” loop is quite useful if you know the exact number of iterations that you need to perform for the loop.
The definition inside the parenthesis of the loop contains three parts separated from each other by semicolons. The first part is the initialization, then we have a Boolean expression followed by the iteration list.
Syntax
for(initializer; boolean expression; iteration list) { //code block for execution// }
The first part of the expression is the initialization block. This expression is used to initialize the integer variable. This will provide the value at the beginning of the loop.
The second part is the Boolean expression that is used to evaluate the true or false condition for the continuation of the loop just like while loop.
The third expression is the iteration part. Here we can use the increment operators or decrement operators to increase or decrease the value of the initialized variable as per the execution requirements.
Important Pointers:
- For loops in C# allow the programmers to define the exact number of iterations to be performed.
- For loop also contains initialization and iteration expressions along with the Boolean expression to provide a condition for the loop.
- For loop is used when we clearly know the number of iteration required by the loop.
- The initialization of the variable occurs at the start of the loop.
- After initialization, the control is passed to the second section for validating the Boolean expression. The Boolean expression can be as complex as you want but the result should always return true or false as a value.
- After the Boolean expression evaluates as true, the code block within the curly braces is executed and the control again moves to the top of the loop and the increment or decrement operator is executed.
- After the iteration list is executed the control again moves to the Boolean expression for evaluation and the loop iterates if it returns “true” or the next code line outside the loop is executed if it returns false.
Example Of A Simple For Loop:
/* for loop starts*/ for(int i=0; i&amp;lt;5; i++) { Console.WriteLine("value of i is "+ i); }
Code Explanation
In the above code, we initialized integer i as 0. Then we provided the Boolean expression to evaluate if i is less than 0 and an increment operator.
Initialization happens at the start of the loop, then the Boolean condition is evaluated followed by the execution of code block inside curly braces. The control is then again passed to the increment operator at the top, which increases the value of i by 1 during each iteration.
Let’s have a look at the output for more clarity.
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
For Each Loop
A For Each loop is used when a program needs to iterate through the contents of a list. It can be used for collections like array lists or arrays.
Syntax
foreach(item_type iterative_variable in list_type) { //code block for execution// }
The “item_type” in the syntax is the type of the item contained in the list. For example, if we are using an integer array then the type will be integer or int.
The “iterative_variable” is a variable name chosen by you and the “in” is a keyword that is used.
The “list_type” is the list type that you are using. For Example, if we are using integer array then the list_type will be int array name.
Important Pointers:
- For each loop executes the code block against each element present in the specified collection.
- For each loop is read-only, hence it doesn’t allow you to modify the iteration variable during execution.
- For each iteration using this loop fetches a new value from the list. The value is then put inside the read-only variable.
- Once all the elements of the list have been exhausted during iteration, the control will pass to the next line of code.
Example Of A Simple For Each Loop:
/* specifies list*/ int[] list = {1,2,3,4,5}; /* foreach loop starts*/ foreach (int nmbr in list) { Console.WriteLine("Numbers present in list are "+ nmbr); }
Code Explanation
At first, we have defined an array “list” in the first line. Then we have used a for each loop to iterate and print all the values of the array.
Inside the loop statement, we have declared an integer type variable “nmbr” followed by the keyword “in” that is then followed by the same of the array. So, here what we mean to say is that we are looking for an integer “nmbr” inside “list”.
Next, the statement is a simple code block to print all the values. We are printing variable “nmbr”, and as discussed earlier it is a read-only variable and stores a new value with each iteration.
Let’s have a look at the output for better understanding.
Output
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
Infinite Loop
A loop can continue for an infinite time if the condition defining the loop never returns a false value. Usually for loop or while loop can be used to perform an infinite loop operation.
Infinite Loop Using For Loop
We can use “for loop” for performing an infinite loop operation as none of the three statement are mandatory. Hence if we leave all the statements empty, then it will create an infinite loop.
/* for loop starts*/ for (; 😉 { Console.WriteLine("infinite loop”); }
This loop will keep on printing an “infinite loop” in the console for an infinite time.
Infinite Loop Using While Loop
While loop can also be used to perform infinite loop operation. We can do that by providing a condition that can never be false.
For example x>0 and incrementing x each time starting from 1.
/* while loop starts*/ int x = 1; while(x&amp;gt;0) { Console.WriteLine("infinite loop”); x++; }
This will keep on printing “infinite loop” to the console as the value of x will always remain greater than 1. Hence the while condition will always return “true” value, and the code block inside while will keep on executing.
Conclusion
The loop allows you to iterate a block of code again and again. C# programming language offers different statements for using a loop like “for”, “while”, “do while” and “for each”.
While loop executes a block of code as long as the expression inside the while block is true. Do While loop allows the user to execute a block of code at least once and then it will keep on iterating till the expression inside while returns false.
For loop is used when we already know the number of times we need to iterate the code. For each loop is used to execute each element inside a list/collection using a given block of code.
Normally, a loop executes until the control expression returns true but continue or break statement can be used to change its execution flow.
It is also possible to create infinite loops using for or while statements to execute a block of code infinite number of times. These code blocks will keep on executing as the expression defining the loop statement will always return true.
=> Look For The Easy C# Training Guide Here