How do I terminate a loop using break statement?

Category: Introduction, viewed: 148 time(s).

The break statement terminates the enclosing loop or switch statement. After the break executed the control will be transferred to the next statement after the terminated loop or switch.

In the example below we initially want to do an iteration while the value of i is less than 50, so it equals to 50 iteration. But we also have a conditional check inside that loop that tells to exit the loop is i equals to 10.

To see a break inside a switch statement you can see at the following example, How do I use switch statement?.

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

namespace Kodecsharp.Example.Intro
{
    class BreakDemo
    {
        [STAThread]
        public static void Main(string[] args)
        {
            for (int i = 0; i < 50; i++)
            {
                if (i == 10)
                {
                    //
                    // break the for loop
                    //
                    break;
                }
                Console.WriteLine("i = " + i);
            }
            Console.ReadLine();
        }
    }
}

The result:

i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Network Sites

Statistics

Locations of visitors to this page