Loop statements in C #: while LOOP and for loop (1 ),

Source: Internet
Author: User

Loop statements in C #: while LOOP and for loop (1 ),

For example, if we want to output hundreds of numbers when doing a lot of things, one output is not only troublesome, but also time-consuming and inefficient. At this time, C # provides us with a simpler output method, that is, a loop. There are multiple types of loops. Here I compare two types of loops: while LOOP & for loop.

First, the while loop:

 

While loop format is very simple:

While (loop condition)

{

Loop body

}

This means that when the logical value is "true", the loop body will keep repeating until the logical value changes to "false. If the logical value is always true, the loop will not stop, that is, the "endless loop" We often say ". For example:

While (true)

{

Console. Write (1 );

}

That is, the number 1 is continuously output. Such a cycle has no value. If you want to rewrite this code, we will do this:

Use the while loop method to output 10 1 records.

First, we can set an integer type variable int I = 10,

 

Int I = 10;

While (I> 0)

{

Console. Write (I );

I = I-1;

}

Console. ReadLine ();

The code is written.

Analysis: When this program is executed,

First loop: Because the variable I = 10, so I> 0 is true, loop execution, to I = I-1, execute the second loop, then the variable I becomes 9;

The second loop: because after the first loop is executed I = 9, I> 0, is true, and then executes the loop, to the I = I-1, start to execute the third loop, the variable I is changed to 8, and so on.

When the loop is executed for 11th times, the variable I = 0 does not meet the I> 0 condition, so it is false. Then the loop ends, so the program outputs 10 1 and stops. It is much easier to output a large number of numbers.

 

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.