Control Structures
Control structures allow modifying the execution flow of a program in C#.
With them, we can make decisions or repeat blocks of code based on conditions.
Decision Structures
- if (simple conditional)
Evaluates a condition and executes the block if it is true.
int age = 18;
if (age >= 18)
{
Console.WriteLine("You are of legal age.");
}
- else
Adds an alternative block when the condition is false.
if (age >= 18)
{
Console.WriteLine("You can enter.");
}
else
{
Console.WriteLine("You cannot enter.");
}
- else if
int score = 85;
if (score >= 90)
{
Console.WriteLine("Excellent");
}
else if (score >= 70)
{
Console.WriteLine("Approved");
}
else
{
Console.WriteLine("Failed");
}
- switch
Used when a variable can have multiple possible cases.
string day = "Monday";
switch (day)
{
case "Monday":
Console.WriteLine("Start of the week");
break;
case "Friday":
Console.WriteLine("Weekend is near");
break;
default:
Console.WriteLine("Normal day");
break;
}
Loops
- for
Used when we know the exact number of iterations.
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Iteration {i}");
}
- foreach
Used to iterate over collections (lists, arrays, etc.).
string[] names = { "Ana", "Luis", "Pedro" };
foreach (string name in names)
{
Console.WriteLine(name);
}
- while
Executes the block as long as the condition remains true.
int counter = 1;
while (counter <= 3)
{
Console.WriteLine($"Counter: {counter}");
counter++;
}
- do..while
Executes the block at least once, and then evaluates the condition.
int number = 1;
do
{
Console.WriteLine($"Number: {number}");
number++;
} while (number <= 3);