Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

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

In this guide, we will compare the four common iterative statements and summarize the best practices for loop choice.

Jun 14, 2019 • 7 Minute Read

Introduction

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.

      // for template
for (initializer; condition; update_expression)
{
    code_block;
}

// rewritten for by while
initializer;                // execute initializer before while loop
while (condition)
{
    code_block;
    update_expression;        // execute update-expression after code_block
}
    

while -> for: just ignore initializer and update_expression.

      // while templates
while (condition)
{
    code_block;
}

// rewritten while by for
for (;condition;)        // initializer and update_expression stay empty
{
    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:

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:

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:

      // infinite for loop
for (;;)
{
    Console.WriteLine("I am trapped in loop. Is anybody here?"); 
}

// infinite while loop
while (true)
{
    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.

      int[,] bookshelf = new int[2, 3] {
    {11, 7, 10},
    {9, 15, 12},
};

int sum = 0;
// iteration for the first dimension
for (int i = 0; i < bookshelf.GetLength(0); ++i)
{
    // iteration for the second dimension
    for (int j = 0; j < bookshelf.GetLength(1); ++j)
    {
        sum += bookshelf[i, j];
    }
}
Console.WriteLine("there are {0} books on this bookshelf", sum);
// 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.

Conclusion

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.

Recnac

Recnac

Written content author.

More about this author