C# break

break stops a loop, such as for loop, foreach loop and while loop.

using System.Windows.Forms;
int sum=0;
for (int i=0;i < 10;i++)
{
sum += i;
}
MessageBox.Show(sum.ToString()); //45
sum=0;
for (int i=0;i < 10;i++)
{
if (i == 5) break;
sum += i;
}
MessageBox.Show(sum.ToString()); //10

break stops a while loop.
int i=9;
int sum=0;
while (i > 0)
{
if (i == 5) break;
sum += i;
i--;
} //sum=30 (9+8+7+6)

Using goto statement to jump out of multiple loops.
int ori = 10;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 10; j++)
{
ori = ori + 5;
if (i == 3) goto pos;
}
}
pos:
ori += 10; //175


endmemo.com © 2017  Terms of Use | Home