C# Part 4 : Control Flow Statements In C#

C# PART 4: CONTROL FLOW STATEMENTS IN C#


Please Subscribe Youtube| Like Facebook | Follow Twitter

Control Flow Statements In C#

In this article, we will provide a detailed overview of control flow statements in C# and provide examples of how they are used in C# programming.

Control flow statements are essential constructs in programming languages that allow for executing specific instructions based on certain conditions or iterating over a set of instructions repeatedly until a certain condition is met. In C#, there are several control flow statements, including if/else statements, switch statements, for loops, while loops, and do-while loops.

If-else statement

If-else statements are used to execute different code based on different conditions. Here is the syntax for an if-else statement:

if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}

In an if-else statement, the code inside the first set of curly braces is executed if the condition is true. If the condition is false, the code inside the second set of curly braces is executed.

In some cases, you may need to evaluate multiple conditions. In these cases, you can use the else if statement. Here is the syntax for multiple if-else statement:

if (condition1) {
  // code to be executed if condition1 is true
} elseif (condition2) {
  // code to be executed if condition2 is true
} else {
  // code to be executed if all conditions are false
}

The else if statement allows you to evaluate multiple conditions and execute different blocks of code based on the result of the evaluations

Here’s an example of if-else statement in C#

using System;

class Program
{
    static void Main(string[] args)
    {
        int a = 10, b = 20, c = 30;
        int largest;

        if (a > b && a > c)
        {
            largest = a;
        }
        else if (b > c)
        {
            largest = b;
        }
        else
        {
            largest = c;
        }

        Console.WriteLine("The largest number is: " + largest);
    }
}

Output

The largest number is: 30

Initially , it declares and initializes the variables a, b, and c.
Next, it declares the variable largest without initializing it.
Then, it uses if-else statements to check if a, b, or c is the largest number. If a is greater than both b and c, it sets largest equal to a. Otherwise, if b is greater than c, it sets largest equal to b. If neither of these conditions are true, it sets largest equal to c.
Finally, it prints the result using Console.WriteLine statement.
When the program is executed, it outputs the largest number among the three, which in this case is 30.

Switch statement

The switch statement is used to execute a block of code based on the value of a variable or expression. The syntax for the switch statement is as follows:

switch (expression) 
{
    case value1:
        // code to execute if expression is equal to value1
        break;
    case value2:
        // code to execute if expression is equal to value2
        break;
    ...
    default:
        // code to execute if expression does not match any of the cases
        break;
}

The switch statement evaluates the expression and compares it to each of the values specified in the case statements. If a match is found, the code inside the corresponding case block is executed. If no match is found, the code inside the default block (if present) is executed.

Here’s an example program that uses a switch statement to print the name of a day based on its number:

using System;

class Program
{
    static void Main(string[] args)
    {
        int day = 3;
        string dayName;

        switch (day)
        {
            case 1:
                dayName = "Monday";
                break;
            case 2:
                dayName = "Tuesday";
                break;
            case 3:
                dayName = "Wednesday";
                break;
            case 4:
                dayName = "Thursday";
                break;
            case 5:
                dayName = "Friday";
                break;
            case 6:
                dayName = "Saturday";
                break;
            case 7:
                dayName = "Sunday";
                break;
            default:
                dayName = "Invalid day";
                break;
        }

        Console.WriteLine("The day is: " + dayName);
    }
}

Output

The day is: Wednesday

Program initializes an integer variable day with a value of 3, and declares a string variable dayName without initializing it.

The switch statement checks the value of day against the cases of 1, 2, 3, 4, 5, 6, and 7. If day matches any of the cases, the corresponding dayName is assigned to the variable dayName. If day does not match any of the cases, the default case is executed, and dayName is assigned the value “Invalid day”.

Finally, it prints the result using Console.WriteLine statement, which outputs “The day is: Wednesday” because day is initialized to 3, which corresponds to the case for “Wednesday”.

For loop

The for loop is used to iterate over a block of code a fixed number of times. The syntax for the for loop is as follows:

for (initialization; condition; increment/decrement) 
{
    // code to execute
}

The initialization step is used to set the initial value of the loop variable. The condition step is used to determine whether the loop should continue executing or not. The increment/decrement step is used to modify the loop variable after each iteration.

Here’s an example program that uses a for loop to print the first 10 even numbers:

using System;

