Mastering Loops In C# (Part 2 of 2)

Olayiwola Osho
7 min readFeb 22, 2024

--

Breaking Out of Loops — Escaping Early

So far, we’ve seen how loops keep repeating until their conditions become false. But what if you need to exit a loop before reaching the end? That’s where the break keyword comes in as your escape hatch!

The break Keyword and its Role:

Imagine you’re running a marathon (not literally, hopefully!). While the finish line is your ultimate goal, sometimes unforeseen circumstances might force you to stop early. The break keyword acts similarly in loops. It allows you to force an exit from the loop immediately, regardless of the current condition.

Here’s the syntax:

while (condition) {
// … loop body
if (someCondition) {
break;
}
// …
}

If the if condition inside the loop becomes true, the break statement executes, causing the loop to abandon all remaining iterations and jump to the code after the loop.

Controlling Early Exits with Conditions:

The true power of break lies in using it with conditions. This allows you to control when you want to escape the loop based on specific criteria:

Finding a Specific Value:

int[] numbers = { 1, 3, 5, 7, 2 };
for (int i = 0; i < numbers.Length; i++) {
if (numbers[i] == 2) {
break;
}
}
// This only loops until reaching and finding the value 2

This example searches for the number 2 in an array. As soon as it finds it, break kicks in, stopping the loop prematurely.

Validating User Input:

int age;
do {
Console.WriteLine(“Enter your age: “);
age = int.Parse(Console.ReadLine());
} while (age <= 0);
// This keeps asking for age until a valid value (positive) is entered

Here, the loop keeps asking for a user’s age until they enter a positive value. break ensures the loop exits once a valid age is provided.

Avoiding Misuses of break:

While break is a powerful tool, using it excessively or without proper planning can lead to messy and hard-to-understand code. Remember:

  • Use break sparingly and with clear conditions.
  • Avoid placing break statements within nested loops unless you completely intend to exit both loops.
  • Consider alternative approaches like refactoring conditions or using flags to avoid excessive break usage.

Code Challenge

Write a program that reads numbers from the user until they enter a negative number. Use a loop and the break statement to control the exit condition.

  1. Application: Design a program that simulates a guessing game. The user tries to guess a hidden number within a certain range. Use a loop and break to exit the game when the user guesses correctly or runs out of attempts.
  2. Problem-Solving: Implement a function that takes a list/array of numbers and returns a new list/array containing only the even numbers. Use a loop, break, and an if statement to achieve this.
  3. Debate: Should break statements always be used with conditions? When might it be acceptable to use them unconditionally?

Continuing Within Loops — Skipping and Jumping Ahead

In the exciting world of loops, sometimes you need to execute most iterations but gracefully skip specific ones. Enter the continue keyword, your loyal companion for selectively jumping ahead within a loop. Let’s explore its magic!

The continue Keyword and its Usage:

Similar to break, continue resides within your loop body. However, instead of causing a complete exit, it instructs the loop to immediately jump to the next iteration, skipping the remaining statements in the current iteration.

Here’s the syntax:

while (condition) {
// … loop body
if (someCondition) {
continue;
}
// …
}

If the if condition inside the loop evaluates to true, the continue statement kicks in, causing the loop to abandon the current iteration and proceed directly to the beginning of the next iteration.

Conditional Skips and Jumps for Specific Scenarios:

The true power of continue lies in its ability to skip iterations based on specific criteria:

Ignoring Even Numbers:

for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
Console.WriteLine(i); // Only prints odd numbers
}

This loop demonstrates how continue filters out even numbers, only printing odd numbers from 1 to 10.

Skipping Empty Strings:

string[] names = { “Alice”, “”, “Bob”, “”, “Charlie” };
for (int i = 0; i < names.Length; i++) {
if (string.IsNullOrEmpty(names[i])) {
continue;
}
Console.WriteLine(names[i]); // Prints only non-empty names
}

Here, the loop skips over empty strings in the names array to avoid printing them.

Balancing continue with Proper Loop Logic:

Overusing continue can create confusing and unpredictable code. Remember:

  • Use continue judiciously and with clear conditions. Avoid excessive skipping that might obscure the loop’s intent.
  • Think carefully about the overall logic. Ensure continue doesn’t lead to infinite loops or unintended skipping of essential behavior.
  • Consider alternative approaches like refactoring conditions or using flags to achieve the desired filtering or skipping without relying heavily on continue.

Beyond continue and break:

