Home > C# > Loops in C#

C# Loops

Loops are control structures that are used to execute a portion of code multiple times. Compiler executes each statement of loop body in sequential order. However, we must remember that loops are different from functions. As a loop will repeat same code (once loop starts its execution) unless given condition is false. While functions will repeat a block of code only when we make an explicit or implicit to the function.

Types of Loops in C#

Different types of loops in C# are:

  1. while loop
  2. do-while loop
  3. for loop
  4. foreach loop

We can use all these loops inside each other. This is the nesting of loops.

while loop

This loop will run while the given condition is true. It checks the condition of the loop before executing a body of a loop. This loop runs 0 or more times. We use while loop when we don’t know the exact number of iterations.
The basic syntax is:

Initialize loop_variable;
while(condition)
{
     //loop body
     Increment/decrement;
}

The compiler executes the Loop body only when the condition is true.
Example Program

using System;

namespace while_loop
{
    class Program
    {
        static void Main(string[] args)
        {
             // initializing variable
            int x=0;
            while(x<10) // condition to be checked
            {
                Console.WriteLine("This is a while loop. Value of x = " + x);
                x++; // increment
            }
        }
    }
}

Output
while loop - C# Loops

In the example above we see that the compiler prints the message we wrote inside loop body 10 times. And when loop condition is false i.e. when the value of x=10 compiler doesn’t print the message on the console.

Nested While loop

Nested while loops mean that one or more while loops inside another while loop(s).
We can write Nested while loops as

Initialize loop_variable;
while(condition)
{
     //Outer while loop body 
Initialize loop_variable;
     while(condition)
     {
          //Inner while loop body
          Increment/decrement;
     }
     .
     .
     .
     Increment/decrement;
}

It is not necessary to initialize inner loop variable inside the outer loop. However, it is necessary that we should initialize the Loop variable before loops. Hence avoiding compile time error in a program.
Similarly, it is not necessary to increment or decrement outer loop variable before or after inner loop. It completely depends on the nature or requirement of a program to when incrementing or decrement loop variable.
Example Program

using System;

namespace while_loop
{
    class Program
    {
        static void Main(string[] args)
        {
            // initializing variable
            int x=0;
            while(x<2)// Outer loop condition
            {
                Console.WriteLine("This is Outer while loop. Value of x = " + x);
                x++;// increment
                int y = 0;
                while(y<3)// inner loop condition
                {
                    Console.WriteLine("This is inner while loop. Value of y = " + y);
                    y++;// increment
                }
            }
        }
    }
}

Output
nested while loop -Types of Loops in C#

In the program written above. We can see that Inner loop is executed 3 times for outer loop i.e. when x=0. After that x is incremented to 1 and the inner loop is again executed. Hence inner loop is executed every time outer loop condition is true. Remember inner loop will only execute when its own condition is also true.

do-while loop

do while loop is almost like while loop. But it runs 1 or more times. In the do-while loop, Compiler checks the condition after executing the loop body.
Its basic syntax is

Initialize loop_variable;
do
{
     // body
} while (condition);

Example Program

using System;

namespace do_while_loop
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 0;
            do
            {
                Console.WriteLine("This is a Do while loop. Value of x = "+x);
                x++;
            } while (x < 3);
        }
    }
}

Output

 do while loop - Types of Loops in C#

In this example above do while loop worked almost same as while loop. But have a look at below example in which condition is false from start but do while loop will execute its body at least 1 time.

Example program

using System;

namespace do_while_loop
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 0;
            do
            {
                Console.WriteLine("This is a Do while loop. Value of x = "+x);
                x++;
            } while (x < 0);
        }
    }
}

As we can see that value of x is 0 which violates the given condition yet the compiler executes the body of the do-while loop.
Output
 do-while false - Types of Loops in C#

Nested do-while loops

Nested do while loops are the do-while loop(s) inside another do-while loop(s).
The syntax for nested do-while loops is

Initialize loop_variable;
do
{
     // body
     Initialize loop_variable;
     do
     {
          // body
     }while (condition);
     .
     .
     .
} while (condition);

