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 1 - while, do

Start with the basic concept of an iterative statement, then learn the first important loop - while loop. Analyze the syntax and flowchart of while/do while.

Jun 14, 2019 • 10 Minute Read

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:

      while (alive)
{
    eat();
    //sleep();
    code();
}
    

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:

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

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):

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

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:

      while (condition)
{
    code_block;
}
    

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.

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:

      Console.WriteLine("welcome to chat with me");
string command;
// read command from input, and continue looping while command != "end conversation"
while ((command = Console.ReadLine()) != "end conversation")
{
    Console.WriteLine("sorry, I don't understand the meaning of {0}", command);
}

Console.WriteLine("glad to chat with you, bye~");
    

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

      welcome to chat with me
>> hi
sorry, I don't understand the meaning of hi
>> what do you know?
sorry, I don't understand the meaning of what do you know?
>> end conversation
glad 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.

      do {
    code_block;
} while (condition)
    

Flowchart

Here is the flowchart of do while loop:

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.

      Console.WriteLine("welcome to chat with me");
string command;
do
{
    command = Console.ReadLine();   // read the command from input
    Console.WriteLine("sorry, I don't understand the meaning of {0}", command);   
} while (command != "end conversation");  // continue looping until "end conversation"

Console.WriteLine("hah, I'm kidding with that, and glad to chat with you, bye~");
    

Let's try again:

      welcome to chat with me
>> tell me a joke
sorry, I don't understand the meaning of tell me a joke
>> bye
sorry, I don't understand the meaning of bye
>> end conversation
sorry, I don't understand the meaning of end conversation
hah, 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:

      // do while template
do
{
    do_something();
} while (condition);

// rewritten do-while by while
do_something();
while (condition)
{
    do_something();
}
    

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.