While continue and break offer powerful control, explore other loop constructs like foreach for iterating over collections efficiently.

Key Takeaways:

  • continue selectively skips iterations within a loop, allowing you to focus on specific elements or conditions.
  • Use continue strategically with clear conditions to avoid creating confusing or inefficient code.

By mastering continue and break, you’ll gain valuable tools for crafting well-structured and efficient loops that precisely control the flow of your C# programs.

Code Challenge

  1. code snippets
for (int i = 0; i < 5; i++)
{
if (i == 2)
{
Console.WriteLine(“Skipping 2”);
}
else
{
Console.WriteLine(i);
}
}

2. code snippets

for (int i = 0; i < 5; i++)
{
if (i == 2)
{
Console.WriteLine(“Skipping 2”);
continue;
}
Console.WriteLine(i);
}

Identify the continue keyword: From these two code snippets identify which ones use continue and explain its purpose.

  1. Vowel Removal: Write a program that takes a string as input from the user. Iterate through each character in the string using a for loop. Use continue to skip characters that are vowels (a, e, i, o, u). Print the remaining characters to create a new string without vowels.
  2. Password Checker: Write a program that checks the strength of a user-entered password. The password must meet certain criteria (e.g., minimum length, at least one uppercase letter, one lowercase letter, one number, one special character). Use a while loop to ask the user for a password until they enter one that meets all requirements. Use continue to skip to the next iteration if the password fails any criterion.

Loop Alternatives — Iterating without Explicit Loops

So far, we’ve explored the power of explicit loops like while, for, and do-while. But C# offers even more ways to iterate through data without manually writing loop constructs. Let’s delve into these alternatives and when to use them effectively.

Using foreach to Loop Through Collections:

The foreach statement provides a concise and readable way to iterate over elements in a collection, such as an array or list. It eliminates the need for explicit loop variables and index management, making your code cleaner and more focused.

Here’s an example:

string[] names = { “Alice”, “Bob”, “Charlie” };
foreach (string name in names) {
Console.WriteLine(name);
}

This code iterates through the names array, automatically assigning each element to the name variable on each iteration, and then prints it.

Understanding Functional Programming Approaches:

Functional programming concepts like LINQ (Language Integrated Query) offer powerful ways to declaratively express how you want to transform or iterate over data. Instead of writing explicit loops, you define operations on the entire collection, and the system handles the iteration efficiently.

Here’s an example using LINQ to select and print even numbers from an array:

int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (int number in evenNumbers) {
Console.WriteLine(number);
}

This code uses LINQ’s Where method to filter the numbers array for even numbers, creating a new collection of even numbers, and then iterates through that filtered collection.

Choosing the Right Tool for the Job:

When deciding which approach to use, consider these factors:

  • Simplicity: For straightforward iterations, foreach is often the easiest and most readable choice.
  • Collection type and operations: If you need complex filtering or transformations, LINQ might be more efficient and expressive.
  • Performance: For performance-critical scenarios, benchmark different approaches to find the most efficient one.

Additional Alternatives:

  • Recursion: While not commonly used for simple iterations, recursion can be a powerful tool for traversing tree-like data structures.
  • Yield return: This technique allows you to create custom iterators that can yield values on demand, useful for lazy evaluation or infinite sequences.

Code Challenge

  1. Define an array: Create an array of Product objects. You can define a Product class with properties for name, price (double), and quantity (int).Initialize the array with at least 5 different products.
  2. Print inventory: Write a foreach loop to iterate through the Product array and print each product’s name, price, and quantity.
  3. Find specific product: Ask the user to enter the name of a product they want to find. Write a foreach loop to search the array for the product and print its details if found. If not found, inform the user.
  4. Update quantity: Ask the user to enter the name of a product and the new quantity. Use a foreach loop to find the product and update its quantity. Print a message confirming the update or indicating if the product wasn’t found.
  5. Calculate total value: Write a foreach loop to iterate through the array and calculate the total value of your inventory by multiplying each product’s price by its quantity and summing all the values. Print the total value.

What’s Next?

Congratulations on completing “Mastering Loops in C# Part 2”! Now that you’ve mastered the fundamentals of loops in C#, it’s time to take your coding journey to the next level.

Next Topic

Ready to continue your exploration of C# programming? The next topic to dive into is Mastering Methods/Functions in C# . Enhance your code with this fundamental construct, enabling efficient and modular decomposition of tasks in your programs.

--

--