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 to combine these statements makes the 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#: Jump Statements.
Jump Statement plays an important role in complex logic. It can even tell the famous fable The Crow and the Pitcher:
A thirsty crow wanted to drink the water in a pitcher, but it could not reach the water. So It had to pick up pebbles and dropped them into pitcher again and again until the water was near enough.
As a tutorial 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 two important jump statements: break
and continue
statement.
Some readers might be curious. What is a jump statement? And why do we need it?
Let's come back to the fable "the crow and the pitcher".
Define a pile of pebbles
as int
array, and we assume the empty space left in the pitcher is pitcherVacancy
. The crow has to pick up pebbles
to fill the pitcherVacancy
repetitively. So loop is appropriate here. But we should break out the loop once the pitcher is full. Jump Statement is born for such situations.
We take a look at the implementation first:
1Console.WriteLine("pick up pebbles to fill the vacancy in pitcher");
2int pitcherVacancy = 28;
3int[] pebbles = {8, 6, 7, 9, 8, 5, 10};
4foreach (int pebble in pebbles) // use foreach to pick up all the pebbles
5{
6 pitcherVacancy -= pebble;
7 Console.WriteLine("pick up a pebble size of {0}, get {1} vacancy left", pebble, pitcherVacancy);
8 if (pitcherVacancy <= 0) // break out once pitcher is full
9 {
10 break;
11 }
12 Console.WriteLine("still can not reach the water, I have to pick up more pebbles");
13}
14Console.WriteLine("finally, I can drink the water!");
Let's run the fable program:
1pick up pebbles to fill the vacancy in the pitcher
2pick up a pebble size of 8, get 20 vacancies left
3still can not reach the water, I have to pick up more pebbles
4pick up a pebble size of 6, get 14 vacancies left
5still can not reach the water, I have to pick up more pebbles
6pick up a pebble size of 7, get 7 vacancies left
7still can not reach the water, I have to pick up more pebbles
8pick up a pebble size of 9, get -2 vacancies left
9finally, I can drink the water!
From the above example, we can see if we want to change the process in a loop, such as break
loop in some condition, or skip the rest loop logic and continue
to the next iteration, or even goto
everywhere you want.
This is the role of jump statements in control flow. We will learn these three basic jump statements in the following sections.
Since we have learned an example of the break
statement in the previous section, it's time to learn the syntax of break
in C#. Here is the code template:
1loop (loop_condition) // represents all kinds of loop
2{
3 code_block_before_break;
4 if (break_condition)
5 {
6 break;
7 }
8 code_block_after_break;
9}
Analyze each segment in the break
statement:
loop
represents all kinds of iterative statements, including do-while
although the syntax is a little different.break_condition
is a boolean expression and decides the condition to break the loop.code_block_before_break
is the logic before break
. code_block_after_break
is the logic after break
, and it is skipped when break
triggers.I draw a flowchart of break
statement to help you understand flow control better.
The red line represents loop flow, and the blue line represents break
jump flow. Or you can simply focus on the arrow direction in code template.
From the flowchart, we can see break
builds on the standard loop. The key point is when break_condition
triggered, skip the rest loop.
Imagine this scenario:
Design a lottery generator. It generates six number from 1 to 9, and no duplicate number is allowed.
The continue
statement can solve this problem.
By convention, we learn the syntax of the continue
statement first.
1loop (loop_condition)
2{
3 code_block_before_continue;
4 if (continue_condition)
5 {
6 continue;
7 }
8 code_block_after_continue;
9}
The code segments in continue
are similar to break
, refer to the previous section if you need.
Please take a look at the continue
flowchart. It shows flow control intuitively.
The red line represents loop flow, and the blue line represents continue
jump flow. Or you can simply focus on the arrow direction in code template.
Similar to break
, we can see continue
also builds on the standard loop. The only difference is when continue_condition
triggered, skip the rest loop logic in the current iteration.
Since we have learned the mechanism of continue
, it is time to solve the lottery problem. The idea is generating numbers in the loop until we get enough numbers. If a number is a duplicate, we abandon it and continue the loop.
1Random random = new Random();
2List<int> lottery = new List<int>();
3while (lottery.Count < 6)
4{
5 int num = random.Next(1, 10);
6 if (lottery.Contains(num))
7 {
8 Console.WriteLine("{0} already exists, generate again", num);
9 continue; //if num is duplicate, abandon and generate again
10 }
11 lottery.Add(num);
12 Console.WriteLine("generate number: {0}", num);
13}
14
15Console.WriteLine("the result of lottery is: {0}", string.Join(", ", lottery));
Here is a generation result:
1generate number: 1
2generate number: 9
39 already exists, generate again
4generate number: 2
5generate number: 8
6generate number: 4
72 already exists, generate again
8generate number: 7
9the result of the lottery is: 1, 9, 2, 8, 4, 7
Notice this solution is not the most effective algorithm, but a good example of continue
.
break
and continue
are based on loop, and change the flow of loop in some cases.
break
skips the rest of the loop. By contrast, continue
skips the rest of logic in the current iteration.
Both of them can only operate on the current loop but do not affect on outer loops.
Here is the jump route in multiple nested loops:
In this guide, we have learned an important flow control in C#: jump statements. It helps to change the execution flow in some condition. We started with the basic concept of jump statement. Then we learned two important conditional statements: break
and continue
statements. We analyzed the syntax and flowchart of them and practiced with examples. Furthermore, we talked about how break
and continue
work in nested loops.
In the next guide, we'll explore 'goto' statements.
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].