Skip to content

Working with LOOPS in C# and .Net 7

Working with LOOPS in C# and .Net 7
Become a developer with our complete learning paths
Become a developer with our complete learning paths

Working with LOOPS in C# and .Net 7

By the end of this article, you’ll have a solid understanding of how to work with loops in C# and how to use them effectively in your own programs. Whether you’re a beginner or an experienced programmer, loops are an essential tool in your programming toolbox, and mastering them will help you write more efficient and powerful code.

C# is a popular programming language that is widely used for developing a variety of applications, from desktop software to web applications and mobile apps. One of the key concepts in C# programming is loops, which allow you to execute a block of code repeatedly until a certain condition is met.

Loops are essential for automating repetitive tasks, such as processing large amounts of data or iterating over collections. By using loops, you can write more efficient and concise code, which is easier to maintain and debug.

In this article, we’ll cover the three main types of loops in C# version 11: for loops, while loops, and do-while loops. Each of these loops has its own syntax and use cases, but they all follow the basic structure of evaluating a condition and executing a block of code repeatedly.

We’ll also explain what the break and continue keywords are used for. These Control flow statements allow you to modify the behavior of loops. Like with the break keyword allowing you to exit a loop prematurely, or the continue keyword allowing you to skip over the current iteration of a loop and move on to the next one. As said, we will go over more detail later and include some examples as well.

If you want to skyrocket your C# career, check out our powerful ASP.NET FULL-STACK WEB DEVELOPMENT COURSE, which also covers test-driven development and C# software architecture.

Before we dive into the specifics of each type of loop, it’s important to understand the basic structure of a loop.

 

What is a loop?

In programming, a loop is a control structure that allows you to execute a block of code repeatedly. The idea is to keep executing the same block of code as long as a certain condition is true. Once the condition becomes false, the loop will terminate and the program will move on to the next line of code.

In C# 11, there are several types of loops available, including the for loop, the while loop, and the do-while loop. Each of these loops has its own syntax and use cases. We will learn more about these in the continuation.

The condition of a loop is usually expressed as a boolean expression, which is either true or false. At the beginning of each iteration, the condition is evaluated, and if it is true, the block of code associated with the loop is executed. This block of code can contain any number of statements, and can include other control structures like if statements and switch statements.

loop(condition){
    code to be executed
}

Once the block of code has finished executing, the condition is evaluated again. If it is still true, the block of code is executed again, and the process repeats. This continues until the condition is false, at which point the loop terminates, and the program moves on to the next line of code.

NOTE It’s important to be careful when using loops, as it is possible to create an infinite loop that never terminates. This can happen if the condition of the loop is always true, or if there is a mistake in the code that prevents the condition from ever becoming false. Infinite loops can cause a program to become unresponsive or crash, so it’s important to test your code thoroughly and ensure your loops are working as intended.

With that, let us start with the first type of loop, probably the simplest and most well-known one. The for loop.

For Loops

A for loop is the most commonly used type of loop in C#. It has a compact syntax and is ideal for situations where you need to iterate over a fixed number of items. Here is the basic structure of a for loop:

for (initialization; condition; increment/decrement)
{
    // code to be executed
}

The initialization statement is used to declare and initialize a variable that will be used to control the loop. The condition statement is a Boolean expression that is evaluated at the beginning of each iteration. If the condition is true, the loop continues. If it is false, the loop ends. The increment/decrement statement is used to modify the variable that controls the loop at the end of each iteration.

Let’s take a look at a simple example of a for loop:

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

We declare and initialize a variable i to 0. The condition is that i must be less than 5. The increment statement adds 1 to i at the end of each iteration. This loop will execute 5 times and print the values of i from 0 to 4.

What if we wanted to keep looping until a given condition stops being true? So as in, keep looping while a certain condition is true? Well, for that we have the While loop.

 

While Loops

A while loop is used when you need to repeat a block of code while a certain condition is true. Here is the basic structure of a while loop:

while (condition)
{
    // code to be executed
}

The condition statement is a Boolean expression that is evaluated at the beginning of each iteration. If the condition is true, the loop continues. If it is false, the loop ends.

Let’s take a look at a simple example of a while loop:

