Control Statements in C# – if, else, switch, and loops Explained
Control statements in C# are used to determine the flow of execution based on conditions and loops. These include decision-making (if, else, switch) and looping (for, while, do-while, foreach) constructs.
Example
using System;
class Program
{
static void Main()
{
int number = 10;
// if-else example
if (number > 0)
{
Console.WriteLine("Positive Number");
}
else
{
Console.WriteLine("Non-Positive Number");
}
// switch example
switch (number)
{
case 10:
Console.WriteLine("Number is 10");
break;
default:
Console.WriteLine("Unknown number");
break;
}
// for loop example
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Count: " + i);
}
}
}
Summary
Control statements are crucial for creating logic in applications. if-else and switch are used for decision-making, while loops (for, while, do-while, foreach) help execute code repeatedly based on a condition.
Example
string[] colors = { "Red", "Green", "Blue" };
foreach (string color in colors)
{
Console.WriteLine(color);
}