Jump Statements in C# (Break, Continue, Goto, Return and Throw)

Jump statements allow you to control the flow of your program. They are also known as control transfer statements. There are several types of jump statements in C#, including break, continue, goto, return, and throw.
In this post, we will try to learn different types of jump statements available in C# with multiple examples. Additionally, we will discuss how and where to use them.

jump-statements-in-c-sharp
jump statements in C#

What are Jump Statements in C#?

Jump statements are used to alter the normal flow of a program. They are also known as control transfer statements. There are several types of jump statements in C#, including:

  • break
  • continue
  • goto
  • return
  • throw

The break Statement

The break statement is used to exit a loop (such as, for, foreach, while, or do loop) or switch statement. It immediately transfers the control to the statement following the loop or switch. For example, the following code uses a while loop and the break statement to print the first 5 even numbers:

Example:

using System;
public class BreakExample
{
    public static void Main(string[] args)
    {
        // Print 5 even numbers
        int i = 0;
        while (true)
        {
            if (i == 10)
            {
                break;
            }
            if (i % 2 == 0)
            {
                Console.Write(String.Concat(i,","));
            }
            i++;
        }
        // Output: 0, 2, 4,  6,  8
        Console.ReadLine();
    }
}

Example 2:

using System;
class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        foreach (int number in numbers)
        {
            if (number == 5)
            {
                break;
            }

            Console.Write($"{number} ");
        }
        Console.WriteLine();
        Console.WriteLine("End of the example.");
        // Output:
        // 0 1 2 3 4
        // End of the example.
        Console.ReadLine();
    }
}

Flowchart: break statement

jump statements break flowchart

The continue Statement

The continue statement is used to skip the current iteration of a loop and continue with the next iteration. For example, the following code uses a for loop and the continue statement to print only the odd numbers between 1 and 10:

Example:

using System;
public class ContinueExample
{
    public static void Main(string[] args)
    {
        // Print only the odd numbers between 1 and 10
        for (int i = 1; i <= 10; i++)
        {
            if (i % 2 == 0)
            {
                continue;
            }
            Console.Write(String.Concat(i,","));
        }
        // Output: 1, 3, 5, 7, 9
        Console.ReadLine();
    }
}

Flowchart: continue statement

jump statements continue flowchart

The goto Statement

The goto statement is used to transfer control to a labeled statement. The label must be followed by a colon and must be placed on a separate line. For example, the following code uses the goto statement to transfer control to the labeled statement start when the variable i is less than 5:

Example:

using System;
public class gotoExample
{
    public static void Main(string[] args)
    {
        // Initialize variable i as 0
        int i = 0;  
        start:      // Label the start of a loop
        if (i < 5)  // Check if the value of i is less than 5
        {
            // If true, print the value of i
            Console.Write(String.Concat(i,","));  
            i++;  // Increment the value of i by 1
            goto start;  // Transfer control to the start of the loop
        }
        // Output: 0, 1, 2, 3, 4
        Console.ReadLine();
    }
}

Example: switch case with a goto statement

using System;
class Program
{
    static void Main(string[] args)
    {
        int input = 2;

        switch (input)
        {
            case 1:
                Console.WriteLine("Input is 1");
                goto case 2; // goto statement transfers control to the next case label (case 2)
            case 2:
                Console.WriteLine("Input is 2");
                break;
            case 3:
                Console.WriteLine("Input is 3");
                break;
            default:
                Console.WriteLine("Input is not 1, 2 or 3");
                break;
        }

        Console.ReadLine();
    }
}

In the above code example, the goto case 2; statement is used to transfer control to the next case label, which is case 2. This means that if the input variable is equal to 1, the program will execute the code for both case 1 and case 2. The break statement is used to exit the switch statement after the code for the current case has been executed.

The return Statement

The return statement is used to exit a method and return a value. For example, the following code defines a method AddNumbers that takes two integers as parameters and returns their sum:

Example:

using System;
public class returnExample
{
    public static void Main(string[] args)
    {
        int result = AddNumbers(5, 15);
        Console.WriteLine(result); // Output: 20
        Console.ReadLine();
    }
    static int AddNumbers(int a, int b)
    {
        // Check if the input is valid
        if (a < 0 || b < 0)
        {
            // If the input is invalid, return -1
            return -1;
        }

        // If the input is valid, return the sum of the numbers
        return a + b;
    }
}

The throw Statement

The throw statement is used to throw an exception. For example, the following code throws an exception when the value of the variable num is less than 0:

using System;
class Program
{
    static void Main(string[] args)
    {
        try
        {
            // Input a number
            int num = int.Parse(Console.ReadLine());

            // Check if the number is less than 0
            if (num < 0)
            {
                // Throw an exception if the number is less than 0
                throw new Exception("Number cannot be negative");
            }
            else
            {
                // Print the number if it is greater than or equal to 0
                Console.WriteLine($"The number is: {num}");
            }
        }
        catch (Exception ex)
        {
            // Catch the exception and print the error message
            Console.WriteLine(ex.Message);
        }
        Console.ReadLine();
    }
}

Conclusion

Jump statements in C# are an important feature that allows you to control the flow of your program. You can write more efficient and effective code by understanding the different types of jump statements such as break, continue, goto, return, and throw.

FAQ

Q: What are jump statements in C#?

Jump statements are used to alter or control the normal flow of a program. They are also known as control transfer statements. There are several types of jump statements in C#, such as break, continue, goto, return, and throw.

Q: When should you use the break statement?

The break statement can be used to exit a loop or switch statement. It immediately transfers the control to the statement following the loop or switch. For example, you can use the break statement to exit a loop when a certain condition is met.

Q: When should you use the continue statement in C#?

The continue statement is used to skip the current iteration of a loop and continue with the next iteration. For example, you can use the continue statement to skip over certain values in an array or list.

Q: When should you use the goto statement?

The goto statement is used to transfer control to a labeled statement. It is typically used to transfer control to a specific point within a loop. However, it is generally considered to be a less readable and less maintainable control flow created than other alternatives such as if-else and switch-case.

Q: Is it possible to use jump statements inside a try-catch block?

Yes, it is possible to use jump statements inside a try-catch block. The throw statement can be used inside the try block to throw an exception, and the goto statement can be used inside a catch block to transfer control to a specific point.

Q: Can you use jump statements in a nested loop?

Yes, you can use jump statements in a nested loop. When a break statement is encountered inside a nested loop, it will only exit the innermost loop. Similarly, when a continue statement is encountered inside a nested loop, it will only affect the innermost loop.

References: MSDN-jump statements

Articles you might also like:

Your support is greatly appreciated! Please share this post and leave a comment below.

Shekh Ali
5 3 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments