Looping Structs in C#

We will go through the different looping structs in C#. These are statements that are used to repeat a certain action or code block multiple times based on a given condition.

Overview

Another important construct in programming is the capability to iterate your code or in other words doing a task multiple times and is usually terminated once the condition is met.

We’ll go through the most common type of loop in C# first, which is the for loop then we’ll also going to take a look at do..while loop and while loop.

for Loop

The basic structure of a for loop in C# and a sample is below:

for (assignment; condition; increment / decrement)
    statement or block of statements;
    enclosed in { } brackets

Example code:

    static void Main(string[] args)
    {
        int val;
        for (val = -5; val <= 5; val++)
        {
            if (val > 0)
                Console.Write("z");
            else if (val < 0)
                Console.Write("x");
        }
    }

unassigned

Important Points about for loop in C#

  • The three statements inside the for()` – assignment, condition, and increment/decrement – are optional.

    You can use any combination of these and even decide not to use any one at all but you still have to put the semicolons, doing so will make what is called ‘infinite loop’.

    for (; ; ) { }

    for (; i < 10; i++)

    for (int i=3; ;i--)

    for(; i>5;)

  • If you declare a variable in for()’s assignment, it’s life (scope) will only last inside the loop and it will die after the loop body terminates.

    On the example below, the compiler will complain at line 1 that “x is an undeclared identifier.

    for (int x = 0; x < 5; x++) { Console.WriteLine(“The value of x is " + x); } x++;

    unassigned

  • You can use break and continue in for loops or any other loop to change the normal execution path.

    break - terminates the loop and transfers the execution to a point just outside the for loop. continue - ignores the remaining part of the current iteration and starts the next iteration.

    Consider the following for loop code with break and continue:

    break sample:

      static void Main(string[] args)
      {
          for (int i = 0; i < 3; i++)
          {
              break; //No output. Console.WriteLine will be unreachable
              Console.WriteLine("The value of i is " + i);
          }
      }
    

    continue sample:

      static void Main(string[] args)
      {
          for (int i = 0; i < 5; i++)
          {
              if (i == 2)
              {
                  continue;
              }
              Console.WriteLine("value of i is " + i);
          }
      }
    

    unassigned

do…while Loop

The basic structure of do..while in C# is:

do
statement or block of statements
while (boolean expression);

The statements under do will execute the first time and then the condition is checked.

The loop will continue while the condition remains true.

Consider the example below:

static void Main(string[] args)
{
    int x = 0;
    do
    {
        Console.WriteLine("value of x is " + x);
        x++;
    } while (x < 5);
}

unassigned

Important Points about do…while

  • The statements in a do...while() loop always executes at least once.
  • There is a semicolon ; after the while statement.

while Loop

The general form of while loop in C# is:

while (Boolean expression)
    statements or blocks of statements

The while loop is similar to the do...while loop, except that it checks the condition before entering the first iteration (execution of code inside the body of the loop).

Here’s a sample code on how while works in C#:

static void Main(string[] args)
{
    int x = 0;
    while(x < 5)
    {
        Console.WriteLine("value of x is " + x);
        x++;
    }
}

unassigned


🔚 end of document 🔚

References