An Ultimate Guide to a One-Stop Solution to Loops in C#

At times finding a solution to a problem might seem recursive and a traditional coding approach to repeatedly execute a logic might drastically increase the code length. This can be resolved by implementing loops. Loops are conditional statements that can execute logic for any number of times and also minimize the code to a major extent.

In this tutorial, you will learn about many forms of loops in C#, which include while, do-while, for each, nested loops, continue, break, and switch, with syntax and code examples.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Introduction to Loops in C#

The repeated execution of a sequence of operations is common in programming. A loop is a basic programming element that allows you to repeat the execution of a piece of code. The loop's code is repeated a certain number of times or until it achieves a certain time, depending on the loop's kind. The situation is in order (exists).

what-is-loops-in-c#

After understanding loops in C#, you will look at a few different sorts of loops in further depth.

Types of Loops in C#

Loops are used to repeat one or more statements until a condition is met. The types of loops in C# are as follows:

  • While Loop

While the condition is any expression that yields a Boolean result–true or false–it is known as the loop condition because it defines how long the loop body will be repeated. The programming code performed at each loop iteration, i.e., anytime the input condition is true, is referred to as the loop body in this example.

Syntax:

while (condition)

 {  

         code body; 

 }

Flow Diagram:

while-loop-types-of-loops-in-C#

  • In the while loop, the Boolean expression is first calculated, and if it is true, the sequence of operations in the loop's body is executed.
  • The input condition is then checked again, and if it is true, the loop's body is executed once more.
  • All of this is repeated until the conditional expression returns false at some point.
  • At this point, the loop is terminated, and the program proceeds to the next line, immediately following the loop's body.
  • If the cycle condition returns false at the start, the body of the while loop may not be executed even once. If the cycle's condition is never broken, the loop will continue indefinitely.

Code Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace program1

{

class Program

{

static void Main(string[] args)

{

int i = 1; // Initialize the counter

while(i<=15)// Execute the loop body while the loop condition holds

{

Console.WriteLine(i);//print the counter value

i++;// Increment the counter

}

Console.ReadKey(); 

}

}

}

Output :

while-code-output-loops-in-c#

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

  • Do-While Loop

While the while loop checks the condition after each loop body execution, the do-while loop does not. A loop with a condition at the end is referred to as this loop-type (post-test loop).

Syntax:

do

{

   code

} while(condition);

Flow Diagram:

do-while-loop-loops-in-c#

  • The loop body is executed first, and its condition is evaluated.
  • If it is true, the loop's body is repeated; otherwise, it is terminated.
  • This logic is repeated until the loop's condition is broken. The loop's body is executed at least once.
  • If the loop's condition is always true, the loop will never end.

Code Example:

using System;

namespace LogicalPrograms

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.Write("x = ");

            int x = int.Parse(Console.ReadLine());

            decimal factorial = 1;

            do

            {

                factorial = factorial * x;

                x--;

            } while (x > 0);

            Console.Write($"The Factorial is: {factorial}");

            Console.ReadLine();

        }      

    }

}

Output:

do-while-types-of-loop-code-output

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

  • For Loop:

While the functionality of a for loop is like that of a while loop, the syntax is different. When loop statements are to be executed are known ahead of time, for loops are preferred. The loop variable initialization, condition to be tested, and increment/decrement of the loop variable are all done in one line in the for loop, resulting in a shorter, easier to debug looping structure. 

Syntax:

for (loop variable initialization ; testing condition; increment / decrement)

{   

    // statements to be executed

}

Variable Initialization: The variable that controls the loop is set here. It acts as a loop's starting point. It is possible to use a variable that has already been defined or to declare a variable that is just local to the loop.

Testing Condition: The circumstances in which loop statements are run. It's used to ensure that the loop's exit condition is correct. Either true or false must be returned. The control is withdrawn from the loop and stopped when the condition is false.