int i = 0;
while (i < 5)
{
    Console.WriteLine(i);
    i++;
}

We declare and initialize a variable i to 0. The condition is that i must be less than 5. The block of code inside the loop will execute as long as the condition is true. Inside the loop, we print the value of i and then increment it by 1. This loop will execute 5 times and print the values of i from 0 to 4.

Sometimes we just want a certain piece of code to at least run once, then repeat if a condition is met, is that also possible? Yes, with the Do-While loop.

 

Do-While Loops

A do-while loop is similar to a while loop, but the block of code is executed at least once, regardless of whether the condition is true or false. Here is the basic structure of a do-while loop:

do
{
    // code to be executed
}
while (condition);

The block of code is executed first, and then the condition statement is evaluated. If the condition is true, the loop continues. If it is false, the loop ends.

Let’s take a look at a simple example of a do-while loop:

int i = 0;
do { 
    Console.WriteLine(i);
    i++; 
} while (i < 5);

We declare and initialize a variable i to 0. The block of code inside the loop will execute at least once, regardless of the value of i. Inside the loop, we print the value of i and then increment it by 1. The condition is that i must be less than 5. This loop will execute 5 times and print the values of i from 0 to 4.

Do-while loops are useful in situations where you need to ensure that a block of code is executed at least once, even if the condition is not met initially. They can be especially helpful for user input validation, menu-driven applications, and operations with an unknown number of iterations. We can see one such example here:

User input validation: Do-while loops are often used when you want to prompt the user for input and validate their response before proceeding. Since the loop executes the code at least once, you can ensure that the user is prompted and their input is checked against the validation criteria.

string userInput;
int number;
do
{
    Console.Write("Enter a number between 1 and 10: ");
    userInput = Console.ReadLine();
}
while (!int.TryParse(userInput, out number) || number < 1 || number > 10);

 

And that would be it for our quick overview of loops! If you by now started asking yourself, “And what about foreach?” then well, you are right! What about foreach? That we covered in our blogpost about collections and iterators in C# .Net 7! Check it out to find out more!

For now, though, to finish up this article, we want to talk about Break and Continue! So let us get to it!

Break and Continue Keywords

In addition to the three types of loops, C# also provides two keywords that can be used to control the flow of a loop: break and continue.

The break keyword is used to exit a loop early. When break is encountered inside a loop, the loop is immediately terminated, and control is passed to the statement following the loop. Here is an example of using break in a for loop:

for (int i = 0; i < 5; i++) {
    if (i == 3) { 
        break; 
    } 
    Console.WriteLine(i); 
}

We use an if statement inside the loop to check if the value of i is 3. If it is, we use break to exit the loop early. This loop will execute 4 times and print the values of i from 0 to 2.

On the other hand, the continue keyword is used to skip over an iteration of a loop. When continue is encountered inside a loop, the current iteration is skipped and control is passed to the next iteration. Here is an example of using continue in a while loop:

int i = 0; 
while (i < 5) { 
    i++; 
    if (i == 3) {
        continue; 
    } 
    Console.WriteLine(i); 
}

We use an if statement inside the loop to check if the value of i is 3. If it is, we use continue to skip the current iteration. This loop will execute 5 times and print the values of i from 1 to 5, skipping the value 3.

And that is it! Guess we got through it, hope you learned something new today!

Conclusion: Working with LOOPS in C# and .Net 7

In conclusion, loops are an essential tool for developers when it comes to automating repetitive tasks in their programs.

As a quick summary, C# offers three types of loops: for loops, while loops, and do-while loops. These loops follow a similar structure of evaluating a condition and executing a block of code repeatedly until the condition is no longer met. Additionally, the break and continue keywords can be used to modify the behavior of loops. And it is important to remember to be careful when using loops to avoid creating infinite loops that can cause a program to become unresponsive or crash.

Overall, understanding how to work with loops in C# can help developers write more efficient and powerful code.

If you want to skyrocket your C# career, check out our powerful ASP.NET FULL-STACK WEB DEVELOPMENT COURSE, which also covers test-driven development and C# software architecture.

Lost in coding? Discover our Learning Paths!
Lost in coding? Discover our Learning Paths!
Enter your email and we will send you the PDF guide:
Enter your email and we will send you the PDF guide