Control Structures: If-Else and Switch Statements

Control structures, such as if-else statements and switch cases, are fundamental in programming. They enable developers to make decisions within their code, directing the flow of execution based on specific conditions. This makes programs more dynamic and responsive. In this reading, we’ll explore the purpose, syntax, and practical uses of these structures to help you apply them effectively in your code.

If-Else Statements: Making Binary Decisions

An if-else statement evaluates a condition and executes one block of code if the condition is true, and another if it is false. This structure is ideal for scenarios where a program must choose between two possible outcomes.

Example: Age Verification

Imagine a program that checks whether a user is old enough to access a restricted website section. If the user is 18 or older, access is granted; otherwise, it’s denied.

Syntax in C#

if (condition) 
{
    // Executes if condition is true
} 
else 
{
    // Executes if condition is false
}

Example:

int age = 18;
if (age >= 18) 
{
    Console.WriteLine("Access granted.");
} 
else 
{
    Console.WriteLine("Access denied.");
}

Here, the program checks the age variable and prints the appropriate message based on the condition.

Switch Cases: Handling Multiple Conditions

While if-else works well for binary choices, switch cases provide a cleaner way to handle multiple possible values. A switch statement evaluates a variable and executes different code blocks depending on its value.

Example: Vending Machine Selection

A vending machine program could use a switch case to dispense different drinks based on the user’s selection.

Syntax in C#

switch (variable) 
{
    case value1:
        // Code for value1
        break;
    case value2:
        // Code for value2
        break;
    default:
        // Code if no cases match
        break;
}

Example:

string button = "Water";
switch (button) 
{
    case "Water":
        Console.WriteLine("Dispensing water");
        break;
    case "Soda":
        Console.WriteLine("Dispensing soda");
        break;
    default:
        Console.WriteLine("Invalid option");
        break;
}

Here, the program checks the button variable and executes the corresponding case. The default case runs if no matches are found.

Applying If-Else and Switch in Problem-Solving

1. Using If-Else for Simple Conditions

Example: Checking if a student passed an exam (passing grade ≥ 50).

int grade = 55;
if (grade >= 50) 
{
    Console.WriteLine("Passed");
} 
else 
{
    Console.WriteLine("Failed");
}

2. Using Switch for Multiple Conditions

Example: Assigning letter grades based on a student’s score.

int score = 85;
switch (score / 10) 
{
    case 10:
    case 9:
        Console.WriteLine("A");
        break;
    case 8:
        Console.WriteLine("B");
        break;
    case 7:
        Console.WriteLine("C");
        break;
    default:
        Console.WriteLine("F");
        break;
}

This approach efficiently maps score ranges to letter grades.

Advanced Control Structures

1. Nested If-Else Statements

Nested if-else statements allow handling complex decisions by placing one if-else inside another. This is useful when actions depend on multiple conditions.

Example: Store Discounts
A store may offer discounts based on purchase amount and membership status:

if (totalAmount > 100) 
{
    if (isMember) 
    {
        applyMemberDiscount();
    } 
    else 
    {
        applyRegularDiscount();
    }
} 
else 
{
    applyNoDiscount();
}

⚠ Caution: Overusing nested if-else can lead to “spaghetti code.” Break down complex logic into functions for better readability.

2. Chained If-Else Statements

Chained if-else checks conditions sequentially, making it ideal for mutually exclusive cases.

Example: Shipping Cost Calculation

if (location == "local") 
{
    applyLocalShipping();
} 
else if (location == "domestic") 
{
    applyDomesticShipping();
} 
else if (location == "international") 
{
    applyInternationalShipping();
} 
else 
{
    applyStandardShipping();
}

3. Complex Switch Statements

Switch statements can be enhanced with combined cases and pattern matching for more flexibility.

Example: Combined Cases

switch (day) 
{
    case "Monday":
    case "Wednesday":
        Console.WriteLine("Eat cereal");
        break;
    case "Friday":
        Console.WriteLine("Pizza day!");
        break;
    default:
        Console.WriteLine("No special meal today.");
        break;
}

Example: Pattern Matching

switch (musicGenre) 
{
    case string g when g.Contains("jazz"):
        Console.WriteLine("Playing jazz playlist");
        break;
    case string g when g.Contains("rock"):
        Console.WriteLine("Playing rock playlist");
        break;
    default:
        Console.WriteLine("No matching playlist");
        break;
}

Real-World Applications

1. Inventory Management

Use if-else to decide whether to restock:

if (stockLevel < reorderThreshold) 
{    
    reorderProduct();
} 
else 
{
    maintainCurrentStock();
}

2. Order Processing

Use switch to determine shipping methods:

switch (location) 
{
    case "local": 
        applyLocalShipping(); 
        break;
    case "domestic": 
        applyDomesticShipping(); 
        break;
    case "international": 
        applyInternationalShipping(); 
        break;
    default:
        applyStandardShipping();
        break;
}

3. Discount Application

Use nested if-else for tiered discounts:

if (totalAmount > 100) 
{
    if (isMember) 
    {
        applyMemberDiscount();
    } 
    else 
    {
        applyRegularDiscount();
    }
} 
else 
{
    applyNoDiscount();
}

Best Practices for Clean Code

✔ Avoid deep nesting – Refactor into functions.
✔ Use switch for multiple fixed values – Improves readability.
✔ Comment complex conditions – Helps maintainability.
✔ Prefer pattern matching – Simplifies dynamic checks.

Conclusion

Control structures like if-else and switch are essential for decision-making in programming.

  • If-else is best for binary and sequential conditions.
  • Switch excels in handling multiple fixed values.
  • Nested and chained conditions manage complex logic but should be used judiciously.

By mastering these structures—including advanced techniques like pattern matching—you can write efficient, readable, and maintainable code for real-world applications.

Previous Article

Microsoft Copilot: The AI-Powered Coding Assistant Revolutionizing Development

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