Author avatar


A Comprehensive Walkthrough of C# Iterative Statements Part 3 - Advanced Usages


  • Jun 14, 2019
  • 7 Min read
  • Jun 14, 2019
  • 7 Min read
Programming Languages


This is the third part of a three-part series on C# iterative statements. In Part 1 and Part 2, we have learned all the four common iterative statements: while, do while, for, and foreach. Check them out in case you missed them.

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.

`while` vs. `for`

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)
4    code_block;
7// rewritten for by while
8initializer;                // execute initializer before while loop
9while (condition)
11    code_block;
12    update_expression;        // execute update-expression after code_block

while -> for: just ignore initializer and update_expression.

1// while templates
2while (condition)
4    code_block;
7// rewritten while by for
8for (;condition;)        // initializer and update_expression stay empty
10    code_block;

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.

Best Practices for Loop Choice

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:

best practice of loop choice

We can follow the below process to make a decision:

  1. Firstly, ask yourself, “Is it a loop with a collection?”
  2. If the answer is yes, we determine whether to use 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.
  3. If the answer is no, we must further consider, “Does it process logic before checking the condition?” If yes, do while is the best choice.
  4. The final step: If a loop logic needs an 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:

appropriate scope of loop usages

Advanced Usages

Cooperate with Jump Statement

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.

Infinite Loop

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 (;;)
4    Console.WriteLine("I am trapped in loop. Is anybody here?"); 
7// infinite while loop
8while (true)
10    Console.WriteLine("I am trapped in loop again. Please help me!");

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.

Nested 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},
6int sum = 0;
7// iteration for the first dimension
8for (int i = 0; i < bookshelf.GetLength(0); ++i)
10    // iteration for the second dimension
11    for (int j = 0; j < bookshelf.GetLength(1); ++j)
12    {
13        sum += bookshelf[i, j];
14    }
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.

Iterative Statements Loop mind map

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].