Loop statement in C: Use of while for foreach
- 2021-07-10 20:36:58
- OfStack
Loop structure can realize the repeated execution of a program module, which is of great significance for us to simplify the program and organize the algorithm better. C # provides us with several kinds of loop statements, which are suitable for different situations, and are described in turn below.
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();
}
Through the introduction of the above specific examples, I hope to give you some enlightenment and help you understand and use circular sentences well.