Break statement:
The break statement causes the running program to immediately exit the loop contained in the innermost layer or exit a switch statement. Because it is used to exit a loop or switch statement, this form of break statement is valid only when it appears in these statements.
If the termination condition of a loop is very complex, it is much easier to use the break statement to implement certain conditions than to use a loop expression to express all the conditions.
For (var I = 1; I <= 10; I ++)
{
If (I = 6) break;
Document. write (I );
}
// Output result: 12345
Continue statement:
The continue statement is similar to the break statement. The difference is that it is not to exit a loop, but to start a new iteration of the loop.
The continue statement can only be used in the loop body of the while statement, do/while statement, for statement, or for/in statement. It may cause errors when used elsewhere!
For (var I = 1; I <= 10; I ++)
{
If (I = 6) continue;
Document. write (I );
}
// Output result: 1234578910
Example: use continue to calculate the sum of the numbers between 1 and 100 (including 1 and 100) except the number that can be divisible by 7.
Namespace @ continue
{
Class Program
{
Static void Main (string [] args)
{
Int sum = 0;
// Method 1
For (int I = 1; I <= 100; I ++)
{
If (I % 7 = 0)
{
Continue;
}
Sum + = I;
}
// Method 2
Int I = 1;
While (I <= 100)
{
If (I % 7 = 0)
{
I ++;
Continue;
}
Sum = sum + I;
I ++;
}
Console. WriteLine (sum );
Console. ReadKey ();
}
}
}