Author avatar

Recnac

A Comprehensive Walkthrough of C# Jump Statements Part 1 - break, continue

Recnac

  • Jun 14, 2019
  • 9 Min read
  • 44 Views
  • Jun 14, 2019
  • 9 Min read
  • 44 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 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.

  1. First, I will start with an interesting scenario.
  2. Then I will show you the code templates and flowcharts of all kinds of jump 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 two important jump statements: break and continue statement.

Getting Started

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Console.WriteLine("pick up pebbles to fill the vacancy in pitcher");
int pitcherVacancy = 28;
int[] pebbles = {8, 6, 7, 9, 8, 5, 10};
foreach (int pebble in pebbles)  // use foreach to pick up all the pebbles 
{
    pitcherVacancy -= pebble;
    Console.WriteLine("pick up a pebble size of {0}, get {1} vacancy left", pebble, pitcherVacancy);
    if (pitcherVacancy <= 0)	// break out once pitcher is full
    {
        break;
    }
    Console.WriteLine("still can not reach the water, I have to pick up more pebbles");
}
Console.WriteLine("finally, I can drink the water!");
csharp

Let's run the fable program:

1
2
3
4
5
6
7
8
9
pick up pebbles to fill the vacancy in the pitcher
pick up a pebble size of 8, get 20 vacancies left
still can not reach the water, I have to pick up more pebbles
pick up a pebble size of 6, get 14 vacancies left
still can not reach the water, I have to pick up more pebbles
pick up a pebble size of 7, get 7 vacancies left
still can not reach the water, I have to pick up more pebbles
pick up a pebble size of 9, get -2 vacancies left
finally, 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.

`break` Statement

Syntax

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:

1
2
3
4
5
6
7
8
9
loop (loop_condition)	// represents all kinds of loop
{
    code_block_before_break;
    if (break_condition)
    {
         break;
    }
    code_block_after_break;
}
csharp

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.

Flowchart

I draw a flowchart of break statement to help you understand flow control better.

jump statements break flowchart

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.

`continue` statement

Scenario

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.

Syntax

By convention, we learn the syntax of the continue statement first.

1
2
3
4
5
6
7
8
9
loop (loop_condition)
{
    code_block_before_continue;
    if (continue_condition)
    {
         continue;
    }
    code_block_after_continue;
}
csharp

The code segments in continue are similar to break, refer to the previous section if you need.

Flowchart

Please take a look at the continue flowchart. It shows flow control intuitively.

jump statements continue flowchart

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.

Practice

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Random random = new Random();
List<int> lottery = new List<int>();
while (lottery.Count < 6)
{
    int num = random.Next(1, 10);
    if (lottery.Contains(num))
    {
        Console.WriteLine("{0} already exists, generate again", num);
        continue;	//if num is duplicate, abandon and generate again
    }
    lottery.Add(num);
    Console.WriteLine("generate number: {0}", num);
}

Console.WriteLine("the result of lottery is: {0}", string.Join(", ", lottery));
csharp

Here is a generation result:

1
2
3
4
5
6
7
8
9
generate number: 1
generate number: 9
9 already exists, generate again
generate number: 2
generate number: 8
generate number: 4
2 already exists, generate again
generate number: 7
the 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.

Used in Nested Loops

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:

jump statements break continue in nested loop flowchart

Conclusion

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.

jump statements 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