Increment / Decrement: The control returns to the testing condition after incrementing or decrementing the loop variable dependent on the requirement.

Flow Diagram:

For-loop-loops-in-C#

  • The initialization statement is run first. The variable is usually declared and initialized here. The amount of iterations the loop will do is controlled by this variable, which is known as a counter flag.
  • The steps in analyzing the FOR condition are as follows. A Boolean expression returns true or false when the condition is met. The statements/programs within the For loop are executed if the condition is true. This process is repeated until the condition is found to be untrue.
  • When the condition evaluates to false, the flow shifts from inside the loop to outside the block.

Code Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

public class sharpExercise

{

    static void Main(string[] args)

    {        

        int a, b, i, result;

        // Reading number

        Console.Write("Enter any number: ");

        a = Convert.ToInt32(Console.ReadLine());

        Console.Write("Enter any number: ");

        b = Convert.ToInt32(Console.ReadLine());

        result = 1;        

        //caculating power of given number

        for (i = 1; i <= b; i++)

            result = result * a;            

        Console.Write("a^b : "+ result);

        Console.ReadLine();

    }

}

Output:

for-loop-output-code-types-of-loop

  • For Each Loop

Each loop in C# iterates through a collection of items, an array, or a list. When each loop is executed, it executes a block of code on a collection of items, passing through the items in the collection and finally displaying them one by one.

Syntax:

foreach (type variable in the collection)

 {

    // statements;

 }

Flow Diagram:

For-each-loops-in-C#

  • The for-each loop iterates through the elements in the collection; when using the for-each loop, it is mandatory to enclose statements in curly braces.
  • You can use the same type as the array's base type when declaring a loop counter variable.

Code Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

public class program1

{

  static void Main (string[]args)

  {

    int[] numbers = { 2, 4, 6, 8, 10, 12, 14, 16 };

    foreach (int i in numbers)

    {

      Console.Write (" " + i);

    }

    Console.WriteLine ();

    string[] towns =

    {

    "Paris", "London", "USA", "NewYork"};

    foreach (string town in towns)

    {

      Console.Write (" " + town);

    }

    Console.ReadLine ();

  }

}

Output:

for-each-types-of-loop-in-c#

  • Nested Loop

Nested loops are programming constructs made up of several nested loops within each other. You execute the innermost loop more frequently, while the outermost is executed less frequently.

Syntax:

for ( variable initialization ; testing condition; increment / decrement)

 {

  for(variable initialization ; testing condition; increment / decrement)

    {

    // statements;

    }

 }

Flow Diagram:

nested-loop-types-of-loop-in-c#

  • Following the initialization of the first for loop, the execution of its body, which contains the second (nested) loop, will begin.
  • Its variable will be initialized, its condition will be checked, and it will execute the code within its body, followed by the variable being updated and execution continuing until the condition returns false.
  • Following that, the second iteration of the first for loop will continue, its variable will be updated, and the entire second loop will be repeated.
  • The inner loop will be executed as many times as the outer loop's body.

Code Example:

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.Text;  

namespace Hello_Word  

{  

   class Program  

   {  

      static void Main(string[] args)  

      {  

         int value = 5;  

         int row, column, k ;  

         for (row = 1; row <= value; row++)  

         {  

            for (column = 1; column <= value-row; column++)  

            {  

               // Console.Write("");  

            }  

            for (k = 1; k <= row; k++)  

            {  

               Console.Write("*");  

            }  

            Console.WriteLine("");  

         }  

         Console.ReadLine();  

      }  

   }  

}

Output:

Nested_Loop_C_sharp

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

  • Continue

Continue is one of many conditional statements in the C# programming language that can be used inside a conditional loop block to function as a clause to continue the loop execution after the iterative condition is executed to move on to the execution of the next iteration in the conditional loop. It is commonly used with iterative conditional loops such as a for-while loop, a do-while loop, and a for-each loop.

Syntax:

continue;

