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}
As this will be a guide for beginners, I try my best to use vivid visualizations and examples to help you understand.
This guide (Part 1) will focus on the basic concept and introduce an important iterative statement: while
/do while
loop.
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.
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);
There are several problems with this brute force version:
m
to n
? You’ll never know where to start and end.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}
From this example, we can see there are many advantages from an iterative statement:
m
to n
.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
Before this, let me introduce the grammar of while
in C#. This is the code template:
1while (condition)
2{
3 code_block;
4}
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.I will draw a flowchart of a while loop to help you understand flow control better.
The while
loop process is as follows:
condition
.condition
is true , process loop logic in code_block
.condition
is false and then exit loop.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~");
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
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.
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)
Here is the flowchart of do while
loop:
The process of do while
loop is:
code_block
.condition
after code_block
.condition
is true, loop back to step 1, which means continue looping. If condition
is false, exit loop.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~");
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}
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.
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.
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]