DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering C# Fundamentals: Do-While and For Loops

Meta Description: Learn how to efficiently control the flow of your C# programs using iteration statements like do-while and for loops. Explore practical examples, including nested loops, controlling loops with break and continue, and implementing interactive menus.

In C# programming, there are many situations where you'll need to repeat a block of code multiple times. This is where iteration statements, or loops, come into play. Whether you're processing a set of values, repeating actions until a condition is met, or iterating through user input, loops are fundamental.

In this article, we’ll explore do-while loops and for loops, with real-world examples. We’ll also cover key keywords like break and continue that help control loop execution.


The Do-While Loop

A do-while loop is similar to the while loop, but with a major difference: the do-while loop guarantees that the code inside will run at least once, even if the condition is false at the beginning.

This happens because the condition is evaluated after the loop body runs, as shown here:

do
{
    // Code to execute
} while (condition);
Enter fullscreen mode Exit fullscreen mode

Let’s look at an example where we ask a user to input a number:

int userInput;

do
{
    Console.WriteLine("Please enter a number greater than 10:");
    userInput = int.Parse(Console.ReadLine());
} while (userInput <= 10);

Console.WriteLine("Thank you, you entered: " + userInput);
Enter fullscreen mode Exit fullscreen mode

In this example, the code block asking for the user input will execute at least once, even if the user initially provides an invalid value. The loop keeps prompting the user until they enter a number greater than 10.

Why Use a Do-While Loop?

The do-while loop is useful when you want to ensure that a block of code runs at least once before checking a condition. For example, it’s commonly used for menus or prompts that should always display at least once.


The For Loop

The for loop is one of the most frequently used loop structures in C#. It's especially efficient when you know how many times the loop needs to run. The syntax of a for loop is concise and easy to follow:

for (initialization; condition; increment)
{
    // Code to execute
}
Enter fullscreen mode Exit fullscreen mode
  • Initialization: Declares and initializes the loop counter.
  • Condition: Checked before each iteration. If true, the loop runs; if false, it exits.
  • Increment: Increases or decreases the counter after each iteration.

Here’s a simple example of a for loop where we display a countdown:

for (int countdown = 5; countdown > 0; countdown--)
{
    Console.WriteLine("Countdown: " + countdown);
}

Console.WriteLine("Liftoff!");
Enter fullscreen mode Exit fullscreen mode

In this case:

  • Initialization: int countdown = 5 starts the loop at 5.
  • Condition: countdown > 0 keeps the loop running as long as the countdown is greater than 0.
  • Increment: countdown-- decreases the countdown by 1 after each iteration.

Nested For Loops

You can also nest loops for more complex scenarios. Here’s an example that outputs a multiplication table:

for (int row = 1; row <= 3; row++)
{
    for (int col = 1; col <= 3; col++)
    {
        Console.Write(row * col + "\t");
    }
    Console.WriteLine();  // Newline after each row
}
Enter fullscreen mode Exit fullscreen mode

This loop prints a small 3x3 multiplication table. The outer loop controls the rows, while the inner loop controls the columns.


Controlling Loops with Break and Continue

C# provides two useful keywords to control the flow inside loops:

  • break: Exits the loop entirely.
  • continue: Skips the current iteration and moves to the next one.

Break Example:

If you want to stop the loop once a specific condition is met, you can use break:

for (int number = 1; number <= 10; number++)
{
    if (number == 7)
    {
        Console.WriteLine("Found 7, stopping the loop!");
        break;
    }
    Console.WriteLine(number);
}
Enter fullscreen mode Exit fullscreen mode

This will print numbers from 1 to 6, and when number is 7, it exits the loop.

Continue Example:

You can use continue to skip certain iterations:

for (int number = 1; number <= 10; number++)
{
    if (number % 2 == 0)
    {
        continue;  // Skip even numbers
    }
    Console.WriteLine(number);  // Only odd numbers will be printed
}
Enter fullscreen mode Exit fullscreen mode

This loop will only print odd numbers because continue skips the loop iteration for even numbers.


Practical Example: Do-While Loop with a Menu

Let's combine these concepts into a practical example where we create a simple menu that keeps running until the user selects the "exit" option:

string userChoice;

do
{
    Console.WriteLine("Choose an action:");
    Console.WriteLine("1. View balance");
    Console.WriteLine("2. Deposit money");
    Console.WriteLine("3. Withdraw money");
    Console.WriteLine("99. Exit");

    userChoice = Console.ReadLine();

    switch (userChoice)
    {
        case "1":
            Console.WriteLine("Your balance is $1000");
            break;
        case "2":
            Console.WriteLine("Depositing money...");
            break;
        case "3":
            Console.WriteLine("Withdrawing money...");
            break;
        case "99":
            Console.WriteLine("Exiting...");
            break;
        default:
            Console.WriteLine("Invalid option, please try again.");
            break;
    }

} while (userChoice != "99");

Console.WriteLine("Thank you for using the system.");
Enter fullscreen mode Exit fullscreen mode

In this example, the menu keeps displaying as long as the user doesn’t enter 99. The do-while loop ensures that the menu is shown at least once, and the switch statement handles different actions based on user input.


Conclusion

In this article, we explored the do-while and for loops in C#. Both loops are important tools for controlling the flow of your application. The do-while loop is useful when you need to ensure that a block of code runs at least once, while the for loop is perfect for situations where you know the exact number of iterations.

Additionally, we discussed how to use break to exit a loop early and continue to skip specific iterations. Mastering these looping structures is crucial for building efficient and maintainable C# programs.

Top comments (0)