Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Recnac

A Comprehensive Walkthrough of C# Iterative Statements Part 1 - while, do

Recnac

  • Jun 14, 2019
  • 10 Min read
  • 1,851 Views
  • Jun 14, 2019
  • 10 Min read
  • 1,851 Views
Programming Languages
C#

Introduction

When you start to learn a programming language such as C#, one of the most important concepts is Flow Control. We know a program is composed of statements. The way that we combine these statements makes a program more powerful. And this is the responsibility of flow control: control the flow of program execution.

Sequential execution one by one is not enough for many situations, so flow control provides many useful statements such as conditional statements, iterative statements, jump statements, and other advanced features. In this guide, we will focus on an important flow control in C#: Iterative Statements. Or, to use a more familiar term: Loop.

Loop is a very powerful statement. It can even describe the life of a perfect programmer in a few words:

1while (alive)
2{
3    eat();
4    //sleep();
5    code();
6}
csharp

As this will be a guide for beginners, I try my best to use vivid visualizations and examples to help you understand.

  1. First, I will start with an interesting scenario.
  2. Then I will show you the code templates and flowcharts of all kinds of iterative statements.
  3. In addition, we compare them and summarize the best practice.
  4. Finally, we will talk about advanced usages.

This guide (Part 1) will focus on the basic concept and introduce an important iterative statement: while/do while loop.

Getting Started

Scenario

Some readers might be curious. What is an iterative statement? And why do we need it?

Imagine this scenario:

Develop an early education robot to teach a baby how to count.

Let's start from counting sheep from 1 to 4.

Sequential Version

If using sequential statements, we can achieve the goal in a straightforward way:

1// count from 1 to 4
2Console.WriteLine("{0} little sheep", 1);
3Console.WriteLine("{0} little sheep", 2);
4Console.WriteLine("{0} little sheep", 3);
5Console.WriteLine("{0} little sheep", 4);
csharp

There are several problems with this brute force version:

  • How about counting fish instead? You have to change every single line. Be careful when you refactor your code, it may bring inconsistent bugs.
  • How about counting from 1 to 100 when the baby grows up? It is definitely a huge project!
  • How about counting from m to n? You’ll never know where to start and end.

Loop Version

So, when you want to do something repetitively, loop (iterative statement) can help you. Here is the loop version (If you are not familiar with the grammar of for, don't worry, I will explain it in the following section):

1int m = 1, n = 4;        // start from m, end to n, both are included
2// use for loop to print repetitively
3for (int i = m; i <= n; ++i)
4{
5    Console.WriteLine("{0} little sheep", i);
6}
csharp

From this example, we can see there are many advantages from an iterative statement:

  • Extract duplicate logics and reuse code. It makes the program easier to refactor and reduce the possibility of bugs.
  • Make code concise and enhance readability.
  • More flexible to embrace change.
  • Solve more complicated problems which sequential execution can't, such as loop from m to n.

`while` Loop

Scenario

Imagine this scenario:

Develop a silly chat robot. Currently, it has only learned one command: "end conversation".

while and do while loops are suitable in this situation.

while

Syntax

Before this, let me introduce the grammar of while in C#. This is the code template:

1while (condition)
2{
3    code_block;
4}
csharp

The while statement is composed of a condition and a code_block:

  • code_block represents the logic executed in the loop. It can include multiple statements, even another loop block.
  • condition is a boolean expression. It decides whether should continue looping or exit loop.

Flowchart

I will draw a flowchart of a while loop to help you understand flow control better.

iterative statements while flowchart

The while loop process is as follows:

  1. Check whether it satisfies the condition.
  2. If condition is true , process loop logic in code_block.
  3. Repeat the above process until the condition is false and then exit loop.

Practice

Now we are ready to implement this silly chat robot by while:

1Console.WriteLine("welcome to chat with me");
2string command;
3// read command from input, and continue looping while command != "end conversation"
4while ((command = Console.ReadLine()) != "end conversation")
5{
6    Console.WriteLine("sorry, I don't understand the meaning of {0}", command);
7}
8
9Console.WriteLine("glad to chat with you, bye~");
csharp

Let's have a try. Chat robot will stay in the conversation loop until we input “end conversation”.

1welcome to chat with me
2>> hi
3sorry, I don't understand the meaning of hi
4>> what do you know?
5sorry, I don't understand the meaning of what do you know?
6>> end conversation
7glad to chat with you, bye~

do while

Scenario

Let's modify the above scenario a little bit:

Even if the user says "end conversation", chat robot will also pretend it doesn't understand.

For this situation, do while is a better choice.

Syntax

Also, the code template of do while is given. code_block and condition are the same as while loop, refer to the previous section if you need to refresh.

1do {
2    code_block;
3} while (condition)
csharp

Flowchart

Here is the flowchart of do while loop:

iterative statements do while flowchart

The process of do while loop is:

  1. Process loop logic in code_block.
  2. Evaluate condition after code_block.
  3. If condition is true, loop back to step 1, which means continue looping. If condition is false, exit loop.

Practice

In the new scenario, if we tend to execute exit before quit, do while reuses code maximally.

1Console.WriteLine("welcome to chat with me");
2string command;
3do
4{
5    command = Console.ReadLine();   // read the command from input
6    Console.WriteLine("sorry, I don't understand the meaning of {0}", command);   
7} while (command != "end conversation");  // continue looping until "end conversation"
8
9Console.WriteLine("hah, I'm kidding with that, and glad to chat with you, bye~");
csharp

Let's try again:

1welcome to chat with me
2>> tell me a joke
3sorry, I don't understand the meaning of tell me a joke
4>> bye
5sorry, I don't understand the meaning of bye
6>> end conversation
7sorry, I don't understand the meaning of end conversation
8hah, I'm kidding with that, and glad to chat with you, bye~

do while works fine to complete what we want: process loop logic before the condition check.

while vs. do while

From the code template and flowchart, we can find out that the only difference is that do while processes loop logic first, then evaluates the condition. So you can consider do while as the extension of while. Actually, do while can be rewritten by while, with a little redundancy:

1// do while template
2do
3{
4    do_something();
5} while (condition);
6
7// rewritten do-while by while
8do_something();
9while (condition)
10{
11    do_something();
12}
csharp

But the while version called do_something twice, it violates the rule don't repeat yourself.

So, for the situation loop logic before the condition check, do while is the best practice.

Conclusion

In this guide, we have learned about an important flow control in C#: iterative statement (loop). It helps to process logic repeatedly. We started with the basic concept of an iterative statement. Then we learned the first important loop - while loop. We analyzed the syntax and flowchart of while/do while and practiced them with examples.

In the second part, we will cover another important loop: for/foreach loop.

In the third part, we will compare them and summarize the best practices. In addition, we will explore advanced usages.

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