Drani Academy – Interview Question, Search Job, Tuitorials, Cheat Sheet, Project, eBook

C#.Net

Tutorials – C#.Net

 
Chapter 3: Control Flow


Chapter 3 of our C# tutorial takes you on a journey through the world of control flow in C#. Understanding control flow is essential for building programs that can make decisions, repeat actions, and handle exceptions. In this chapter, we will explore the following control flow constructs: conditional statements, loops, and exception handling.

3.1 Conditional Statements

Conditional statements in C# allow your programs to make decisions. Depending on the outcome of a condition, the program can take different paths. C# provides several conditional statements, with the most common being the if statement.

3.1.1 The if Statement

The if statement is used to execute a block of code if a specified condition is true. Here’s the basic syntax of an if statement:

if (condition)
{
// Code to execute if the condition is true }

For example, you can use an if statement to check if a number is positive:

int number = 5;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}

In this example, the code within the if block is executed because the condition number > 0 is true.

3.1.2 The else Clause

You can extend the if statement with an else clause to specify what should happen if the condition is false. Here’s the syntax:

if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}

For example, let’s modify the previous example to check if a number is positive or non-positive:

int number = -3;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else
{
Console.WriteLine("The number is non-positive.");
}

In this case, because the number is not greater than 0, the code in the else block is executed.

3.1.3 The else if Clause

To handle multiple conditions, you can use the else if clause after the initial if statement. This allows you to check additional conditions if the previous ones are false. Here’s the syntax:

if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition2 is true
}
// You can have more else if blocks as needed
else
{
// Code to execute if no conditions are true
}

For instance, let’s check if a number is positive, negative, or zero:

int number = -2;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else if (number < 0)
{
Console.WriteLine("The number is negative.");
}
else
{
Console.WriteLine("The number is zero.");
}

The else if block allows you to specify an additional condition to check if the previous condition was false.

3.1.4 The switch Statement

The switch statement is another way to handle multiple conditions. It is particularly useful when you want to compare a value to several possible constant values. Here’s the basic structure of a switch statement:

switch (expression)
{
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More case statements as needed
default:
// Code to execute if expression doesn't match any case
break;
}

For example, let’s use a switch statement to determine the day of the week based on a numeric input:

int dayOfWeek = 3;
switch (dayOfWeek)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
// More cases for other days
default:
Console.WriteLine("Invalid day");
break;
}

The switch statement compares the value of dayOfWeek to the cases, and when it finds a match, it executes the corresponding code block. If no match is found, the code in the default block is executed.

3.2 Looping

Loops in C# allow you to repeat a block of code multiple times. They are essential for tasks like iterating over arrays, processing data, and performing repetitive operations.

3.2.1 The for Loop

The for loop is used when you know the number of iterations you need. It consists of three parts: initialization, condition, and increment (or decrement). Here’s the syntax:

for (initialization; condition; increment)
{
// Code to repeat
}

Let’s use a for loop to print the numbers from 1 to 5:

for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}

In this example, the loop initializes i to 1, checks if i is less than or equal to 5, and increments i by 1 in each iteration.

3.2.2 The while Loop

The while loop repeats a block of code as long as a specified condition is true. Here’s the basic structure:

while (condition)
{
// Code to repeat
}

For instance, let’s use a while loop to print even numbers from 2 to 10:

int num = 2;
while (num <= 10)
{
Console.WriteLine(num);
num += 2;
}

The loop continues to run as long as num is less than or equal to 10, and in each iteration, num is incremented by 2.

3.2.3 The do-while Loop

The do-while loop is similar to the while loop but with one crucial difference: it guarantees that the block of code is executed at least once. Here’s the syntax:

do
{
// Code to repeat
} while (condition);

Let’s use a do-while loop to ask the user for input and keep asking until they enter a positive number:

int number;
do
{
Console.Write("Enter a positive number: ");
number = int.Parse(Console.ReadLine());
} while (number <= 0);
Console.WriteLine("You entered a positive number.");

In this example, the loop first executes the code inside the do block and then checks the condition. If the condition is true, the loop continues; otherwise, it exits.

3.2.4 The foreach Loop

The foreach loop is used to iterate over the elements of a collection, such as an array or a list. It simplifies the process of iterating through the items without needing to manage an index. Here’s the syntax:

foreach (elementType element in collection)
{
// Code to process each element
}

For example, let’s use a foreach loop to print the elements of an array:

int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}

The foreach loop iterates through each element in the numbers array and executes the code block.

3.3 Exception Handling

Exception handling in C# is a way to manage and recover from runtime errors. It ensures that your program can gracefully handle unexpected situations. The core constructs for exception handling are the try, catch, and finally blocks.

3.3.1 The try and catch Blocks

The try block contains code that might cause an exception. If an exception occurs, the program jumps to the corresponding catch block to handle the exception.

Here’s the basic structure:

try
{
// Code that may cause an exception
}
catch (ExceptionType ex)
{
// Code to handle the exception
}

For instance, let’s use a try-catch block to safely divide two numbers, catching a DivideByZeroException if the denominator is zero:

int numerator = 10;
int denominator = 0;
try
{
int result = numerator / denominator;
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero.");
}

In this example, the code inside the try block attempts to divide numerator by denominator. Since denominator is zero, a DivideByZeroException is thrown, and the program jumps to the catch block to handle it.

3.3.2 The finally Block

The finally block is used to specify code that should be executed whether or not an exception is thrown. It’s typically used for cleanup tasks, such as closing files or releasing resources.

Here’s the structure of a try-catch-finally block:

try
{
// Code that may cause an exception
}
catch (ExceptionType ex)
{
// Code to handle the exception
}
finally
{
// Code to execute regardless of whether an exception occurred
}

Let’s modify the previous example to include a finally block:

int numerator = 10;
int denominator = 0;
try
{
int result = numerator / denominator;
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero.");
}
finally
{
Console.WriteLine("The calculation is complete.");
}

In this case, the program executes the code in the finally block after catching the exception, ensuring that the “The calculation is complete” message is displayed.

3.4 Conclusion of Chapter 3

In Chapter 3, you’ve explored the essential aspects of control flow in C#. You’ve learned how to make decisions using conditional statements, including if, else, else if, and switch. You’ve also gained an understanding of how to repeat code using loops, including for, while, do-while, and foreach. Lastly, you’ve seen how to handle runtime errors and exceptions using the try, catch, and finally blocks.

These control flow constructs are the building blocks for building complex, functional, and robust applications. As you continue your journey in C# development, you’ll use these concepts to create programs that can adapt, respond to various inputs, and handle unexpected situations gracefully. The ability to control the flow of your program is a fundamental skill that every C# developer should master.

Scroll to Top