DEV Community

Cover image for Control Structures in C#: Loops and Conditionals
Odumosu Matthew
Odumosu Matthew

Posted on

Control Structures in C#: Loops and Conditionals

In programming, there will be times when you want your program to make decisions or repeat certain actions. That's where control structures come in. Control structures allow your program to follow different paths based on conditions (decision-making) or repeat tasks (looping). In this article, I'll dive into two major control structures in C#: conditionals (if, else, switch) and loops (for, while, foreach).

I'll explain them in simple terms with real-world examples and show how they are used in code.

1. Conditionals: Making Decisions in Code
Imagine you’re going to a movie theater. Your decision to buy a ticket depends on certain conditions:

  • If the movie is a comedy, you buy a ticket.

  • If it’s a horror movie, you might skip it.

In programming, you use conditional statements like if, else if, and else to make similar decisions. Here's how it works in C#.

a. if and else Statements
The if statement allows your program to make decisions based on a condition. Think of it as asking a question: "If this is true, do this; otherwise, do something else."

Example 1: Deciding What to Wear Based on the Weather

Imagine you're deciding what to wear based on the temperature:

int temperature = 25;

if (temperature > 30)
{
    Console.WriteLine("It's hot outside. Wear shorts.");
}
else
{
    Console.WriteLine("It's not too hot. Wear regular clothes.");
}

Enter fullscreen mode Exit fullscreen mode
  • If the temperature is greater than 30 degrees, the program prints "It's hot outside. Wear shorts."

  • If the temperature is 30 or below, it prints "It's not too hot. Wear regular clothes."

Breaking It Down:

  • if (temperature > 30): The program checks if the temperature is higher than 30.

  • else: This is the fallback if the if condition is false. It means, "If the temperature is not greater than 30, do this instead."

b. else if: Adding More Conditions
Sometimes, you have more than one condition to check. For instance, you might want to wear different clothes depending on whether it's cold, warm, or hot. In this case, you can use else if to handle multiple conditions.

Example 2: Dressing for Different Weather Conditions

int temperature = 10;

if (temperature > 30)
{
    Console.WriteLine("It's hot outside. Wear shorts.");
}
else if (temperature > 20)
{
    Console.WriteLine("It's warm. Wear light clothes.");
}
else
{
    Console.WriteLine("It's cold. Wear a jacket.");
}

Enter fullscreen mode Exit fullscreen mode
  • If the temperature is above 30, it suggests wearing shorts.

  • If the temperature is between 21 and 30, it suggests light clothes.

  • If the temperature is 20 or below, it suggests wearing a jacket.

c. switch Statement

The switch statement is another way to handle multiple conditions, especially when you have many possible values to compare. It works like a menu with multiple choices.

Example 3: Choosing a Meal Based on the Day

Let’s say you have a meal plan that changes based on the day of the week. Here’s how you can use a switch statement to decide what meal you’re having:

string dayOfWeek = "Monday";

switch (dayOfWeek)
{
    case "Monday":
        Console.WriteLine("Today's meal: Pasta");
        break;
    case "Tuesday":
        Console.WriteLine("Today's meal: Tacos");
        break;
    case "Wednesday":
        Console.WriteLine("Today's meal: Pizza");
        break;
    default:
        Console.WriteLine("Meal not available for this day.");
        break;
}

Enter fullscreen mode Exit fullscreen mode
  • If it’s Monday, the program prints "Today's meal: Pasta."

  • If it’s Tuesday, it prints "Today's meal: Tacos."

  • If it’s any other day not listed (using the default case), it prints "Meal not available for this day."

Breaking It Down:

  • switch (dayOfWeek): The switch statement checks the value of dayOfWeek.

  • case "Monday": If the day is "Monday," it prints the meal.

  • break: This stops the program from continuing to check other cases once it finds a match.

  • default: If none of the specified cases match, the program will execute the default block.

2. Loops: Repeating Actions in Code

There are situations where you need to do the same task multiple times. For example, what if you want to greet every person at a party one by one? In programming, we use loops to repeat actions until a certain condition is met.

a. for Loop
A for loop is useful when you know exactly how many times you want to repeat an action.

