Author avatar

Recnac

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

Recnac

  • Jun 14, 2019
  • 7 Min read
  • 112 Views
  • Jun 14, 2019
  • 7 Min read
  • 112 Views
Programming Languages
C#

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
// 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
}
csharp

while -> for: just ignore initializer and update_expression.

1
2
3
4
5
6
7
8
9
10
11
// while templates
while (condition)
{
    code_block;
}

// rewritten while by for
for (;condition;)        // initializer and update_expression stay empty
{
    code_block;
}
csharp

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
2
3
4
5
6
7
8
9
10
11
// 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!");
}
csharp

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
csharp

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.

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]

0