CONTROL
Control structures in C# are used to control the flow of execution in a program based on certain conditions or loops. They allow you to make decisions, repeat code blocks, and execute different paths of code. Here are the main control structures in C#:
- If Statement:
The if statement allows you to execute a block of code conditionally based on a specified condition.
Example:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
- Switch Statement:
The switch statement provides a way to execute different code blocks based on the value of a variable or an expression.
Example:
switch (variable)
{
case value1:
// Code to execute if variable matches value1
break;
case value2:
// Code to execute if variable matches value2
break;
default:
// Code to execute if variable doesn’t match any case
break;
}
- While Loop:
The while loop repeatedly executes a block of code as long as a specified condition is true.
Example:
while (condition)
{
// Code to execute while the condition is true
}
- Do-While Loop:
The do-while loop is similar to the while loop, but it executes the code block at least once before checking the condition.
Example:
do
{
// Code to execute at least once
} while (condition);
- For Loop:
The for loop allows you to execute a block of code repeatedly for a specified number of times.
Example:
for (initialization; condition; iteration)
{
// Code to execute in each iteration
}
- Foreach Loop:
The foreach loop is used to iterate over elements in a collection, such as an array or a list.
Example:
foreach (var item in collection)
{
// Code to execute for each item in the collection
}
- Break Statement:
The break statement is used to exit a loop or terminate a switch statement prematurely.
Example:
while (true)
{
if (condition)
{
break; // Exit the loop
}
}
- Continue Statement:
The continue statement is used to skip the rest of the loop’s current iteration and move to the next iteration.
Example:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
continue; // Skip the rest of the code for this iteration
}
// Code to execute for each iteration except when i is 5
}