Control Flow in C#: if, switch, Loops, break & continue

1. Control Flow in C#

Q: What is control flow in C#?

Control flow determines the order in which a program's statements are executed. C# provides constructs like conditional statements (if, else, switch), loops (for, while, do-while), and jump statements (break, continue, goto) to control execution based on conditions or iterations.

2. if, else, and switch Statements

Q: What are if, else, and else if statements in C#?

The if statement executes a block of code if a condition is true. The else statement provides an alternative block if the condition is false. The else if allows testing multiple conditions sequentially.

Syntax:

if (condition) {
    // Code if true
} else if (anotherCondition) {
    // Code if anotherCondition is true
} else {
    // Code if all conditions are false
}

Q: What is the switch statement in C#?

The switch statement selects a code block to execute based on the value of an expression, matching it against case labels. It supports modern features like switch expressions (C# 8.0+).

Syntax:

switch (expression) {
    case value1:
        // Code
        break;
    case value2:
        // Code
        break;
    default:
        // Code if no case matches
        break;
}

Q: Can you give an example of if, else, and switch statements in C#?

using System;

namespace Conditionals
{
    class Program
    {
        static void Main(string[] args)
        {
            // If, else if, else
            int number = 15;
            if (number > 10)
            {
                Console.WriteLine($"{number} is greater than 10");
            }
            else if (number > 5)
            {
                Console.WriteLine($"{number} is greater than 5 but not 10");
            }
            else
            {
                Console.WriteLine($"{number} is 5 or less");
            }

            // Switch statement
            string day = "Monday";
            switch (day)
            {
                case "Monday":
                    Console.WriteLine("Start of the week!");
                    break;
                case "Friday":
                    Console.WriteLine("End of the work week!");
                    break;
                default:
                    Console.WriteLine("Some other day");
                    break;
            }

            // Switch expression (C# 8.0+)
            string message = day switch
            {
                "Monday" => "Start of the week!",
                "Friday" => "End of the work week!",
                _ => "Some other day"
            };
            Console.WriteLine(message);
        }
    }
}

Output:

15 is greater than 10
Start of the week!
Start of the week!

Q: How do if and switch differ from C/C++?

3. for, while, do-while & foreach Loops

Q: What is a for loop in C#?

A for loop executes a block of code a specified number of times, using an initializer, condition, and iterator.

Syntax:

for (initializer; condition; iterator) {
    // Code
}

Q: What is a while loop in C#?

A while loop executes a block of code as long as a condition is true, checked before each iteration.

Syntax:

while (condition) {
    // Code
}

Q: What is a do-while loop in C#?

A do-while loop executes a block of code at least once, then continues as long as a condition is true, checked after each iteration.

Syntax:

do {
    // Code
} while (condition);

Q: What is a foreach loop in C#?

A foreach loop iterates over elements in a collection (e.g., array, list) without needing an index.

Syntax:

foreach (type variable in collection) {
    // Code
}

Q: Can you give an example of loops in C#?

using System;

namespace Loops
{
    class Program
    {
        static void Main(string[] args)
        {
            // For loop
            Console.WriteLine("For loop:");
            for (int i = 1; i <= 3; i++)
            {
                Console.WriteLine($"Count: {i}");
            }

            // While loop
            Console.WriteLine("\nWhile loop:");
            int j = 1;
            while (j <= 3)
            {
                Console.WriteLine($"Count: {j}");
                j++;
            }

            // Do-while loop
            Console.WriteLine("\nDo-while loop:");
            int k = 1;
            do
            {
                Console.WriteLine($"Count: {k}");
                k++;
            } while (k <= 3);

            // Foreach loop
            Console.WriteLine("\nForeach loop:");
            string[] colors = { "Red", "Green", "Blue" };
            foreach (string color in colors)
            {
                Console.WriteLine($"Color: {color}");
            }
        }
    }
}

Output:

For loop:
Count: 1
Count: 2
Count: 3

While loop:
Count: 1
Count: 2
Count: 3

Do-while loop:
Count: 1
Count: 2
Count: 3

Foreach loop:
Color: Red
Color: Green
Color: Blue

Q: How do loops in C# differ from C/C++?

4. break, continue, and goto Statements

Q: What is the break statement in C#?

The break statement exits the innermost loop or switch statement immediately, transferring control to the next statement after the loop or switch.

Q: What is the continue statement in C#?

The continue statement skips the rest of the current loop iteration and proceeds to the next iteration.

Q: What is the goto statement in C#?

The goto statement transfers control to a labeled statement within the same function. It's rarely used due to potential for unreadable code but can be used in switch cases or for error handling.

Q: Can you give an example of break, continue, and goto in C#?

using System;

namespace JumpStatements
{
    class Program
    {
        static void Main(string[] args)
        {
            // Break in loop
            Console.WriteLine("Break example:");
            for (int i = 1; i <= 5; i++)
            {
                if (i == 4)
                {
                    break; // Exit loop when i is 4
                }
                Console.WriteLine($"Count: {i}");
            }

            // Continue in loop
            Console.WriteLine("\nContinue example:");
            for (int i = 1; i <= 5; i++)
            {
                if (i % 2 == 0)
                {
                    continue; // Skip even numbers
                }
                Console.WriteLine($"Odd number: {i}");
            }

            // Goto in switch
            Console.WriteLine("\nGoto example:");
            int choice = 2;
            switch (choice)
            {
                case 1:
                    Console.WriteLine("Choice 1");
                    break;
                case 2:
                    Console.WriteLine("Going to custom label");
                    goto CustomLabel;
                default:
                    Console.WriteLine("Default case");
                    break;
            }

        CustomLabel:
            Console.WriteLine("Reached custom label");
        }
    }
}

Output:

Break example:
Count: 1
Count: 2
Count: 3

Continue example:
Odd number: 1
Odd number: 3
Odd number: 5

Goto example:
Going to custom label
Reached custom label

Q: How do break, continue, and goto differ from C/C++?

5. Common Mistakes & Best Practices

Q: Common mistakes?

if/switch:

Loops:

Jump Statements:

Q: Best practices?

if/switch:

Loops:

Jump Statements:

General: