Mastering Loops in C# (Part 1 of 2)

Olayiwola Osho
8 min readFeb 22, 2024

--

Introduction

Welcome to the world of loops! In programming, loops are essential tools that help you efficiently handle repetitive tasks. Whether you’re just starting or have some experience, knowing how to use loops is crucial for writing code that is both effective and easy to manage.

Why Use Loops?

Loops are important in programming because they allow you to automate tasks that need to be repeated. Instead of writing the same set of instructions multiple times, you can use loops to execute them over and over until a specific condition is met. This not only makes your code cleaner but also saves you from unnecessary repetition, making it simpler to work with and update.

Part 1: The Basics of Loops in C#

The While Loop — Simple Repetition

Syntax and Structure:

In C#, the while loop is a basic tool for repeating a block of code as long as a condition remains true.

Structure

while (condition) {
// Statements to execute repeatedly
}
  • while: Keyword that introduces the loop.
  • condition: A Boolean expression that determines if the loop continues.
  • statements: The block of code to be executed repeatedly as long as the condition is true.

Understanding the Loop Condition:

The condition is the heart of the while loop. It’s a Boolean expression that evaluates to either true or false. As long as the condition remains true, the loop continues to execute the statements within its block. Once the condition becomes false, the loop terminates.

Examples: Counting Up, Down, and By Factors:

Here are some examples of using the while loop for different counting scenarios:

a) Counting Up:

int i = 1;
while (i <= 5) {
Console.WriteLine(i);
i++; // Increment i by 1 after each iteration
}

This loop will print numbers from 1 to 5 (inclusive).

b) Counting Down:

int i = 10;
while (i >= 1) {
Console.WriteLine(i);
i — ; // Decrement i by 1 after each iteration
}

This loop will print numbers from 10 to 1 (inclusive).

c) Counting by Factors of 3:

int i = 3;
while (i <= 15) {
Console.WriteLine(i);
i += 3; // Increment i by 3 after each iteration
}

This loop will print multiples of 3 from 3 to 15 (inclusive).

Debugging and Avoiding Infinite Loops:

One of the biggest challenges with while loops is the risk of creating infinite loops. This happens when the condition never becomes false, causing the loop to run continuously. To avoid this, make sure your condition always has the potential to change to false within the loop body.

Here are some tips:

  • Use incrementing or decrementing variables within the loop to change the condition.
  • Check for user input or external factors that can affect the condition.
  • Always test your loops for different scenarios to ensure they terminate properly.

By understanding the syntax, condition, and potential pitfalls of the while loop, you can utilize it effectively for simple repetition tasks in your C# programs.

Code Challenge

Sum of Numbers:

  • Write a program that uses a while loop to take input from the user until they enter 0. Calculate the sum of all the entered numbers and display it to the console.
  • Modify the program to only consider positive numbers for the sum.

Guessing Game:

  • Write a program that uses a while loop to generate a random number between 1 and 100. The user needs to guess the number. After each guess,display whether the guess is too high, too low, or correct. Continue the loop until the user guesses correctly.

Prime Number Checker:

  • Write a program that uses a while loop to check if a given number (entered by the user) is prime. A prime number is only divisible by 1 and itself.
  • Modify the program to print all prime numbers between 1 and a given number (entered by the user).

The do-while Loop — Checking First, Running Later

While the while loop excels at repeating code as long as a condition is true, sometimes you need to ensure the loop body executes at least once, regardless of the initial condition. That’s where the do-while loop comes in! Buckle up as we explore this interesting variation.

Syntax and Structure:

The do-while loop follows a slightly different structure:

do {
// Loop body: statements to be executed at least once
} while (condition);

Here’s how it works:

  1. The do keyword: marks the beginning of the loop body.
  2. The loop body: similar to the while loop, contains the statements you want to repeat.
  3. The while keyword: followed by the condition, determines whether the loop repeats. This check happens after the first execution of the body.

Comparing to while: The Key Difference:

The crucial difference between while and do-while lies in the condition check. In while, the condition is checked before the body, so the body might not execute at all if the condition is initially false. In do-while, the body executes at least once, and then the condition is checked for future repetitions.

Examples: Reading User Input, Guessing Games:

Let’s see how this difference plays out in practice:

Reading User Input:

string input;
do {
Console.WriteLine(“Enter your name: “);
input = Console.ReadLine();
} while (string.IsNullOrEmpty(input));

This code ensures the user enters a name at least once. Even if the user initially presses Enter without typing anything (string.IsNullOrEmpty(input)), the prompt repeats because the body runs before the check.

Guessing Games:

int secretNumber = 42;
int guess;
do {
Console.WriteLine(“Guess the secret number: “);
guess = int.Parse(Console.ReadLine());
} while (guess != secretNumber);

In this guessing game, the player gets at least one attempt, regardless of their initial guess. The loop continues until the guess matches the secret number.

