Control Statements
C# Control Statements
Control statements in C# determine the flow of execution in a program based on conditions or loops. They allow decision-making, branching, and iteration.
Types of Control Statements
1. Conditional Statements
Used to execute specific code blocks based on a condition.
Statement
Description
Example
if
Executes if the condition is true.
if (x > 10) { Console.WriteLine("Yes"); }
else
Executes if the if condition is false.
else { Console.WriteLine("No"); }
else if
Tests another condition if previous if is false.
else if (x == 5) { ... }
switch
Selects one case to execute.
switch (choice) { case 1: ... break; }
Example:
int x = 10;
if (x > 15) {
Console.WriteLine("Greater than 15");
} else if (x == 10) {
Console.WriteLine("Equal to 10"); // Output: Equal to 10
} else {
Console.WriteLine("Less than 10");
}2. Looping Statements
Used to execute a block of code multiple times.
Statement
Description
Example
for
Loops a set number of times.
for (int i = 0; i < 5; i++) { ... }
while
Loops while the condition is true.
while (x < 10) { ... }
do-while
Executes first, then checks the condition.
do { ... } while (x < 10);
foreach
Iterates over a collection.
foreach (var item in list) { ... }
Example:
3. Jump Statements
Alter the normal flow of execution.
Statement
Description
Example
break
Exits a loop or switch statement.
if (i == 5) break;
continue
Skips the current iteration and continues.
if (i % 2 == 0) continue;
return
Exits the method and optionally returns a value.
return x;
goto
Transfers control to a labeled statement.
goto Label; Label: ...;
Example:
4. Exception Handling Statements
Handle errors during runtime.
Statement
Description
Example
try
Encapsulates code that may throw an exception.
try { int x = 10 / 0; }
catch
Handles exceptions thrown by try.
catch (Exception ex) { ... }
finally
Executes code regardless of exceptions.
finally { Console.WriteLine("End"); }
Example:
5. Selection Statements
Redirect execution based on conditions.
Statement
Description
Example
if-else
Executes code based on a true/false condition.
if (x > 10) { ... } else { ... }
switch
Executes one of many possible cases.
switch (value) { case 1: ... }
Example:
Summary
Conditional Statements: Control execution flow (
if,else,switch).Looping Statements: Repeat actions (
for,while,foreach).Jump Statements: Change flow (
break,continue,return).Exception Handling: Handle runtime errors (
try,catch,finally).Selection Statements: Branching based on multiple conditions.
Control statements are crucial for managing the logical flow of a program, enabling it to handle conditions, repeat tasks, and manage errors effectively.