Control Structures
Master decision-making and loops in C# programming
Decision Making
Control structures allow your program to make decisions and execute different code paths based on conditions.
If Statements
The if statement executes code when a condition is true:
int age = 18;
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
// Single line if (without braces)
if (age >= 18) Console.WriteLine("Eligible to vote.");If-Else Statements
Use else to handle the false condition:
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 if (score >= 60)
{
Console.WriteLine("Grade: D");
}
else
{
Console.WriteLine("Grade: F");
}Comparison Operators
int x = 10, y = 20;
// Equality operators
Console.WriteLine($"{x} == {y}: {x == y}"); // Equal to
Console.WriteLine($"{x} != {y}: {x != y}"); // Not equal to
// Relational operators
Console.WriteLine($"{x} < {y}: {x < y}"); // Less than
Console.WriteLine($"{x} > {y}: {x > y}"); // Greater than
Console.WriteLine($"{x} <= {y}: {x <= y}"); // Less than or equal
Console.WriteLine($"{x} >= {y}: {x >= y}"); // Greater than or equalLogical Operators
bool hasLicense = true;
int age = 20;
bool hasInsurance = false;
// AND operator (&&) - both conditions must be true
if (hasLicense && age >= 18)
{
Console.WriteLine("Can drive legally.");
}
// OR operator (||) - at least one condition must be true
if (hasLicense || age >= 21)
{
Console.WriteLine("At least one condition is met.");
}
// NOT operator (!) - inverts the boolean value
if (!hasInsurance)
{
Console.WriteLine("Warning: No insurance coverage!");
}
// Complex logical expressions
if ((hasLicense && age >= 18) && (hasInsurance || age >= 25))
{
Console.WriteLine("Can rent a car.");
}Switch Statements
Switch statements provide a clean way to handle multiple conditions:
char grade = 'B';
switch (grade)
{
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
Console.WriteLine("Good job!");
break;
case 'C':
Console.WriteLine("Average performance.");
break;
case 'D':
Console.WriteLine("Below average.");
break;
case 'F':
Console.WriteLine("Failed.");
break;
default:
Console.WriteLine("Invalid grade.");
break;
}Switch Expressions (C# 8+)
Modern C# offers a more concise switch syntax:
char grade = 'B';
string message = grade switch
{
'A' => "Excellent!",
'B' => "Good job!",
'C' => "Average performance.",
'D' => "Below average.",
'F' => "Failed.",
_ => "Invalid grade." // Default case
};
Console.WriteLine(message);
// Switch expression with multiple values
string dayType = DateTime.Now.DayOfWeek switch
{
DayOfWeek.Monday or DayOfWeek.Tuesday or DayOfWeek.Wednesday
or DayOfWeek.Thursday or DayOfWeek.Friday => "Weekday",
DayOfWeek.Saturday or DayOfWeek.Sunday => "Weekend",
_ => "Unknown"
};
Console.WriteLine($"Today is a {dayType}");Loops
Loops allow you to execute code repeatedly based on a condition.
For Loop
Use for loops when you know the number of iterations:
// Basic for loop
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Iteration {i}");
}
// Counting backwards
for (int i = 10; i >= 1; i--)
{
Console.WriteLine($"Countdown: {i}");
}
// Different increment values
for (int i = 0; i <= 20; i += 2)
{
Console.WriteLine($"Even number: {i}");
}
// Multiple variables in for loop
for (int i = 0, j = 10; i < 5; i++, j--)
{
Console.WriteLine($"i = {i}, j = {j}");
}While Loop
Use while loops when the number of iterations is unknown:
int count = 1;
while (count <= 5)
{
Console.WriteLine($"Count: {count}");
count++; // Important: increment to avoid infinite loop
}
// Practical example: user input validation
string input;
int number;
Console.Write("Enter a positive number: ");
while (!int.TryParse(Console.ReadLine(), out number) || number <= 0)
{
Console.Write("Invalid input. Please enter a positive number: ");
}
Console.WriteLine($"You entered: {number}");Do-While Loop
do-while loops execute at least once, then check the condition:
int attempts = 0;
string password;
do
{
Console.Write("Enter password: ");
password = Console.ReadLine();
attempts++;
if (password != "secret123")
{
Console.WriteLine("Incorrect password. Try again.");
}
} while (password != "secret123" && attempts < 3);
if (password == "secret123")
{
Console.WriteLine("Access granted!");
}
else
{
Console.WriteLine("Too many failed attempts. Access denied.");
}Foreach Loop
Use foreach to iterate through collections:
// Array iteration
string[] fruits = { "apple", "banana", "orange", "grape" };
foreach (string fruit in fruits)
{
Console.WriteLine($"I like {fruit}");
}
// String iteration (strings are collections of characters)
string word = "Hello";
foreach (char letter in word)
{
Console.WriteLine($"Letter: {letter}");
}
// Working with numbers
int[] numbers = { 2, 4, 6, 8, 10 };
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
Console.WriteLine($"Sum of numbers: {sum}");Loop Control Statements
Break Statement
break exits the loop immediately:
// Finding a specific number
int[] numbers = { 1, 3, 7, 9, 12, 15, 18 };
int target = 12;
bool found = false;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == target)
{
Console.WriteLine($"Found {target} at index {i}");
found = true;
break; // Exit the loop early
}
}
if (!found)
{
Console.WriteLine($"{target} not found in the array");
}Continue Statement
continue skips the current iteration and moves to the next:
// Print only even numbers
for (int i = 1; i <= 10; i++)
{
if (i % 2 != 0) // If number is odd
{
continue; // Skip this iteration
}
Console.WriteLine($"Even number: {i}");
}
// Skip empty strings
string[] words = { "apple", "", "banana", "", "cherry" };
foreach (string word in words)
{
if (string.IsNullOrEmpty(word))
{
continue; // Skip empty strings
}
Console.WriteLine($"Processing: {word}");
}Nested Loops
Loops can be nested inside other loops:
// Multiplication table
Console.WriteLine("Multiplication Table:");
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
Console.Write($"{i * j:D2} "); // D2 formats as 2-digit number
}
Console.WriteLine(); // New line after each row
}
// Pattern printing
Console.WriteLine("\nStar Pattern:");
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("* ");
}
Console.WriteLine();
}Conditional Operator (Ternary)
A shorthand for simple if-else statements:
int age = 20;
// Traditional if-else
string status1;
if (age >= 18)
{
status1 = "Adult";
}
else
{
status1 = "Minor";
}
// Ternary operator (condition ? true_value : false_value)
string status2 = age >= 18 ? "Adult" : "Minor";
Console.WriteLine($"Status: {status2}");
// Nested ternary operators (use sparingly)
int score = 85;
string grade = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" :
score >= 60 ? "D" : "F";
Console.WriteLine($"Grade: {grade}");Practical Examples
Number Guessing Game
Random random = new Random();
int secretNumber = random.Next(1, 101); // Random number 1-100
int attempts = 0;
int maxAttempts = 7;
bool hasWon = false;
Console.WriteLine("Welcome to the Number Guessing Game!");
Console.WriteLine("I'm thinking of a number between 1 and 100.");
while (attempts < maxAttempts && !hasWon)
{
Console.Write($"Attempt {attempts + 1}/{maxAttempts}: Enter your guess: ");
if (int.TryParse(Console.ReadLine(), out int guess))
{
attempts++;
if (guess == secretNumber)
{
Console.WriteLine($"Congratulations! You found the number in {attempts} attempts!");
hasWon = true;
}
else if (guess < secretNumber)
{
Console.WriteLine("Too low! Try a higher number.");
}
else
{
Console.WriteLine("Too high! Try a lower number.");
}
}
else
{
Console.WriteLine("Please enter a valid number.");
}
}
if (!hasWon)
{
Console.WriteLine($"Game over! The number was {secretNumber}.");
}Simple Calculator
bool continueCalculating = true;
while (continueCalculating)
{
Console.WriteLine("\n=== Simple Calculator ===");
Console.Write("Enter first number: ");
if (!double.TryParse(Console.ReadLine(), out double num1))
{
Console.WriteLine("Invalid number!");
continue;
}
Console.Write("Enter operator (+, -, *, /): ");
string op = Console.ReadLine();
Console.Write("Enter second number: ");
if (!double.TryParse(Console.ReadLine(), out double num2))
{
Console.WriteLine("Invalid number!");
continue;
}
double result = op switch
{
"+" => num1 + num2,
"-" => num1 - num2,
"*" => num1 * num2,
"/" when num2 != 0 => num1 / num2,
"/" => double.NaN, // Division by zero
_ => double.NaN // Invalid operator
};
if (double.IsNaN(result))
{
if (op == "/" && num2 == 0)
Console.WriteLine("Error: Division by zero!");
else
Console.WriteLine("Error: Invalid operator!");
}
else
{
Console.WriteLine($"Result: {num1} {op} {num2} = {result}");
}
Console.Write("Continue? (y/n): ");
string answer = Console.ReadLine()?.ToLower();
continueCalculating = answer == "y" || answer == "yes";
}
Console.WriteLine("Thank you for using the calculator!");Control structures are essential for creating dynamic, interactive programs. They allow your code to respond to different conditions and process data efficiently through repetition. Practice with these examples to build your understanding of program flow control.
Last updated on