Avoiding Infinite Loops in do-while:

Just like with while loops, ensuring the loop eventually terminates is crucial. Make sure your condition within the do-while loop changes in a way that eventually leads to it becoming false, preventing infinite execution.

Summary:

The do-while loop provides a unique way to guarantee at least one execution of the loop body, even if the initial condition is false. Understanding this key difference compared to the while loop opens up various possibilities for crafting logic that requires guaranteed initial execution.

Next, we’ll delve into the powerful for loop, which offers fine-grained control over repetitive tasks. Stay tuned!

Code Challenge

  1. Write a program that uses a do-while loop to print the numbers from 1 to 10, inclusive. Modify the program to only print even numbers between 2 and 20.
  2. Write a program that reads user input until the user enters a specific keyword (e.g., “quit”). Each time the user enters input, print it back to them in uppercase.
  3. Write a program that asks the user for a positive number. Use a do-whileloop to keep asking until the user enters a valid positive number.

Challenge: Create a program that simulates a simple dice-rolling game. Players take turns rolling a die (simulated with a random number generator) and adding the values to their score. The game continues until a player reaches a certain target score or rolls a specific number (e.g., 1) that resets their score. Use do-while loops to control the player turns and the game flow.

The for Loop — Controlling Repetition with Precision

Get ready to unleash the power of the for loop! The for loop is like a precision instrument for controlling code repetition in C# programming. It provides a structured way to repeat a block of code a specific number of times, making it a favorite among C# programmers.

Syntax and Structure: Initialization, Condition, Increment:

The for loop packs a punch with three key components:

for (initialization; condition; increment) {
// Loop body: statements to be executed repeatedly
}

Let’s break it down:

  1. Initialization: This part happens once before the loop starts, often used to declare and initialize a loop counter variable.
  2. Condition: Similar to other loop types, this expression determines whether the loop continues. As long as it evaluates to true, the loop body executes.
  3. Increment (or decrement): This statement is executed after each iteration of the loop body, typically modifying the loop counter variable to move closer to the stopping condition.

Understanding Each Part of the for Loop:

Each element of the for loop plays a crucial role:

  • Initialization: This is where you set the stage for your loop. Commonly used for loop counters, it can also initialize other variables needed within the loop.
  • Condition: This acts as the gatekeeper, controlling how long the loop runs. By carefully crafting your condition, you can achieve precise control over the number of iterations.
  • Increment: This is the workhorse that keeps the loop moving forward (or backward if you use decrement). Each iteration, this statement updates the loop counter variable, bringing it closer to the point where the condition becomes false and the loop stops.

Examples: Counting in Ranges, Building Arrays:

Now, let’s see how the for loop shines in action:

Counting in Ranges:

for (int i = 1; i <= 10; i++) {
Console.WriteLine(i);
}

This code counts from 1 to 10. In the initialization part, i is set to 1. The condition checks if i is less than or equal to 10. After each iteration, i is incremented by 1, eventually reaching the stopping point.

Building Arrays:

int[] numbers = new int[5];
for (int i = 0; i < numbers.Length; i++) {
numbers[i] = i + 1;
}

This code creates an array of numbers from 1 to 5. The loop iterates 5 times, using the counter i to access each element of the array and assign its value based on the current i.

Using Nested Loops for Complex Tasks:

The for loop’s power doesn’t stop there! It can be nested within other loops, creating intricate patterns and structures. This allows you to tackle complex tasks by breaking them down into smaller, manageable loops:

for (int i = 0; i < 3; i++) {
for (int j = 0; j < 5; j++) {
Console.Write(“*”);
}
Console.WriteLine();
}

This code prints a 3x5 rectangle of asterisks using two nested loops. The outer loop controls the rows, and the inner loop controls the columns.

Summary:

The for loop provides a powerful and flexible way to control repetitive tasks in your C# programs. By understanding its syntax and structure, you can create precise and efficient loops that meet your specific needs. Next, we’ll explore more advanced loop techniques, including breaking and continuing within loops, to further enhance your C# programming skills. Stay tuned!

Code Challenge:

Write a for loop that prints the numbers from 1 to 10. Modify the loop to:

  • Print only even numbers between 2 and 20.
  • Start at 5 and count down to 1.
  • Print the squares of numbers from 1 to 6.

Simple Array Manipulation:

  • Create an array of 5 numbers and print each element using a for loop.
  • Write a program that calculates the sum of all elements in an array of numbers.
  • Write a program that finds the maximum and minimum values in an array of numbers.

Pattern Printing:

  • Write a program that prints the following pattern using for loops:
*
**
***
****
*****
  • Write a program that prints a multiplication table for a given number using nested for loops.

Next Topic:

Ready to continue your exploration of C# programming? The next topic to dive into is Mastering Loops Part 2. Learn more about Streamlining your code with these powerful control structures, enabling efficient iteration and processing of arrays and other collections in your programs.

--

--