C # cycle


Release date:2023-08-25 Update date:2023-10-13 Editor:admin View counts:350

Label:

C # cycle

Sometimes, you may need to execute the same piece of code multiple times. Ingeneral, statements are executed sequentially: the first statement in the function is executed first, then the second statement, and so on.

Programming languages provide a variety of control structures that allow formore complex execution paths.

Loop statements allow us to execute a statement or group of statements multiple times. Here is the general form of loop statements in most programming languages:

../../_images/loop_architecture.jpg

Cyclic structure

Cycle type

C # provides the following loop types. Click the link to view the details ofeach type.

Cycle type

Description

While cycle

Repeat a statement or group of statements when a given condition is true. Ittests the condition before executing the loop body.

For/foreach cycle

Execute a sequence of statements multiple times to simplify the code for managing loop variables.

do…while cycle

Except that it tests the condition at the end of the loop body, the rest is similar to the while statement.

Nested loop

You can use one or more loops within a while, for, or do..while loop.

Loop control statement

The loop control statement changes 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. Click the link to see the details of each statement.

Control statement

Description

Break statement

Terminates the loop or switch statement, and the program flow continues to execute the next statement immediately following loop or switch.

Continue statement

Skip this cycle and start the next cycle.

Infinite cycle

If the condition is never false, the loop becomes an infinite loop. for loops can be used to realize infinite loops in the traditional sense.Becausenone of the three expressions that make up the loop is required, youcan leave some conditional expressions blank to form an infinite loop.

Example

using System;
namespace Loops
{

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

        }
    }
}

When a conditional expression does not exist, it is assumed to be true. You can also set an initial value and an incremental expression, but in general,programmers prefer to use the for(;;) structure to represent aninfinite loop.

Powered by TorCMS (https://github.com/bukun/TorCMS).