SoFunction
Updated on 2025-03-07

Loop statements in C#: use of while, for, and foreach

A loop structure can realize the repeated execution of a program module, which is of great significance to us simplify programs and better organize algorithms. C# provides us with several loop statements, which are applicable to different situations, and are introduced in sequence below.

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

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


2. For loop (can be nested for loops, 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 requires modifying the judgment conditions for (int i = 0; i < ; i++)
 {
  (hs[i].ToString());
 }
  ();
}  


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

static void Main(string[] args)
{
 int[] hs = { 1,2,3,4,5,6,7,8,9};
 //The var keyword is used here, anonymous type (automatically inferred by the compiler), you can replace it with int foreach (var item in hs)
 {
  (());
 }
 ();
}

Through the introduction of the above specific examples, I hope it can inspire you and help you understand and use loop statements well.