Example 4: Counting from 1 to 5
Let’s say you want to print the numbers from 1 to 5:

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

Enter fullscreen mode Exit fullscreen mode

This loop will print:

1
2
3
4
5

Enter fullscreen mode Exit fullscreen mode

Breaking It Down:

  • int i = 1: This initializes the loop, starting the count at 1.

  • i <= 5: This is the condition. The loop will continue as long as i is less than or equal to 5.

  • i++: After each loop, the value of i increases by 1.

b. while Loop
A while loop repeats an action as long as a condition is true. It’s useful when you don’t know in advance how many times you’ll need to loop.

Example 5: Counting Down Until a Condition is Met
Imagine you’re counting down for a rocket launch. The countdown starts at 5 and continues until it reaches 0:

int countdown = 5;

while (countdown > 0)
{
    Console.WriteLine(countdown);
    countdown--;
}
Console.WriteLine("Liftoff!");

Enter fullscreen mode Exit fullscreen mode

This loop will print:

5
4
3
2
1
Liftoff!

Enter fullscreen mode Exit fullscreen mode

Breaking It Down:

  • while (countdown > 0): The loop will continue as long as the countdown is greater than 0.

  • countdown--: This decreases the value of countdown by 1 after each loop.

c. foreach Loop
A foreach loop is used to loop through a collection of items, like a list of names, and perform an action on each one. It’s perfect when you need to process each item in a collection without worrying about the index or position of the item.

Example 6: Greeting Party Guests
Let’s say you have a list of names, and you want to greet each person individually:

string[] guests = { "John", "Sarah", "Mike" };

foreach (string guest in guests)
{
    Console.WriteLine("Hello, " + guest + "!");
}

Enter fullscreen mode Exit fullscreen mode

This will print:

Hello, John!
Hello, Sarah!
Hello, Mike!

Enter fullscreen mode Exit fullscreen mode

Breaking It Down:

  • string[] guests: This is an array (a list) of names.

  • foreach (string guest in guests): The loop goes through each name in the guests list and stores it in the variable guest.

  • Console.WriteLine("Hello, " + guest + "!"): This prints a greeting for each guest.

d. do-while Loop

A do-while loop is similar to a while loop, but there’s a key difference: the do-while loop guarantees that the code inside the loop will run at least once, even if the condition is false at the start.

The do-while loop checks the condition after executing the loop block, whereas a while loop checks the condition before running the code inside.

Example 7: Asking for User Input Until It’s Correct

Let’s say you're creating a simple program where you need to ask a user for their age. You’ll keep asking until they enter a valid number:

int age;

do
{
    Console.WriteLine("Please enter your age:");
    age = Convert.ToInt32(Console.ReadLine());
} 
while (age <= 0);

Console.WriteLine("Thank you! You entered a valid age.");

Enter fullscreen mode Exit fullscreen mode

Breaking It Down:

  • do { ... } while (age <= 0);: The program first asks the user for their age. Then, it checks if the age entered is greater than 0. If not, it repeats the loop, asking for the age again.

  • Convert.ToInt32(Console.ReadLine()): This reads the user input from the console and converts it to an integer.

  • The loop will keep running until the user enters a valid positive number.

This loop ensures that the question is asked at least once, even if the user starts by entering an invalid age like -5 or 0.

Wrapping Up: Loops and Conditionals

Understanding loops and conditionals is essential for controlling the flow of your C# programs. Whether it’s making decisions using if, else, or switch statements or repeating tasks using for, while, or foreach loops, these control structures help you write efficient and dynamic programs.

To summarize:

  • Conditionals help your program make decisions based on certain conditions.

  • Loops allow your program to repeat actions until a condition is met or until every item in a collection is processed.

As you continue to practice, you’ll see these control structures used in almost every C# program, helping you create smarter, more responsive applications.

LinkedIn Account : LinkedIn
Twitter Account: Twitter
Credit: Graphics sourced from LoginRadius

Top comments (2)

Collapse
 
bronlund profile image
Pål Brønlund

You forgot do-while :)

Collapse
 
iamcymentho profile image
Odumosu Matthew

Thank you for reading and for the feedback...It has now been included!