It is not necessary to initialize inner loop variable inside the outer loop. However, it is necessary we should initialize the loop variable before the loops. Hence avoiding compile time error in the program.
Similarly, it is not necessary to increment or decrement outer loop variable before or after inner loop. It completely depends on the nature or requirement of a program to when incrementing or decrement loop variable.

Example program

using System;

namespace do_while_loop
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 0;
            do
            {
                Console.WriteLine("This is Outer Do while loop. Value of x = "+x);
                x++;
                int y = 0;
                do
                {
                    Console.WriteLine("This is inner Do while loop. Value of y = " + y);
                    y++;
                } while (y < 0);
            } while (x < 3);
        }
    }
}

Output
nested do while loop - Types of Loops in C#

Now it is clear that a do while loop will execute its body at least one time. As inner loop condition is false. But it executes its body one time for each time outer loop is executed.

For Loop

This is a loop we use when we already know the exact number of iterations for a block of code. In this loop, we initialize the loop variable & then the compiler checks the condition. If the condition is true the body of the loop is executed and at the end, a variable is incremented or decremented
Basic Syntax is:

for (initialize; condition; Increment/decrement)
{
     //loop body
}
Increment/decrement can be done inside loop body. Its syntax is like 
for (initialize; condition;)
{
     //loop body
Increment/decrement;
}
For loop can also be used as:
initialize;
for(;condition;)
{
      //body
Increment/decrement;
}

The difference between two above mentioned syntax is that in the 1st one increment/ decrement is done at the end of statements in the loop body. And in 2nd increment/ decrement is done on the line where the user writes it inside the loop body.
Example Program

using System;

namespace for_loop
{
    class Program
    {
        static void Main(string[] args)
        {
                /* for loop execution */
                for (int x = 0; x < 5; x++)
                {
                    Console.WriteLine("This is a for loop. Value of x =" + x);
                }
        }
    }
}

Output
for loop -Types of Loops in C#
When our compiler executes the above program & reaches the for loop it initializes x with 0 and then checks for a condition which is x<5 so x is less than 5 and loop body will be executed. At the end, x is incremented with 1. And this will be repeated until loop condition is false.
Here it is obvious that compiler initializes x will only once. And the condition for the while loop is checked every time.

Nested for Loops

Nested for loops means that for loop(s) inside other for loop(s).
We can write nested for loops as:

for (initialize; condition; Increment/decrement)
{
      //Outer for loop body
     for (initialize; condition; Increment/decrement)
     {
          // Inner for loop body
     }
     .
     .
     .
}

Here we should remember that it is not necessary to initialize inner loop variable inside the outer loop. However, it is necessary that we should initialize the Loop variable before the loops. Hence avoiding compile time error in a program.
Similarly, it is not necessary to increment or decrement outer loop variable before or after inner loop. It completely depends on the nature or requirement of a program to when incrementing or decrement loop variable.
Example program

using System;

namespace for_loop
{
    class Program
    {
        static void Main(string[] args)
        {
            /* for loop execution */
            for (int x = 0; x < 2; x++)
            {
                Console.WriteLine("This is outer for loop. Value of x =" + x);
                for (int y = 0; y < 5; y++)
                {
                    Console.WriteLine("This is inner for loop. Value of y =" + y);
                }
            }
        }
    }
}

Output
nested for loop - Types of Loops in C#

Just like nested while and do-while loops nested for loops works same i.e. inner loop will be executed the number of times depending on its condition each time outer loop is executed.
Note: – It is not necessary that loops can be nested inside same loops. i.e. for loops can be nested inside while and do-while similarly, while and do- while loops can be nested inside for loop and each other as well.

Infinite Loops

Loops can be infinite. i.e. loop condition is never false. you can define infinite loops in different ways.
E.g.
While

     int x = 1;
     while (x > 1)
     {
          //body of the loop
     x++;
     }

do-while

     int x = 1;
     do
     {
          //loop body
     x++;
     } while (x > 1);

Mostly used is:
for

     for ( ; ; )
     {
          //loop body
     }

Other than these typical loops another type of loop called foreach loop is also available in C#.

3 thoughts on “Loops in C#

Leave a Reply

Your email address will not be published. Required fields are marked *