Control Statements in C#

Learn via video courses
Topics Covered

Overview

Control flow statements in C# are essential for directing the flow of program execution. They enable you to make decisions, repeat actions, and create structured and dynamic behavior. Selection statements such as 'if', 'else', and'switch' allow you to make conditional decisions. Iteration statements like 'for', 'while', 'do-while', and 'foreach' make repetition possible.Jump statements such as 'break,' 'continue,' and'return' allow you to deviate from the typical flow.

In essence, control flow statements in C# enable you to make choices, perform actions in loops, and structure your code's progression. These statements are vital for creating well-structured, interactive, and efficient programs in C#.

Example to Understand Control Flow Statements in C#

Control flow statements in C# dictate how a program progresses. They encompass decision-making, repetition, and altering execution paths. Selection statements like 'if', 'else', and 'switch' determine actions based on conditions. Iteration statements ('for', 'while', 'do-while', 'foreach') repeat actions. Jump statements ('break', 'continue', 'return') modify regular execution.

Output

Explanation: This example covers various control flow statements:

  • The if-else statement makes decisions based on the input number's sign.
  • The switch statement categorizes the number as even or odd.
  • The while loop counts down from 5 to 0.
  • The for loop counts up from 1 to 5.
  • The do-while loop repeatedly prints "Hello" 3 times.
  • The break statement ends the loop when i equals 8.
  • The continue statement skips multiples of 3 in the loop.

if...else Statement

The if...else statement in C# is a fundamental control flow construct used to make decisions in programming. It evaluates a specified condition and executes one of two code blocks based on whether the condition is true or false. The code block under the if keyword runs if the condition is true, while the else block executes if the condition is false.

Output

Explanation:

  • The program prompts the user to enter their age.
  • Console.ReadLine() reads the user's input as a string, which is then converted to an integer using int.Parse().
  • The if statement checks whether the age is greater than or equal to 18. If it is, the program prints "You are an adult." If not, it prints "You are a minor."

if...else if...else Statements

The if...else if...else statement in C# is a versatile control flow tool for making multi-level decisions. It evaluates conditions in sequence, executing the code block corresponding to the first true condition. If none match, the else block is executed. This construct allows for nuanced decision-making by providing a hierarchy of choices.

Output

Explanation:

  • The program prompts the user to enter their grade.
  • Console.ReadLine() reads the user's input as a string, which is then converted to an integer using int.Parse().
  • The if...else if...else statement checks the value of grade in a descending order:
  • If grade is greater than or equal to 90, it prints "Your grade is A."
    • If not, but grade is greater than or equal to 80, it prints "Your grade is B."
    • This pattern continues with decreasing thresholds until the else block, which prints "Your grade is F."

switch Statement

The switch statement provides a way to execute different blocks of code based on the value of a variable or expression.

These control flow and decision-making structures allow you to create dynamic and responsive programs that make decisions based on input and conditions. Choose the appropriate structure based on your program's logic and requirements.

Let's an example that uses a switch statement in C#:

Output

Explanation:

  • User is prompted to input a number representing a day.
  • The entered string is converted to an integer using int.Parse() and stored in the dayNumber variable.
  • A switch statement is used to check the value of dayNumber and determine the corresponding day name.
  • Each case represents a different value of dayNumber, and the appropriate dayName is assigned.
  • The break statement is used to exit the switch statement once a match is found.
  • If none of the case conditions match the value of dayNumber, the default case is executed.
  • The final line uses string interpolation to display the determined dayName.

goto Statement

The goto statement in C# directs program flow to a labeled statement within the same method. However, it's discouraged due to potential code complexity and difficulty in maintenance. While it can be used for looping and jumps, modern practices advise using structured control flow constructs like if, while, and for for clearer and maintainable code.

Output

Explanation:

  • The program initializes an integer variable count with the value 0.
  • The start: label is used to mark a point in the code where the goto statement will jump to.
  • Inside the loop, the current value of count is printed using Console.WriteLine.
  • The if statement checks whether count is less than 5. If it is, the program uses the goto statement to jump back to the start label.
  • This loop continues until count is no longer less than 5.
  • Once the loop ends, the program prints "Loop ended."

ForEach Statement

The foreach statement in C# simplifies iterating over elements in a collection. It automatically handles the iteration process, eliminating the need for index management. With a clean syntax, it sequentially processes each element of the collection, executing the specified code block.

Output

Explanation:

  • A List<int> named numbers is created and initialized with five integer values: 1, 2, 3, 4, and 5.
  • The program displays a message indicating that it will use the foreach loop to show the elements of the list.
  • The foreach loop is used to iterate through each element in the numbers list.
  • For each iteration, the current element's value is stored in the num variable.
  • Inside the loop, the program displays a message, including the current element's value using string concatenation.
  • The loop continues until all elements in the numbers list have been processed.

Break Statement

The break statement in C# is a control flow command used within loops (like for, while, do-while) and switch statements. When encountered, it immediately terminates the innermost loop or exits the switch block, transferring control to the next statement after the loop or switch. This aids in premature loop termination or case handling discontinuation, enhancing code efficiency by avoiding unnecessary iterations or checks in certain situations.

Output

Explanation:

  • The program uses a for loop to count from 1 to 10.
  • If i becomes equal to 6 within the loop, the if statement is true, and the break statement is executed.
  • The break statement terminates the loop immediately, preventing further iterations.
  • The program then prints "Loop ended."

Continue Statement

The continue statement in C# is a control flow command used within loops (like for, while, do-while) to skip the current iteration and move to the next iteration of the loop. When encountered, it immediately jumps to the next iteration, bypassing any remaining code within the current iteration's loop body.

Output

Explanation:

  • The program uses a for loop to iterate through numbers 1 to 10.
  • The if statement checks whether the current number i is even (divisible by 2).
  • If i is even, the continue statement is executed, which immediately skips the rest of the current iteration and moves to the next iteration.
  • If i is odd, the program prints "Processing odd number: " followed by the current value of i.
  • After the loop completes, the program prints "Loop ended."

Conclusion

  • Control flow statements are vital for directing program execution.
  • They include decision-making (if, else, switch), looping (for, while, do-while, foreach), and altering paths (break, continue).
  • if...else enables branching based on conditions.
  • switch simplifies multi-choice scenarios.
  • Loops allow repeating actions efficiently.
  • break exits loops prematurely.
  • continue skips the current loop iteration.
  • Proper use enhances code structure and efficiency.