Flow Diagram

continue-keyword-types-of-loops-C#

If there is a continue statement when the loop starts, it will stop the current iteration and control the next iteration by returning to the loop's start.

Code Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Hello_Word

{

  class Program

  {

    static void Main (string[]args)

    {

      int x = int.Parse (Console.ReadLine ());

      int sumofodd = 0;

      for (int i = 1; i <= x; i += 2)

{

if (i % 9 == 0)

{

continue;

}

sumofodd += i;

}

      Console.WriteLine ("sum = " + sumofodd);

    }

  }

Output:

continue-keyword-types-of-loops-in-c#

  • Break 

The break statement is used to end the loop or statement that it is present in. If they are present, it will pass the control to the statements that follow the break statement. If the break statement is present in the nested loop, it only terminates the loops that contain the break statement.

Syntax:

Break;

Flow Diagram

break-keyword-types-of-loops-C#

  • It checks for the specific condition at the start of the flow; if it is satisfied, the loop is continued.
  • At the point where the loop gets a break statement. Or the condition where this loop gets out of the loop with a break statement.

Code Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace Factorial

{

  class Program

  {

    static void Main ()

    {

      int x = 5;

      int fact = 1;

      while (true)

{

Console.Write (x);

if (x == 1)

{

break;

}

Console.Write ("*");

fact *= x;

x--;

}

      Console.WriteLine (" = {0}", fact);

      Console.ReadLine ();

    }

  }

}

Output:

break-keyword-in-types-of-loops-in-c#

  • Switch

The Switch statement in C# is a multiway branch statement. It provides an efficient method for transferring execution to different parts of a code based on the expression's value. The switch expression is an integer type, int, char, byte, short, enumeration, or string type. The expression is checked for various causes, and only the one that matches is executed.

Syntax:

switch (expression)

 {

case value1: // statement sequence

     break;

case value2: // statement sequence

     break;

case valueN: // statement sequence

     break;

default: // default statement sequence

 }

Flow Diagram:

switch-keyword-types-of-loops-C#

  • With the switch statement, it passes equally an expression to one of the case values.
  • If the value is not equal, the default case is used. This expression's value is then compared to the case identifier or the first case.
  • This expression's value is then compared to the case identifier or the first case.
  • If the first case matches, the code associated with that case is executed; when you reach the break, the execution will halt and exit the switch statement.
  • If the case does not match, the execution moves on to the next case. If this case matches, the second code block is executed; otherwise, the flow proceeds to the next case in the same manner.
  • Finally, the default code block is executed if no case matches.

Code Example:

using System;

namespace Conditional

{

    class SwitchCase

    {

        public static void Main(string[] args)

        {

            char cha;

            Console.WriteLine("type an alphabet");

            cha = Convert.ToChar(Console.ReadLine());

            switch(Char.ToLower(cha))

            {

                case 'a':

                case 'e':

                case 'i':

                case 'o':

                case 'u':

                    Console.WriteLine("Given character is vowel");

                    break;

                default:

                    Console.WriteLine("Given character is not a vowel");

                    break;

            }

        }

Output:

switch-case-code-output0types-of-loops

Now that you’ve completed the loops in the C# tutorial, summarize what you’ve learned so far.

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Next Steps

In this loops in C# tutorial, you looked at everything there is to know about loops in C#, including all the different types of loops, including while, do-while, for each, and many more, with introductions and syntax, as well as flow diagrams and descriptions. Finally, you saw all of these loops with code examples for a better learning experience.

This is the path for you if you want to go beyond Mobile and Software Development and gain knowledge of the most in-demand programming languages and skills today. In that case, Simplilearn's Mobile and Software Development Course is a good fit. Look into this well-known Bootcamp program for more information.

Do you have any comments or queries about this Loops in C# tutorial? Please leave them in the comments section at the bottom of this page if you do. Our experts will gladly respond to your questions as soon as possible!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.