C # Differences between while and for loop statements

Source: Internet
Author: User

C # Differences between while and for loop statements

The while statement executes a statement or block until the specified expression is calculated as false.

// Statements_while.cs
Using system;
Class whiletest
{
Static void main ()
    {
Int n = 1;
While (n <6)
        {
Console. writeline ("current value of n is {0}", n );
N ++;
        }
    }
}

The test of the while expression occurs before each loop, so the while loop is executed zero or more times. This is different from executing a do loop once or multiple times.

When a break, goto, return, or throw statement transfers control beyond a while loop, the loop can be terminated. To pass control to the next iteration without exiting the loop, use the continue statement. Note that in the preceding three examples, the output varies depending on the position where int n increments. In the following example, no output is generated.

// Statements_while_3.cs
// No output is generated
Using system;
Class whiletest
{
Static void main ()
    {
Int n = 5;
While (++ n <6)
        {
Console. writeline ("current value of n is {0}", n );
        }
  

C # for statement

C # for statements are the most common loop structure in most languages, but the syntax is not the same, but the usage is the same.

Code: for (initial value; test; increment/decrement value) {one or more statements;} c # statements followed by the for loop. If you want for to control multiple statements, use the code block symbol to enclose these statements.

Only the even number is displayed during the loop !!!

Void button2_click (object sender, eventargs e)
{
For (int I = 1; I <26; I + = 2)
{
Label2.text + = I + ","; // do not use tostring () because it is followed by string
}
}


Or easy to understand
Protected void button2_click (object sender, eventargs e)
{
For (int I = 1; I <26; I ++)
{
If (I % 2 = 0) // if the remainder of Division 2 is 0
{
Label2.text + = I + ",";
}

}
}

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.