Difference between break and continue

Source: Internet
Author: User

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 ();
}
}
}
 


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.