Collection of Loop Sentences of C and Detailed Explanation of Cases

  • 2021-07-10 20:34:40
  • OfStack

There are many advantages in using loops-using loops can make the program realize judgment logic. With loops, you can take advantage of the powerful computing functions of computers. Below I list the loop statements in C #, and the code is as follows:

With the cyclic structure, it is beneficial to use the calculation

The powerful computing power of the computer

With the cyclic structure, it is beneficial to use the calculation

The powerful computing power of the computer

Loop statements in C #: while, for, foreach
1. while cycle


static void Main(string[] args)
{
 int[] hs = { 1,2,3,4,5,6,7,8,9};
 int ligh = hs.Length;
 while (ligh > 0)
 {
 Console.WriteLine(hs[ligh - 1]);
 ligh -= 1;
 }
 
 Console.ReadKey();
} 

2. for loop (for loop can be nested, for example, it will be used when doing bubble sorting)


static void Main(string[] args)
{
 int[] hs = { 1,2,3,4,5,6,7,8,9};
 // Flashback printing only needs to be modified 1 It can be judged under the following conditions 
 for (int i = 0; i < hs.Length; i++)
 {
 Console.WriteLine(hs[i].ToString());
 }
 
 Console.ReadKey();
} 

3. foreach loops through the elements in the collection (this writing seems to be unique to. NET)


static void Main(string[] args)
{
 int[] hs = { 1,2,3,4,5,6,7,8,9};
 // It's used here var Keyword, anonymous type ( Automatically inferred by the compiler ) You can replace it with int
 foreach (var item in hs)
 {
 Console.WriteLine(item.ToString());
 }
 
 Console.ReadKey();
}

for Loop Example

C # for Loop 1 is generally used in counting or sorting, which is equivalent to numbering each row of data. Therefore, the C # for loop plays an extremely important role in the development process.


int i; 
for(i=1;i<=10;++i) 
{ 
  Console.WriteLine("{0}",i); 
} 

The counter variable is an integer i, which starts at 1 and increments by 1 at the end of each loop. During each loop, the value of i is written to the console.
Note that when the value of i is 11, the code behind the loop is executed. This is because at the end of the loop where i is equal to 10, i is incremented to 11. This is in the test condition i < = 10, when the loop ends.

Finally, note that you can rewrite the above code by declaring the counter variable as part 1 of the C # for loop statement, as follows:


for(int i=1;i<=10;++i) 
{ 
  Console.WriteLine("{0}",i); 
} 

The above content is combined with C # language to achieve the basic cycle statement and combined with case introduction, friends in need can refer to it, I hope you support me a lot.


Related articles: