DEV Community

mohamed Tayel
mohamed Tayel

Posted on • Edited on

Mastering C# Fundamentals: Do-While and For Loops

Iteration statements, or loops, are powerful tools in programming. They allow developers to automate repetitive tasks, process collections, and create interactive systems efficiently. In this article, we’ll explore three essential loop structures in C#: do-while, for, and foreach, their unique use cases, and how to control loop behavior using break and continue. We’ll also include a detailed comparison between for and foreach loops.


1. The do-while Loop

The do-while loop is unique because it guarantees the execution of the code block at least once, even if the condition is initially false. This is particularly useful for tasks like user prompts or menus.

Syntax

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

Example: User Input Validation

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

Key Points:

  • The prompt is always displayed at least once.
  • The loop repeats until the user provides a valid input.

When to Use

  • Interactive menus.
  • Input validation tasks where execution must occur at least once.

2. The for Loop

The for loop is a powerful iteration tool, especially when the number of iterations is known. It combines initialization, condition checking, and increment/decrement in a single statement.

Syntax

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

Example 1: 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 starts with countdown = 5, decrements the value, and stops when the condition (countdown > 0) is false.

Example 2: Multiplication Table

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 iterates through the columns.

When to Use

  • Known iteration counts.
  • Index-based operations, such as accessing or modifying specific elements in a collection.

3. The foreach Loop

The foreach loop is a simpler and safer way to iterate over collections like arrays, lists, and dictionaries. It’s particularly useful for read-only iteration.

Syntax

foreach (var item in collection)
{
    // Code to execute for each item
}
Enter fullscreen mode Exit fullscreen mode

Example 1: Iterating Through a List

List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
Enter fullscreen mode Exit fullscreen mode

Output:

Apple
Banana
Cherry
Enter fullscreen mode Exit fullscreen mode

Example 2: Iterating Through a Dictionary

Dictionary<string, int> inventory = new Dictionary<string, int>
{
    { "Laptop", 5 },
    { "Smartphone", 10 },
    { "Tablet", 3 }
};

foreach (var item in inventory)
{
    Console.WriteLine($"{item.Key}: {item.Value}");
}
Enter fullscreen mode Exit fullscreen mode

Output:

Laptop: 5
Smartphone: 10
Tablet: 3
Enter fullscreen mode Exit fullscreen mode

When to Use

  • Traversing collections where modification is not required.
  • Iterating over key-value pairs in dictionaries.

4. Controlling Loops with break and continue

C# provides keywords to manage loop execution 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

Output:

1
2
3
4
5
6
Found 7, stopping the loop!
Enter fullscreen mode Exit fullscreen mode

Example: Using continue

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

Output:

1
3
5
7
9
Enter fullscreen mode Exit fullscreen mode

5. Comparison: for vs. foreach Loops

Feature for Loop foreach Loop
Syntax Combines initialization, condition, and increment in one statement. Simple and concise for iterating collections.
Ease of Use More verbose; requires managing counters manually. Simpler for straightforward iteration.
Index Access Provides direct access to the index of elements. Does not provide index access.
Read-Only Iteration Allows modification of elements. Best for read-only traversal of collections.
Reverse Iteration Easy to implement. Requires additional logic.
Error-Prone Prone to off-by-one errors in conditions. Safer; handles collection size automatically.
Performance Faster for arrays (direct index access). Slightly slower for non-array collections.
Modifying Collection Can handle additions or removals. Throws exceptions if the collection is modified.

When to Use

  • Use for when you need index-based access or plan to modify the collection.
  • Use foreach for simple, read-only iteration over collections.

6. Practical Challenges

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

Conclusion

In this article, we explored the three essential loops in C#: do-while, for, and foreach, and how to control them with break and continue. Each loop has its unique advantages:

  • Use do-while for tasks that must execute at least once.
  • Use for for precise, index-based iterations.
  • Use foreach for safer, simpler iteration over collections.

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

Top comments (0)