class Program
{
    static void Main(string[] args)
    {
        for (int i = 2; i <= 20; i += 2)
        {
            Console.Write(i + " ");
        }
    }
}

Output

2 4 6 8 10 12 14 16 18 20

The for loop initializes an integer variable i with a value of 2, checks whether i is less than or equal to 20, and increments i by 2 after each iteration.

Within the loop, the program prints the value of i followed by a space, using the Console.Write() statement.

When the program is executed, it outputs the even numbers between 2 and 20, separated by a space: “2 4 6 8 10 12 14 16 18 20”.

Break and Continue Statements Inside a For Loop

break and continue statements inside a for loop allow you to control the flow of the loop by terminating the loop early or skipping a particular iteration.

The break statement allows you to exit the loop prematurely when a certain condition is met. Once the break statement is encountered, the loop is terminated and control is passed to the next statement after the loop.

On the other hand, the continue statement allows you to skip the remaining statements in a particular iteration of the loop and move on to the next iteration. When continue is encountered, control jumps back to the beginning of the loop, and the loop continues with the next iteration.

Here is an example of using break and continue statements inside a for loop in C#:

for (int i = 1; i <= 10; i++)
{
    if (i == 3)
    {
        continue;
    }
    else if (i == 5)
    {
        break;
    }
    Console.WriteLine(i);
}

Output

1
2
4

In this example, the loop iterates from 1 to 10. When i is 3, the continue statement is encountered, so the remaining statements in that iteration are skipped and the loop proceeds to the next iteration. When i is 5, the break statement is encountered and the loop is terminated early. So only the values 1, 2, and 4 are printed to the console.

While loop

The while loop is used to iterate over a block of code while a condition is true. The syntax for the while loop is as follows:

while (condition) 
{
    // code to execute
}

The code inside the loop will continue executing as long as the condition is true.

Here’s an example program that uses a while loop to print the first 10 odd numbers:

using System;

class Program
{
    static void Main(string[] args)
    {
        int i = 1;
        while (i <= 19)
        {
            Console.Write(i + " ");
            i += 2;
        }
    }
}

Output

1 3 5 7 9 11 13 15 17 19

The program initializes an integer variable i to 1.

Then, it enters a while loop that will continue as long as i is less than or equal to 19.

Within each iteration of the loop, the program prints the value of i, followed by a space, using the Console.Write() statement.

After printing the value of i, the program increments i by 2 using the expression i += 2, which ensures that only odd numbers are printed.

When the loop finishes executing, the program has printed the odd numbers between 1 and 19 to the console, separated by a space: “1 3 5 7 9 11 13 15 17 19”.

Do-while loop

The do-while loop is similar to the while loop, except that the condition is checked at the end of the loop instead of the beginning. This means that the code inside the loop will always execute at least once. The syntax for the do-while loop is as follows:

do 
{
    // code to execute
} while (condition);

Here’s an example program that uses a do-while loop to prompt the user for a password until the correct password is entered:

using System;

class Program
{
    static void Main(string[] args)
    {
        string password;
        do
        {
            Console.WriteLine("Enter your password:");
            password = Console.ReadLine();
        } while (password != "password");

        Console.WriteLine("Correct password entered!");
    }
}

Output

Enter your password:
1234
Enter your password:

The program first declares a string variable password and initializes it to an empty string. Then, it enters a do-while loop that will execute at least once.

Within the loop, the program prompts the user to enter a password using the Console.WriteLine() statement. The user’s input is read using the Console.ReadLine() statement and stored in the password variable.

The program checks whether the entered password matches the correct password, which is set to “password” in this example. If the entered password is incorrect, the loop repeats and the program prompts the user to enter a password again. The loop continues until the correct password is entered.

Once the correct password is entered, the program exits the do-while loop and prints a message using the Console.WriteLine() statement to indicate that the correct password has been entered.

Conclusion

In conclusion, control flow statements are an essential part of any programming language, including C#. They allow programmers to control the flow of execution of their programs based on different conditions and criteria. In this article, we covered five common control flow statements in C#: if-else, switch, for loop, while loop, and do-while loop. We explained the syntax and provided detailed examples of how to use each of them. By mastering these statements, you can write more efficient and effective code in C# and other programming languages.

C# Beginner Tutorial Series

Please Subscribe Youtube| Like Facebook | Follow Twitter


Leave a Reply

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