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);
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);
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
}
Example 1: Countdown Timer
for (int countdown = 5; countdown > 0; countdown--)
{
Console.WriteLine("Countdown: " + countdown);
}
Console.WriteLine("Liftoff!");
Explanation:
- The loop starts with
countdown = 5
, decrements the value, and stops when the condition (countdown > 0
) isfalse
.
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();
}
Output:
1 2 3
2 4 6
3 6 9
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
}
Example 1: Iterating Through a List
List<string> fruits = new List<string> { "Apple", "Banana", "Cherry" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Output:
Apple
Banana
Cherry
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}");
}
Output:
Laptop: 5
Smartphone: 10
Tablet: 3
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);
}
Output:
1
2
3
4
5
6
Found 7, stopping the loop!
Example: Using continue
for (int number = 1; number <= 10; number++)
{
if (number % 2 == 0)
{
continue; // Skip even numbers
}
Console.WriteLine(number);
}
Output:
1
3
5
7
9
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:
*
**
***
****
*****
Challenge 2: Inverted Triangle
Modify the loop to create an inverted triangle:
*****
****
***
**
*
Challenge 3: Pyramid
Create a pyramid pattern using nested loops:
*
***
*****
*******
*********
Challenge 4: Diamond
Combine nested loops to draw a diamond shape:
*
***
*****
*******
*********
*******
*****
***
*
Bonus Challenge: Hollow Shapes
Modify the loops to generate hollow shapes, such as a hollow diamond:
*
* *
* *
* *
* *
* *
* *
* *
*
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)