Skip to main content

.NET C# Control Flow

Control flow is one of the fundamental concepts in programming that determines the order in which statements are executed in your code. In C#, control flow structures allow you to make decisions, repeat actions, and jump to different parts of your code. Understanding control flow is essential for writing effective and efficient programs.

Introduction to Control Flow

Control flow refers to the order in which individual statements, instructions, or function calls of a program are executed or evaluated. By default, statements in your C# program are executed sequentially from top to bottom. However, control flow structures allow you to alter this flow based on decisions and conditions.

In C#, control flow can be categorized into three main types:

  1. Conditional Statements: Execute code blocks based on whether a condition is true or false
  2. Loops: Execute code blocks repeatedly based on a condition
  3. Jump Statements: Transfer control to another part of the program

Let's explore each of these in detail.

Conditional Statements

Conditional statements allow your programs to make decisions and execute different code based on different conditions.

if-else Statement

The if-else statement is the most basic form of conditional logic in C#.

Basic Syntax:

csharp
if (condition)
{
// Code executed if condition is true
}
else
{
// Code executed if condition is false
}

Example:

csharp
int age = 20;

if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are a minor.");
}

Output:

You are an adult.

if-else if-else Statement

For multiple conditions, you can use the if-else if-else structure:

csharp
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");
}

Output:

Grade: B

switch Statement

The switch statement provides a more elegant way to handle multiple conditions based on a single value.

csharp
int day = 3;
string dayName;

switch (day)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}

Console.WriteLine($"Day {day} is {dayName}");

Output:

Day 3 is Wednesday

Ternary Operator

The ternary operator ? : provides a compact way to write simple if-else statements:

csharp
int number = 7;
string result = (number % 2 == 0) ? "Even" : "Odd";
Console.WriteLine($"The number {number} is {result}.");

Output:

The number 7 is Odd.

Loops

Loops allow you to execute a block of code repeatedly based on a condition.

for Loop

The for loop is ideal when you know in advance how many times you want to execute a block of code.

csharp
Console.WriteLine("Counting from 1 to 5:");
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Count: {i}");
}

Output:

Counting from 1 to 5:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

while Loop

The while loop continues to execute as long as a specified condition is true.

csharp
int countdown = 5;
Console.WriteLine("Countdown:");
while (countdown > 0)
{
Console.WriteLine(countdown);
countdown--;
}
Console.WriteLine("Blast off!");

Output:

Countdown:
5
4
3
2
1
Blast off!

do-while Loop

Similar to the while loop, but ensures that the code block is executed at least once before checking the condition.

csharp
int number = 1;
Console.WriteLine("do-while example:");
do
{
Console.WriteLine($"Number: {number}");
number++;
} while (number <= 3);

Output:

do-while example:
Number: 1
Number: 2
Number: 3

foreach Loop

The foreach loop is used to iterate over collections like arrays, lists, or other enumerable types.

csharp
string[] fruits = { "Apple", "Banana", "Cherry", "Date" };

Console.WriteLine("Fruits in the basket:");
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}

Output:

Fruits in the basket:
Apple
Banana
Cherry
Date

Jump Statements

Jump statements transfer the control flow to another location in your program.

break Statement

The break statement terminates the closest enclosing loop or switch statement.

csharp
Console.WriteLine("break example:");
for (int i = 1; i <= 10; i++)
{
if (i == 6)
{
break;
}
Console.WriteLine($"Count: {i}");
}

Output:

break example:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

continue Statement

The continue statement skips the current iteration of a loop and continues with the next iteration.

csharp
Console.WriteLine("continue example (skipping odd numbers):");
for (int i = 1; i <= 10; i++)
{
if (i % 2 != 0)
{
continue;
}
Console.WriteLine($"Even number: {i}");
}

Output:

continue example (skipping odd numbers):
Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10

return Statement

The return statement exits a method and optionally returns a value.

csharp
static int Add(int a, int b)
{
return a + b;
}

// Usage
int sum = Add(5, 3);
Console.WriteLine($"Sum: {sum}");

Output:

Sum: 8

goto Statement

The goto statement transfers control directly to a labeled statement. While it's generally discouraged in modern programming due to making code harder to read and maintain, it's available in C#:

csharp
int i = 1;
start:
if (i <= 5)
{
Console.WriteLine($"Using goto: {i}");
i++;
goto start;
}

Output:

Using goto: 1
Using goto: 2
Using goto: 3
Using goto: 4
Using goto: 5

Practical Examples

Let's look at some real-world applications of control flow in C#.

Example 1: Simple ATM Interface

csharp
decimal balance = 1000.00m;
bool exitRequested = false;

Console.WriteLine("Simple ATM Interface");

