Control Flow & Loops
Learn to control program execution with conditional statements and loops. This is a foundational concept in Microsoft application framework that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world .NET experience. Take your time with each section and practice the examples
Conditional Statements
Control flow statements allow your program to make decisions and execute different code blocks based on conditions.. This is an essential concept that every .NET developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
If-Else Statements
// Basic if statement
int age = 18;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
// If-else statement
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Grade: F");
}
// Ternary operator
string status = (age >= 18) ? "Adult" : "Minor";
Console.WriteLine($"Status: {status}");Switch Statements
// Switch statement
char grade = 'B';
switch (grade)
{
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
Console.WriteLine("Good job!");
break;
case 'C':
Console.WriteLine("Satisfactory");
break;
case 'D':
Console.WriteLine("Needs improvement");
break;
case 'F':
Console.WriteLine("Failed");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
// Switch expression (C# 8.0+)
string message = grade switch
{
'A' => "Excellent!",
'B' => "Good job!",
'C' => "Satisfactory",
'D' => "Needs improvement",
'F' => "Failed",
_ => "Invalid grade"
};Loops
// For loop
Console.WriteLine("Counting from 1 to 5:");
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Count: {i}");
}
// While loop
int count = 0;
while (count < 3)
{
Console.WriteLine($"While loop: {count}");
count++;
}
// Do-while loop
int number;
do
{
Console.Write("Enter a positive number: ");
number = int.Parse(Console.ReadLine());
} while (number <= 0);
// Foreach loop
string[] fruits = { "Apple", "Banana", "Orange" };
foreach (string fruit in fruits)
{
Console.WriteLine($"Fruit: {fruit}");
}Loop Control Statements
// Break statement
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
Console.WriteLine("Breaking at 5");
break; // Exit the loop
}
Console.WriteLine(i);
}
// Continue statement
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
Console.WriteLine("Skipping 3");
continue; // Skip to next iteration
}
Console.WriteLine(i);
}
// Nested loops
for (int i = 1; i <= 3; i++)
{
Console.WriteLine($"Outer loop: {i}");
for (int j = 1; j <= 2; j++)
{
Console.WriteLine($" Inner loop: {j}");
}
}