DEV Community

Adrián Bailador
Adrián Bailador

Posted on

1

Part 4: Control Flow in C#

Control flow in a program determines the order in which instructions are executed. In C#, these decisions and repetitions are managed with specific structures that allow you to create dynamic and flexible programs. In this lesson, we will explore the main control flow structures: decisions and loops.

1. Decision Structures

Decision structures allow the program to execute different blocks of code depending on a condition. The most common ones in C# are if, else if, and else.

1.1 if

The if block evaluates a condition and executes the code inside the block if the condition is true.

int number = 10;
if (number > 5)
{
    Console.WriteLine("The number is greater than 5.");
}
Enter fullscreen mode Exit fullscreen mode

1.2 else if

This is used to evaluate additional conditions if the initial condition is not met.

int number = 5;
if (number > 10)
{
    Console.WriteLine("The number is greater than 10.");
}
else if (number == 5)
{
    Console.WriteLine("The number is equal to 5.");
}
Enter fullscreen mode Exit fullscreen mode

1.3 else

The else block is executed if none of the previous conditions are met.

int number = 3;
if (number > 10)
{
    Console.WriteLine("The number is greater than 10.");
}
else if (number == 5)
{
    Console.WriteLine("The number is equal to 5.");
}
else
{
    Console.WriteLine("The number is not greater than 10 nor equal to 5.");
}
Enter fullscreen mode Exit fullscreen mode

2. Loop Structures

Loops or repetition structures allow you to execute a block of code multiple times, making repetitive tasks easier.

2.1 for

The for loop is ideal when you know the exact number of iterations.

for (int i = 0; i < 5; i++)
{
    Console.WriteLine($"Iteration {i}");
}
Enter fullscreen mode Exit fullscreen mode

2.2 while

The while loop executes the code as long as the condition is true.

int counter = 0;
while (counter < 5)
{
    Console.WriteLine($"Counter: {counter}");
    counter++;
}
Enter fullscreen mode Exit fullscreen mode

2.3 do-while

Similar to while, but it ensures that the block of code is executed at least once.

int counter = 0;
do
{
    Console.WriteLine($"Counter: {counter}");
    counter++;
} while (counter < 5);
Enter fullscreen mode Exit fullscreen mode

2.4 foreach

This is used to iterate through collections such as arrays or lists in a simple way.

int[] numbers = {1, 2, 3, 4, 5};
foreach (int number in numbers)
{
    Console.WriteLine(number);
}
Enter fullscreen mode Exit fullscreen mode

3. Practical Exercises

3.1 Calculate the Factorial of a Number

The factorial of a positive integer n is the product of all positive integers less than or equal to n.

int number = 5;
int factorial = 1;
for (int i = 1; i <= number; i++)
{
    factorial *= i;
}
Console.WriteLine($"The factorial of {number} is {factorial}.");
Enter fullscreen mode Exit fullscreen mode

3.2 Consecutive Sums

Calculate the sum of the first n natural numbers.

int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++)
{
    sum += i;
}
Console.WriteLine($"The sum of the first {n} numbers is {sum}.");
Enter fullscreen mode Exit fullscreen mode

3.3 Check if a Number is Prime

A prime number is one that is only divisible by 1 and itself.

int number = 7;
bool isPrime = true;
for (int i = 2; i < number; i++)
{
    if (number % i == 0)
    {
        isPrime = false;
        break;
    }
}
if (isPrime)
{
    Console.WriteLine($"{number} is a prime number.");
}
else
{
    Console.WriteLine($"{number} is not a prime number.");
}
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay