DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering C# Fundamentals: Iteration Statements

Meta Description:
Learn the fundamentals of iteration statements in C# with this comprehensive guide. Discover how to use while, do-while, and for loops to automate repetitive tasks. Explore practical examples, including nested loops and infinite loops, and understand how to choose the right loop for different scenarios.

Now that we've covered the most commonly used decision-making statements in C#, it’s time to explore another important concept in programming: iteration statements, also known as loops. Loops allow us to execute a set of statements repeatedly, typically until a specific condition is met. This makes them essential for tasks like processing user input, working with collections of data, or performing repetitive operations.

What are Iterations and Why Are They Important?

In real-world applications, you will often need to execute the same block of code multiple times. Whether it’s counting the number of files in a directory, repeatedly asking the user for input until they provide valid data, or performing calculations a certain number of times, loops provide a powerful way to automate repetitive tasks.

C# provides several types of loops, including:

  • while loop
  • do-while loop
  • for loop

Each type of loop serves a specific purpose, and understanding them is key to writing efficient and clear C# code.


The while Loop

The while loop is one of the simplest types of loops in C#. It continuously executes a block of code while a specified condition remains true. The condition is checked before each iteration of the loop. If the condition is initially false, the loop will not execute at all.

Here’s the structure of a basic while loop:

int counter = 0;

while (counter < 5)
{
    Console.WriteLine("Counter: " + counter);
    counter++; // Increment the counter to avoid an infinite loop
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The loop will continue to run as long as counter is less than 5.
  • Each time through the loop, the value of counter is printed to the console.
  • After each iteration, counter is incremented by 1.
  • Once counter reaches 5, the loop stops.

Example: Asking for User Input

Let’s create a while loop that prompts the user to input a number and then prints that number to the console repeatedly until they enter 0:

Console.WriteLine("Enter a number (0 to quit): ");
int userNumber = int.Parse(Console.ReadLine());

while (userNumber != 0)
{
    Console.WriteLine("You entered: " + userNumber);
    Console.WriteLine("Enter another number (0 to quit): ");
    userNumber = int.Parse(Console.ReadLine());
}

Console.WriteLine("You have exited the loop.");
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The loop continues to run until the user inputs 0.
  • Each time through the loop, the user is prompted for a new number, which is displayed back to them.

The do-while Loop

The do-while loop is similar to the while loop, but with one key difference: the code inside the loop is guaranteed to run at least once because the condition is checked after the loop has executed.

Here’s the structure of a do-while loop:

int i = 0;

do
{
    Console.WriteLine("Counter: " + i);
    i++;
} while (i < 5);
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • In this example, the do block will execute, and then the condition (i < 5) is evaluated.
  • If the condition is true, the loop continues.
  • If the condition is false, the loop stops.
  • The key difference is that the loop will always execute at least once, even if the condition is initially false.

The for Loop

The for loop is commonly used when you know in advance how many times you want to repeat a block of code. It is more compact than the while loop and consists of three parts:

  1. Initialization: Defines the starting point (usually a counter variable).
  2. Condition: Checks whether the loop should continue.
  3. Increment/Decrement: Updates the counter after each iteration.

Here’s a basic for loop:

for (int j = 0; j < 5; j++)
{
    Console.WriteLine("Counter: " + j);
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The for loop initializes the counter j to 0.
  • The condition j < 5 is checked before each iteration.
  • After each iteration, j is incremented by 1.
  • The loop runs 5 times, printing the value of j each time.

Example: Countdown Timer with for Loop

Here’s a practical example of a for loop that counts down from 10 to 0:

for (int countdown = 10; countdown >= 0; countdown--)
{
    Console.WriteLine("Countdown: " + countdown);
}
Console.WriteLine("Blastoff!");
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The counter countdown starts at 10 and decrements (countdown--) after each iteration.
  • Once the counter reaches 0, the loop ends, and "Blastoff!" is printed to the console.

Nested Loops

You can also nest loops inside each other. This is useful when you need to perform repeated tasks within another repeated task, such as iterating through rows and columns in a matrix.

Here’s an example of a nested while loop:

int outer = 1;

while (outer <= 3)
{
    int inner = 1;
    while (inner <= 3)
    {
        Console.WriteLine("Outer: " + outer + ", Inner: " + inner);
        inner++;
    }
    outer++;
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The outer loop runs 3 times.
  • Inside the outer loop, there is another loop that also runs 3 times.
  • For each iteration of the outer loop, the inner loop executes completely.

Infinite Loops

Be cautious when writing loops, as it's easy to accidentally create an infinite loop if the condition never becomes false. Here’s an example of an intentional infinite loop using the while (true) pattern:

while (true)
{
    Console.WriteLine(DateTime.Now);
    System.Threading.Thread.Sleep(1000); // Pause for 1 second
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • This loop will print the current time every second.
  • The loop will continue forever until the application is manually stopped.

Conclusion

Loops are a fundamental building block of any programming language, allowing you to automate repetitive tasks. In C#, you can use while, do-while, and for loops depending on the specific scenario. Whether you need to iterate over a known range of values, repeat actions based on a condition, or create nested loops for complex operations, C# provides flexible iteration options.

  • Use while when the number of iterations isn’t known upfront and depends on a condition.
  • Use do-while when you want the loop to run at least once.
  • Use for when you know exactly how many times the loop should run.
  • Be cautious of infinite loops and ensure that your loop conditions are properly defined.

Top comments (0)