Mastering C# Fundamentals: Do-While and For Loops

moh_moh701

mohamed Tayel

Posted on September 25, 2024

Mastering C# Fundamentals: Do-While and For Loops

Mastering Loops in C#: A Practical Guide

Iteration statements, or loops, are fundamental in programming. They allow you to repeat a block of code multiple times, enabling automation and efficiency in tasks like processing user input, iterating through collections, or managing interactive menus. In this article, we’ll explore two essential loop structures in C#: do-while and for, along with key keywords like break and continue for controlling loop behavior.


The do-while Loop

The do-while loop is unique because it ensures the code block runs at least once, regardless of whether the condition is initially true or false. This makes it ideal for prompts or menus that must display at least once.

Syntax:

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

Example: Prompting User Input

int userInput;

do
{
    Console.WriteLine("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

Explanation:

  • The prompt is shown at least once, even if the user provides invalid input initially.
  • The loop repeats until the user enters a number greater than 10.

When to Use a do-while Loop

  • To create interactive menus.
  • For retry mechanisms where user input or external conditions might need validation.

The for Loop

The for loop is a powerful iteration tool, especially when the number of repetitions is known beforehand. It combines initialization, condition checking, and increment/decrement in a compact syntax.

Syntax:

for (initialization; condition; increment)
{
    // Code to execute
}
Enter fullscreen mode Exit fullscreen mode

Example: Countdown Timer

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

Explanation:

  • The loop initializes countdown at 5, decrements it after each iteration, and stops when it reaches 0.

Example: Multiplication Table

Nested loops are often used for tasks like generating multiplication tables:

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

Output:

1   2   3
2   4   6
3   6   9
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The outer loop controls the rows, while the inner loop handles the columns.

Controlling Loops with break and continue

C# provides two keywords to modify loop behavior dynamically:

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

Example: Using 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

Explanation: The loop terminates as soon as the number 7 is encountered.

Example: Using continue

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

Explanation: The loop skips even numbers and only processes odd ones.


Practical Example: Interactive Menu

Here’s how to combine a do-while loop with a switch statement to create an interactive menu:

string userChoice;

do
{
    Console.WriteLine("Choose an option:");
    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

Explanation:

  • The menu displays at least once.
  • The loop continues until the user selects the exit option (99).

Choosing Between Loops

Loop Type Best For
do-while When the code must run at least once (e.g., menus).
for When the number of iterations is known.
while When iterations depend on a condition upfront.

Common Pitfalls and Tips

  1. Infinite Loops: Always ensure your loop condition can eventually become false. For example, forgetting to increment a counter can cause a while loop to run forever.
  2. Off-by-One Errors: Double-check loop boundaries to avoid iterating one too few or one too many times.
  3. Avoid Over-Complexity: Keep loops simple and easy to read. For nested loops, consider breaking complex logic into separate methods.

Conclusion

Loops are essential tools for managing repetitive tasks in programming. In this article, we covered:

  • The do-while loop, which guarantees execution at least once.
  • The for loop, ideal for controlled iterations.
  • Using break and continue to manage loop flow effectively.

By mastering these structures, you’ll be able to write efficient, clean, and maintainable C# code. Start experimenting with these examples, and try implementing your own use cases to strengthen your understanding!

Conclusion

Loops are powerful tools that enable developers to handle repetitive tasks efficiently. In this article, we explored:

  • The do-while loop, which ensures the loop executes at least once.
  • The for loop, best for known iteration counts.
  • The break and continue keywords to control loop flow.

By mastering these concepts, you’ll enhance your ability to write efficient and maintainable C# code.


Challenge: Draw Shapes with * Using Loops

Test your understanding of loops by drawing different shapes using *:

Challenge 1: Right-Angled Triangle

Write a for loop to generate the following pattern:

*
**
***
****
*****
Enter fullscreen mode Exit fullscreen mode

Challenge 2: Inverted Triangle

Modify the loop to create an inverted triangle:

*****
****
***
**
*
Enter fullscreen mode Exit fullscreen mode

Challenge 3: Pyramid

Create a pyramid pattern using nested loops:

    *
   ***
  *****
 *******
*********
Enter fullscreen mode Exit fullscreen mode

Challenge 4: Diamond

Combine nested loops to draw a diamond shape:

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *
Enter fullscreen mode Exit fullscreen mode

Bonus Challenge: Hollow Shapes

Modify the loops to generate hollow shapes, such as a hollow diamond:

    *
   * *
  *   *
 *     *
*       *
 *     *
  *   *
   * *
    *
Enter fullscreen mode Exit fullscreen mode

By solving these challenges, you'll gain a deeper understanding of how to use loops effectively to manipulate output and build creative solutions.

💖 💪 🙅 🚩
moh_moh701
mohamed Tayel

Posted on September 25, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related