You are currently viewing C# Programming Looping: Everything You Need to Know

C# Programming Looping: Everything You Need to Know

Looping is a crucial concept in C# programming that allows for efficient repetition of code. This article explores the different types of loops in C#, including for, foreach, do, and while loops. We will provide code examples and explanations, along with loop control statements for added control.

The for Loop

The “for” loop is a versatile construct in C# that allows us to iterate over a block of code a specified number of times. Its syntax is as follows:

for (initialization; condition; increment) {

    // code to be executed
    
}

Let’s see an example that prints numbers 1 through 10 using the for loop:

public class App
{

  public static void Main()
  {
  
    for(int i = 1; i <= 10; i++)
    {
    
      // Print current value of i
      System.Console.Write("{0} ", i); 
      		
    }

  }

}

The loop is initialized with int i = 1. The condition i <= 10 checks if i is less than or equal to 10. After each iteration, i is incremented by 1. The loop executes the code inside the curly braces until the condition becomes false.

The foreach Loop

The “foreach” loop is used to iterate over elements of an array or a collection. Its syntax is as follows:

foreach (type variable in collection) {

    // code to be executed
    
}

Let’s see an example that iterates over the elements in the array and prints each element to the console:

public class App
{

  public static void Main()
  {

    int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    // Iterating over array elements
    foreach (int number in numbers)
    {
    
      System.Console.Write("{0} ", number);
      
    }

  }

}

The foreach loop iterates over each element in the “numbers” array. The loop variable “number” takes the value of each element in the array, allowing us to perform operations on it. In the example, print it out to the console.

The while Loop

The “while” loop is used when we want to execute a block of code repeatedly as long as a condition remains true. Its syntax is as follows:

while (condition) {

    // code to be executed
    
}

Let’s see an example that prints numbers 1 through 10 using the while loop:

public class App
{

  public static void Main()
  {

    int i = 1;

    while (i <= 10)
    {

      System.Console.Write("{0} ", i);

      // Add 1 to 1
      i++;

    }

  }

}

We start with i = 1, and as long as i is less than or equal to 10, the loop continues. The loop control variable i is incremented by 1 after each iteration.

The do-while Loop

The “do-while” loop is similar to the “while” loop, but the condition is checked at the end of the loop. This guarantees that the loop executes at least once. Its syntax is as follows:

do {

    // code to be executed
    
} while (condition);

Let’s see an example that prints numbers 1 through 10 using the do-while loop:

public class App
{

  public static void Main()
  {
  
    int i = 1;
    
    do
    {
    
      System.Console.Write("{0} ", i);
      
      // Add 1 to i
      i++;
    
    } while (i <= 10);
  
  }

}

The loop starts by executing the code inside the block and then checks the condition i <= 10. If the condition is true, the loop continues. The loop control variable i is incremented by 1 after each iteration.

Loop Control Statements

In addition to the basic loop structures, C# provides loop control statements that allow for more precise control over loops. These statements include:

The break Statement

The “break” statement is used to exit the loop prematurely. When encountered within a loop, it immediately terminates the loop and transfers control to the statement following the loop.

public class App
{

  public static void Main()
  {
  
    for (int i = 1; i <= 10; i++)
    {
    
      if (i == 6)
      {
      
        // Exit loop
        break;
      
      }
      
      System.Console.WriteLine("{0} ", i);
    
    }
  
  }

}

The for loop iterates from 1 to 10. However, when i becomes 6, the break statement is encountered, and the loop is terminated. As a result, only numbers 1 to 5 are printed to the console.

The continue Statement

The “continue” statement is used to skip the current iteration of the loop and move to the next iteration. It is useful when you want to skip specific iterations based on certain conditions.

public class App
{

  public static void Main()
  {
  
    for (int i = 1; i <= 10; i++)
    {
    
      if (i == 6)
      {
      
        // Move to next iteration
        // Skip 6
        continue;
      
      }
    
      System.Console.Write("{0} ", i);
    
    }
  
  }

}

The for loop iterates from 1 to 10. However, when i becomes 6, the continue statement is encountered. This statement causes the loop to skip the rest of the current iteration and move to the next iteration. As a result, the number 6 is skipped, and the output will be 1 2 3 4 5 7 8 9 10.

These control statements provide additional control and flexibility within loops, allowing you to break out of loops prematurely, or skip iterations.

Conclusion

Loops are fundamental constructs in C# programming that allow us to repeat a block of code efficiently. By utilizing for, foreach, do-while, and while loops, along with loop control statements like “break” and “continue,” we gain greater control over our code’s flow and can handle various scenarios. Understanding these looping techniques will empower you to write more robust and flexible C# programs.

Sources

I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!

Leave a Reply