This is the 13th day of my participation in the August More Text Challenge.More challenges in August

@TOC

Preface 👻

This article is the introduction of C# loop part of the knowledge of the extension content, from ☀️ learn to programming essential C# most basic knowledge introduction (three) — variables, constants, operators, judgment, loop this part of the content is hereby to introduce in detail

C# provides the following types of loops. This article introduces the meaning and usage of various loops in detail

Circulation type describe
For/foreach loop Execute a sequence of statements multiple times to simplify the code for managing loop variables.
The while loop The statement or statement group is repeated when the given condition is true. It tests the condition before executing the body of the loop.
do… The while loop It is similar to the while statement, except that it tests the condition at the end of the body of the loop.
Nested loop Can be in while, for, or do.. Use one or more loops within a while loop.

C# for/foreach loop 🎈

A for loop is a repeating control structure that allows you to write a loop that executes a certain number of times.


for

Syntax for loop in C#

for ( init; condition; increment )
{
   statement(s);
}
Copy the code

Here is the control flow for the for loop:

  1. Init is executed first and only once. This step allows you to declare and initialize any loop control variable. You can also write nothing here, as long as a semicolon appears.
  2. Next, the condition is judged. If true, the body of the loop is executed. If false, the body of the loop is not executed and the control flow jumps to the next statement immediately following the for loop.
  3. After executing the body of the for loop, the control flow jumps back to the above increment statement. This statement allows you to update loop control variables. The statement can be left blank as long as a semicolon appears after the condition.
  4. The condition is judged again. If true, the loop is executed, and the process is repeated over and over (loop the body, then increment the step value, then rejudge the condition). When the condition becomes false, the for loop terminates.

The flow chart

The instance

The instanceusing System;

namespace Loops
{
   
    class Program
    {
        static void Main(string[] args)
        {
            /* For loop executes */
            for (int a = 10; a < 20; a = a + 1)
            {
                Console.WriteLine("Value of A: {0}", a); } Console.ReadLine(); }}}Copy the code

When the above code is compiled and executed, it produces the following results:

Value of A: 10 Value of A: 11 value of A: 12 value of A: 13 value of A: 14 value of A: 15 value of A: 17 value of A: 18 value of A: 19


foreach

C# also supports foreach loops, which can be used to iterate over an array or a collection object.

The following example has three parts:

  • Print the elements of an integer array through a foreach loop.
  • Prints the elements of an integer array through a for loop.
  • Foreach loop sets the calculator for array elements.
class ForEachTest
{
    static void Main(string[] args)
    {
        int[] fibarray = new int[] { 0.1.1.2.3.5.8.13 };
        foreach (int element in fibarray)
        {
            System.Console.WriteLine(element);
        }
        System.Console.WriteLine();


        // Similar to foreach loop
        for (int i = 0; i < fibarray.Length; i++)
        {
            System.Console.WriteLine(fibarray[i]);
        }
        System.Console.WriteLine();


        // Sets the calculator for the elements in the collection
        int count = 0;
        foreach (int element in fibarray)
        {
            count += 1;
            System.Console.WriteLine("Element #{0}: {1}", count, element);
        }
        System.Console.WriteLine("Number of elements in the array: {0}", count); }}Copy the code

The output is:

0, 1, 1, 2, 3, 5, 8, 13

0, 1, 1, 2, 3, 5, 8, 13

Element #1: 0 Element #2: 1 Element #3: 1 Element #4: 2 Element #5: 3 Element #6: 5 Element #7: 8 Element #8: 13 Number of elements in the array: 8

For more on foreach, see: the use of foreach traversal in C#


C# while loop 🎉

The while loop in C# repeats the target statement as long as the given condition is true.


grammar

Syntax for a while loop in C# :

while(condition)
{
   statement(s);
}
Copy the code

Here, statement(s) can be a single statement or a block of code made up of several statements. Condition can be any expression and is true for any non-zero value. The loop is executed when the condition is true.

When the condition is false, the program flow proceeds to the next statement following the loop.


The flow chart

The key point of the while loop here is that the == loop may not execute == once. When the condition is tested and the result is false, the body of the loop is skipped and the next statement immediately following the while loop is executed.

The instance

The instanceusing System;

namespace Loops
{
   
    class Program
    {
        static void Main(string[] args)
        {
            /* Local variable definition */
            int a = 10;

            /* The while loop executes */
            while (a < 20)
            {
                Console.WriteLine("Value of A: {0}", a); a++; } Console.ReadLine(); }}}Copy the code

When the above code is compiled and executed, it produces the following results:

Value of A: 10 Value of A: 11 value of A: 12 value of A: 13 value of A: 14 value of A: 15 value of A: 17 value of A: 18 value of A: 19


C# do… The while loop 🎄

Unlike for and while loops, they test the loop condition at the head of the loop. do… A while loop checks its conditions at the end of the loop. do… The while loop is similar to the while loop, but do… The while loop ensures that == executes the loop == at least once


grammar

In c # the do… Syntax for the while loop:

do
{
   statement(s);

}while( condition );
Copy the code

Note that the condition expression appears at the end of the loop, so statement(s) in the loop is executed at least once before the condition is tested. If the condition is true, the control flow jumps back to do above and re-executes Statement (s) in the loop. This process repeats until the given condition becomes false.


The flow chart

The instance

The instanceusing System;

namespace Loops
{
   
