Different Control flow statements in C# full Explanation
In C#, control flow statements are used to control
the flow of execution in a program. They determine the order in which
statements are executed based on conditions or looping requirements. Here's an
explanation of Different control flow statements in C#:
1.
Conditional Statements:
v `if`
statement: It evaluates a condition and executes a block of code if the
condition is true.
if (condition)
{
// Code to execute if condition is
true
}
v `if-else`
statement: It evaluates a condition and executes one block of code if the
condition is true, and another block if the condition is false.
if (condition)
{
// Code to execute if condition is
true
}
else
{
// Code to execute if condition is
false
}
v `else
if` statement: It allows you to specify multiple conditions to evaluate in
sequence.
if (condition1)
{
// Code to execute if condition1 is
true
}
else if (condition2)
{
// Code to execute if condition2 is
true
}
else
{
// Code to execute if all conditions
are false
}
2.
Looping Statements:
v `while`
loop: It executes a block of code repeatedly as long as a specified condition
is true.
while (condition)
{
// Code to execute in each iteration
}
v `do-while`
loop: It executes a block of code once and then repeatedly as long as a
specified condition is true.
do
{
// Code to execute in each iteration
} while (condition);
v `for`
loop: It allows you to specify initialization, condition, and iteration
statements in a compact manner.
for (initialization; condition; iteration)
{
// Code to execute in each iteration
}
v `foreach`
loop: It iterates over elements of a collection or an array.
foreach (var item in collection)
{
// Code to execute for each item
}
3.
Jump Statements:
v `break`
statement: It terminates the current loop or switch statement and transfers
control to the next statement after the loop or switch.
while (condition)
{
if (someCondition)
{
break; // Exit the loop
}
}
v `continue`
statement: It skips the remaining code in the current iteration of a loop and
moves to the next iteration.
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
continue; // Skip even numbers
}
// Code to execute for odd numbers
}
v `return`
statement: It terminates the execution of a method and returns a value
(optional) to the caller.
int Add(int a, int b)
{
return a + b;
}
v `goto`
statement: It transfers the program's control to a labeled statement within the
same method.
goto MyLabel;
// Code that is skipped
MyLabel:
// Code to execute after the 'goto'
statement
These control flow statements provide flexibility
and allow you to control the execution of your code based on
conditions or
looping requirements. They are essential for creating decision-making structures
and repetitive tasks in C# programs.
0 Comments