Lesson 6.3

break and continue in c# - with programming example


Objective

What is Break keyword in c#?
What is Continue keyword in c#?
How to use break and continue in program?

What is break and continue in c#?

As a c# programmer, you have seen these two keywords in various programs. In this lesson you will know what exactly break and continue does.

Break and continue both does same work only difference is break completely terminate the loop whereas continue skips the current iteration only.
I know it is difficult for you to understand it with theory but it can be easily understand with the help of programming example.

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace break_and_continue
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                if (i == 8)
                {
                    Console.WriteLine(i+" Exit from Loop");
                    break;
                }
                else if (i == 5)
                {                   
                    continue;                    
                    Console.WriteLine(i + " Skip this iteration"); //Unreachable Code
                }
                else
                {
                    Console.WriteLine(i);
                }
            }
            
            Console.ReadKey();
        }
    }
}

Output

0
1
2
3
4
6
7
8 Exit from Loop
__

Explanation:

In the above example we have created a loop and check condition that if value of i is equal to 8 then break clause will be invoked; if value of i equal to 5 the continue clause invoked; otherwise the loop print value of i. What happened if the value of i reaches to 8 or 5, see below.

i=8 //Loop gets terminated permanently
i=5 //Loop skip current iteration only

Summary

In this chapter you have learned break and continue statement with programming example. Where break is used for breaking the loop permanently; continue is used for skipping the current iteration only. In the next chapter you will learn about return keyword.

BackNext