    class Program
    {
        static void Main(string[] args)
        {
            /* Local variable definition */
            int a = 10;

            /* do executes the */ loop
            do
            {
               Console.WriteLine("Value of A: {0}", a);
                a = a + 1;
            } while (a < 20); Console.ReadLine(); }}}Copy the code

When the above code is compiled and executed, it produces the following results:

Value of A: 10 Value of A: 11 value of A: 12 value of A: 13 value of A: 14 value of A: 15 value of A: 17 value of A: 18 value of A: 19


C# nested loop 👍

C# allows you to use a loop within a loop. Here are a few examples to illustrate this concept.


grammar

Syntax for nested for loops in C#

for ( init; condition; increment )
{
   for ( init; condition; increment )
   {
      statement(s);
   }
   statement(s);
}
Copy the code

Syntax for nested while loops in C# :

while(condition)
{
   while(condition)
   {
      statement(s);
   }
   statement(s);
}
Copy the code

Nested in C# do… The syntax of the while loop:

do
{
   statement(s);
   do
   {
      statement(s);
   }while( condition );

}while( condition );
Copy the code

One thing to note about nested loops is that you can nest any other type of loop within any type of loop. For example, a for loop can be nested within a while loop and vice versa.


Example The following program uses a nested for loop to find primes between 2 and 100:

The instanceusing System;

namespace Loops
{
   
   class Program
   {
      static void Main(string[] args)
      {
         /* Local variable definition */
         int i, j;

         for (i = 2; i < 100; i++)
         {
            for (j = 2; j <= (i / j); j++)
               if ((i % j) == 0) break; // If found, it is not prime
            if (j > (i / j))
               Console.WriteLine("{0} is prime", i); } Console.ReadLine(); }}}Copy the code

When the above code is compiled and executed, it produces the following results:

2 is a prime number 3 is a prime number 5 is a prime number 7 is a prime number 11 is a prime number 13 is a prime number 17 is a prime number 19 is a prime number 29 is a prime number 31 is a prime number 37 is a prime number 41 is a prime number 43 is a prime number 47 is a prime number 53 is a prime number 59 is a prime number 61 is a prime number 67 is a prime 71 is a prime 73 is a prime 79 is a prime 83 is a prime 89 is a prime 97 is a prime


Loop control statement 🎊

Loop control statements change the normal sequence of execution. When execution leaves a scope, all automatic objects created in that scope are destroyed. C# provides the following control statements.

Control statements describe
Break statement Terminate the loop or switch statement, and the flow continues to execute the statement immediately following the loop or switch statement.
The continue statement Causes the loop to skip the rest of the body, restarting the test condition immediately.

C # break statement

The break statement in C# can be used in two ways:

  1. When a break statement occurs within a loop, the loop terminates immediately, and the program flow continues to execute the statement immediately following the loop.
  2. It can be used to terminate a case in a switch statement.

If you are using nested loops (that is, one loop nested within another), the break statement stops executing the innermost loop and then starts executing the next line of code after that block.


grammar

Syntax for break statement in C# :

break;
Copy the code

The flow chart


The instance

The instanceusing System;

namespace Loops
{
   
    class Program
    {
        static void Main(string[] args)
        {
            /* Local variable definition */
            int a = 10;

            /* The while loop executes */
            while (a < 20)
            {
                Console.WriteLine("Value of A: {0}", a);
                a++;
                if (a > 15)
                {
                    /* Terminate loop */ with break statement
                    break; } } Console.ReadLine(); }}}Copy the code

When the above code is compiled and executed, it produces the following results:

Value of A: 10 Value of A: 11 value of A: 12 value of A: 13 value of A: 14 value of A: 15


C # the continue statement

The continue statement in C# is a bit like the break statement. Instead of forcing termination, continue skips code in the current loop and forces the next loop to start.

For the for loop, the continue statement causes the conditional test and the incremental part of the loop to be executed. For while and do… The while loop, the continue statement causes program control to revert to the conditional test.


grammar

Syntax for a continue statement in C# :

continue;
Copy the code

The flow chart

The instance

The instanceusing System;

namespace Loops
{
   
    class Program
    {
        static void Main(string[] args)
        {
            /* Local variable definition */
            int a = 10;

            /* do executes the */ loop
            do
            {
                if (a == 15)
                {
                    /* Skip the iteration */
                    a = a + 1;
                    continue;
                }
                Console.WriteLine("Value of A: {0}", a);
                a++;

            } while (a < 20); Console.ReadLine(); }}}Copy the code

When the above code is compiled and executed, it produces the following results:

Value of A: 10 Value of A: 11 value of A: 12 value of A: 13 value of A: 14 value of A: 16 value of A: 17 value of A: 18 value of A: 19


Infinite loop 💫

If the condition is never false, the loop becomes infinite. A for loop can be used to implement an infinite loop in the traditional sense. Since none of the three expressions that make up the loop is required, you can leave some conditional expressions blank to form an infinite loop.

The instanceusing System;

namespace Loops
{
   
    class Program
    {
        static void Main(string[] args)
        {
            for(; ;) { Console.WriteLine("Hey! I am Trapped"); }}}}Copy the code

A conditional expression is assumed to be true when it does not exist. You can also set an initial value and increment expression, but generally programmers prefer to use for(; 😉 Structure to represent an infinite loop.


Conclusion 💬

This article is an extension of the C# loop. It comes from ☀️ : variables, constants, operators, judgments, loops

This article mainly introduces the loop in C#. If you want to learn more about the basics of C#, click on the basics above to see all the basics of C#. Keep working on 🎅