In this guide, we will compare them and summarize the best practice for loop choice. Furthermore, we will learn the advanced usages.
As this will be a guide for beginners, I try my best to use vivid visualizations and examples to help you understand.
To figure out the characteristics and application scenarios, let's compare while
loop and for
loop.
Think about how to convert for
and while
to each other.
for -> while: put initializer
before while
loop, and put update_expression
after code_block
.
1// for template
2for (initializer; condition; update_expression)
3{
4 code_block;
5}
6
7// rewritten for by while
8initializer; // execute initializer before while loop
9while (condition)
10{
11 code_block;
12 update_expression; // execute update-expression after code_block
13}
while -> for: just ignore initializer
and update_expression
.
1// while templates
2while (condition)
3{
4 code_block;
5}
6
7// rewritten while by for
8for (;condition;) // initializer and update_expression stay empty
9{
10 code_block;
11}
From the above convention strategies, we can conclude that for
is a particular case of while
, that is more usable and readable in situations when we need to initialize and update loop variables.
Now that we have learned all four of these iterative statements and the comparisons between them.
We are going to summarize the best practices to choose which one is best in a particular scenario:
We can follow the below process to make a decision:
for
or foreach
. If it accesses an element in forward order, and there is no need to modify the collection or operate index, we can choose foreach
. Otherwise, choose for
.condition
?” If yes, do while
is the best choice.initializer
or update_expression
code section, we use for
. Choose while
in the rest of the situations.Here is a Venn Diagram to show you the appropriate scope of loop usages intuitively:
For some more complex situations in real-life scenarios, when executed in a loop, some logic may trigger to change the control flow. We need to cooperate with jump statements to achieve that.
For example, use continue
to skip the rest statements and continue to the next iteration, or use break
to break out of the loop, or exit the loop by goto
, return
, or throw
statements.
I will discuss jump statements in another guide: A Comprehensive Walkthrough of C# Jump Statements Part 1 - break, continue.
Since all sections in a loop can be optional, when condition
is empty or true
, it will cause an infinite loop. It will execute loop logic forever until you unplug your computer:
1// infinite for loop
2for (;;)
3{
4 Console.WriteLine("I am trapped in loop. Is anybody here?");
5}
6
7// infinite while loop
8while (true)
9{
10 Console.WriteLine("I am trapped in loop again. Please help me!");
11}
An infinite loop should be avoided in most cases. But don't worry, a jump statement, as just mentioned, is a perfect assistant for an infinite loop.
I have mentioned that code_block
is able to contain another loop block. This is called a nested loop.
So, how to implement a nested loop?
Speaking plainly, we can replace the whole, or some part, of code_block
with another loop.
Let's practice with a simple scenario for a nested loop:
Now we develop the last robot: steward robot. It helps us manage our stuffs.
Here is a
bookshelf
with 2 x 3 cells, We want to ask it how many books are on this bookshelf.
1int[,] bookshelf = new int[2, 3] {
2 {11, 7, 10},
3 {9, 15, 12},
4};
5
6int sum = 0;
7// iteration for the first dimension
8for (int i = 0; i < bookshelf.GetLength(0); ++i)
9{
10 // iteration for the second dimension
11 for (int j = 0; j < bookshelf.GetLength(1); ++j)
12 {
13 sum += bookshelf[i, j];
14 }
15}
16Console.WriteLine("there are {0} books on this bookshelf", sum);
17// output: there are 64 books on this bookshelf
Create a nested loop to index a two-dimensional array. The outer loop is the iteration for the first dimension and the inner loop is for the second dimension.
In this guide, we compared iterative statements (while
, do while
, for
, foreach
) and summarized the best practices for loop choice. In addition, we explored the advanced usages, including jump statement, infinite loop, and nested loop.
As this is the end, I have drawn a mind map to help you organize and review the knowledge in this series.
This guide is one of a series of C# Flow Control guides:
Hope you enjoyed it. If you have any questions, you’re welcome to contact me at [email protected].