C # loop statement: 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.