break, continue and goto statements in C#

Hi programmers, welcome to new article of c#.net. This post i’ll write definition and programs for break statement , continue statement and goto in c# console application.
Break statement :
The Break statement terminates the closest enclosing loop or switch statement in which it appears. loop such as for ,while,do while loop. let’s see the codes.

Example 1
Example 2

Continue Statement :
The Continue statement passes control to next iteration of the enclosing while, do while, for or foreach loop in which it appears. let’s see the codes.

Goto Statement :
The goto statement transfers the program control directly to a labeled statement.
let’s see the codes.

Example 1
Example 2

Directly Test below codes into Editor.

#Break Statement Example
using System;
namespace ConsoleApp1 {
    class Program {       
        static void Main(string[] args)
        {
           for(int i = 1; i <= 10; i++)
            {
                if(i == 4)
                {
                    break;
                }
                Console.WriteLine(i);
            }
        }       
    }
}

#Continue Statement Example
using System;
namespace ConsoleApp1 {
    class Program {       
        static void Main(string[] args)
        {
           for(int i = 1; i<= 10; i++)
            {
                if(i < 4)
                {
                    continue;
                }
                Console.WriteLine(i);
            }
        }       
    }
}


#Goto Statement Example 1
using System;
namespace ConsoleApp1 {
    class Program {       
        static void Main(string[] args)
        {
            int i = 1;
            while(i <= 10)
            {
                if (i == 4)
                {
                    goto G1;
                }
                i++;
            }
        G1: Console.WriteLine(i);
        }       
    }
}

#Goto Statement Example 2
using System;
namespace ConsoleApp1 {
    class Program {       
        static void Main(string[] args)
        {
            Console.Write("Enter Your Selection (1,2, or 3): ");
            string s = Console.ReadLine();
            int n = int.Parse(s);

            switch(n)
            {
                case 1: Console.WriteLine("Current value is {0}", 1);
                        break;
                case 2:
                    Console.WriteLine("Current value is {0}", 2);
                    break;
                case 3:
                    Console.WriteLine("Current value is {0}", 3);
                    goto case 1;
                default:
                    Console.WriteLine("Sorry , Invalid Selection ");
                    break;
            }
        }       
    }
}

Happy Coding…Thanks.

Post Author: adama