while (!exitRequested)
{
Console.WriteLine("\nSelect an option:");
Console.WriteLine("1. View Balance");
Console.WriteLine("2. Deposit Money");
Console.WriteLine("3. Withdraw Money");
Console.WriteLine("4. Exit");

string choice = Console.ReadLine();

switch (choice)
{
case "1":
Console.WriteLine($"Current Balance: ${balance}");
break;
case "2":
Console.Write("Enter amount to deposit: $");
if (decimal.TryParse(Console.ReadLine(), out decimal depositAmount) && depositAmount > 0)
{
balance += depositAmount;
Console.WriteLine($"${depositAmount} has been deposited. New balance: ${balance}");
}
else
{
Console.WriteLine("Invalid amount.");
}
break;
case "3":
Console.Write("Enter amount to withdraw: $");
if (decimal.TryParse(Console.ReadLine(), out decimal withdrawAmount) && withdrawAmount > 0)
{
if (withdrawAmount <= balance)
{
balance -= withdrawAmount;
Console.WriteLine($"${withdrawAmount} has been withdrawn. New balance: ${balance}");
}
else
{
Console.WriteLine("Insufficient funds.");
}
}
else
{
Console.WriteLine("Invalid amount.");
}
break;
case "4":
exitRequested = true;
Console.WriteLine("Thank you for using our ATM. Goodbye!");
break;
default:
Console.WriteLine("Invalid option. Please try again.");
break;
}
}

Example 2: Number Guessing Game

csharp
Random random = new Random();
int secretNumber = random.Next(1, 101); // Generate a random number between 1 and 100
int attempts = 0;
bool hasGuessedCorrectly = false;

Console.WriteLine("Welcome to the Number Guessing Game!");
Console.WriteLine("I'm thinking of a number between 1 and 100.");

while (!hasGuessedCorrectly && attempts < 10) // Maximum 10 attempts
{
Console.Write($"Attempt {attempts + 1}/10. Enter your guess: ");
if (int.TryParse(Console.ReadLine(), out int guess))
{
attempts++;

if (guess < secretNumber)
{
Console.WriteLine("Too low! Try a higher number.");
}
else if (guess > secretNumber)
{
Console.WriteLine("Too high! Try a lower number.");
}
else
{
hasGuessedCorrectly = true;
Console.WriteLine($"Congratulations! You guessed the number {secretNumber} correctly in {attempts} attempts!");
}
}
else
{
Console.WriteLine("Please enter a valid number.");
}
}

if (!hasGuessedCorrectly)
{
Console.WriteLine($"Sorry, you've used all 10 attempts. The secret number was {secretNumber}.");
}

Advanced Control Flow Concepts

Nested Control Structures

You can nest control structures within each other for more complex logic:

csharp
for (int i = 1; i <= 3; i++)
{
Console.WriteLine($"Outer loop iteration {i}");

for (int j = 1; j <= 2; j++)
{
Console.WriteLine($" Inner loop iteration {j}");

if (i == 2 && j == 1)
{
Console.WriteLine(" Special condition met!");
}
}
}

Output:

Outer loop iteration 1
Inner loop iteration 1
Inner loop iteration 2
Outer loop iteration 2
Inner loop iteration 1
Special condition met!
Inner loop iteration 2
Outer loop iteration 3
Inner loop iteration 1
Inner loop iteration 2

Pattern Matching with switch

C# 8.0 and later support enhanced pattern matching in switch expressions:

csharp
object value = "Hello, World!";
string message;

switch (value)
{
case int i when i > 0:
message = $"Positive integer: {i}";
break;
case int i:
message = $"Non-positive integer: {i}";
break;
case string s when s.Length > 5:
message = $"Long string: {s}";
break;
case string s:
message = $"Short string: {s}";
break;
case null:
message = "Null value";
break;
default:
message = $"Unknown type: {value.GetType().Name}";
break;
}

Console.WriteLine(message);

Output:

Long string: Hello, World!

Summary

Control flow is a fundamental concept in C# programming that allows you to:

  1. Make decisions using conditional statements (if-else, switch)
  2. Repeat operations using loops (for, while, do-while, foreach)
  3. Control execution flow using jump statements (break, continue, return, goto)

Mastering control flow structures is essential for writing effective, efficient, and flexible C# programs. As you build more complex applications, you'll find yourself combining these structures in various ways to implement sophisticated program logic.

Additional Resources

To further enhance your understanding of C# control flow, consider exploring these resources:

Exercises

  1. Write a program that prints all prime numbers between 1 and 100.
  2. Create a simple calculator program that allows users to perform basic arithmetic operations (addition, subtraction, multiplication, division).
  3. Implement a program that converts temperatures between Celsius and Fahrenheit based on user input.
  4. Create a "FizzBuzz" program that prints numbers from 1 to 100, but for multiples of 3 prints "Fizz" instead of the number, for multiples of 5 prints "Buzz", and for numbers that are multiples of both 3 and 5 prints "FizzBuzz".
  5. Write a program that prints a pyramid pattern of asterisks based on a height provided by the user.

By completing these exercises, you'll gain practical experience with C# control flow structures and improve your programming skills.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)