Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 55 additions & 43 deletions docs/csharp/tour-of-csharp/tutorials/branches-and-loops.md
Original file line number Diff line number Diff line change
@@ -1,103 +1,113 @@
---
title: Branches and loops - Introductory tutorial
description: In this tutorial about branches and loops, you write C# code to explore the language syntax that supports conditional branches and loops to execute statements repeatedly. You write C# code and see the results of compiling and running your code directly in the browser.
ms.date: 03/06/2025
ms.date: 12/03/2025
---
# C# `if` statements and loops - conditional logic tutorial

This tutorial teaches you how to write C# code that examines variables and changes the execution path based on those variables. You write C# code and see the results of compiling and running it. The tutorial contains a series of lessons that explore branching and looping constructs in C#. These lessons teach you the fundamentals of the C# language.

> [!TIP]
>
> When a code snippet block includes the "Run" button, that button opens the interactive window, or replaces the existing code in the interactive window. When the snippet doesn't include a "Run" button, you can copy the code and add it to the current interactive window.
To use codespaces, you need a GitHub account. If you don't already have one, you can create a free account at [GitHub.com](https://github.com).

Open a browser window to [GitHub codespaces](https://github.com/codespaces). Create a new codespace from the *.NET Template*. If you've done other tutorials in this series, you can open that codespace. Once your codespace loads, create a new file in the *tutorials* folder named *branches-loops.cs*. Open your new file. Type or copy the following code into *branches-loops.cs*:

Run the following code in the interactive window. Select **Run**:
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="FirstIf":::

:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="FirstIf":::
Try this code by typing the following in the integrated terminal:

```dotnetcli
cd tutorials
dotnet branches-loops.cs
```

Modify the declaration of `b` so that the sum is less than 10:
You should see the message "The answer is greater than 10." printed to your console. Modify the declaration of `b` so that the sum is less than 10:

```csharp
int b = 3;
```

Select the **Run** button again. Because the answer is less than 10, nothing is printed. The **condition** you're testing is false. You don't have any code to execute because you only wrote one of the possible branches for an `if` statement: the true branch.
Type `dotnet branches-loops.cs` again in the terminal window. Because the answer is less than 10, nothing is printed. The **condition** you're testing is false. You don't have any code to execute because you've only written one of the possible branches for an `if` statement: the true branch.

> [!TIP]
>
> As you explore C# (or any programming language), you make mistakes when you write code. The **compiler** finds those errors and report them to you. When the output contains error messages, look closely at the example code, and the code in the interactive window to see what to fix. That exercise helps you learn the structure of C# code.
> As you explore C# (or any programming language), you'll make mistakes when you write code. The compiler will find and report the errors. Look closely at the error output and the code that generated the error. You can also ask Copilot to find differences or spot any mistakes. The compiler error can usually help you find the problem.

This first sample shows the power of `if` and boolean types. A *boolean* is a variable that can have one of two values: `true` or `false`. C# defines a special type, `bool` for boolean variables. The `if` statement checks the value of a `bool`. When the value is `true`, the statement following the `if` executes. Otherwise, it's skipped.

This process of checking conditions and executing statements based on those conditions is powerful. Let's explore more.
This first sample shows the power of `if` and Boolean types. A *Boolean* is a variable that can have one of two values: `true` or `false`. C# defines a special type, `bool` for Boolean variables. The `if` statement checks the value of a `bool`. When the value is `true`, the statement following the `if` executes. Otherwise, it's skipped. This process of checking conditions and executing statements based on those conditions is powerful. Let's explore more.

## Make if and else work together

To execute different code in both the true and false branches, you create an `else` branch that executes when the condition is false. Try the following code:
To execute different code in both the true and false branches, you create an `else` branch that executes when the condition is false. Try an `else` branch. Add the last two lines in the following code snippet (you should already have the first four):

:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="IfAndElse":::
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="IfAndElse":::

The statement following the `else` keyword executes only when the condition being tested is `false`. Combining `if` and `else` with boolean conditions provides all the power you need.
The statement following the `else` keyword executes only when the condition being tested is `false`. Combining `if` and `else` with Boolean conditions provides all the power you need to handle both a `true` and a `false` condition.

> [!IMPORTANT]
>
> The indentation under the `if` and `else` statements is for human readers. The C# language doesn't treat indentation or white space as significant. The statement following the `if` or `else` keyword executes based on the condition. All the samples in this tutorial follow a common practice to indent lines based on the control flow of statements.

Because indentation isn't significant, you need to use `{` and `}` to indicate when you want more than one statement to be part of the block that executes conditionally. C# programmers typically use those braces on all `if` and `else` clauses. The following example is the same as what you created. Try it.
Because indentation isn't significant, you need to use `{` and `}` to indicate when you want more than one statement to be part of the block that executes conditionally. C# programmers typically use those braces on all `if` and `else` clauses. The following example is the same as what you created. Modify your code above to match the following code:

:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="IncludeBraces":::
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="IncludeBraces":::

> [!TIP]
>
> Through the rest of this tutorial, the code samples all include the braces, following accepted practices.

You can test more complicated conditions:
You can test more complicated conditions. Add the following code after the code you've written so far:

:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="ComplexConditions":::
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="ComplexConditions":::

The `==` symbol tests for *equality*. Using `==` distinguishes the test for equality from assignment, which you saw in `a = 5`.

The `&&` represents "and". It means both conditions must be true to execute the statement in the true branch. These examples also show that you can have multiple statements in each conditional branch, provided you enclose them in `{` and `}`.

You can also use `||` to represent "or":
You can also use `||` to represent "or". Add the following code after what you've written so far:

:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="UseOr":::
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="UseOr":::

Modify the values of `a`, `b`, and `c` and switch between `&&` and `||` to explore. You gain more understanding of how the `&&` and `||` operators work.

You finished the first step. Before you start the next section, let's move the current code into a separate method. That makes it easier to start working with a new example. Put the existing code in a method called `ExploreIf()`. Call it from the top of your program. When you finished those changes, your code should look like the following:

:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="Refactor":::

Comment out the call to `ExploreIf()`. It will make the output less cluttered as you work in this section:

```csharp
//ExploreIf();
```

The `//` starts a **comment** in C#. Comments are any text you want to keep in your source code but not execute as code. The compiler doesn't generate any executable code from comments.

## Use loops to repeat operations

Another important concept to create larger programs is **loops**. You use loops to repeat statements that you want executed more than once. Try this code in the interactive window:
Another important concept to create larger programs is **loops**. You use loops to repeat statements that you want executed more than once. Add this code after the call to `ExploreIf`:

:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="WhileLoop":::
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="WhileLoop":::

The `while` statement checks a condition and executes the statement following the `while`. It repeats checking the condition and executing those statements until the condition is false.

There's one other new operator in this example. The `++` after the `counter` variable is the **increment** operator. It adds 1 to the value of counter, and stores that value in the counter variable.
There's one other new operator in this example. The `++` after the `counter` variable is the **increment** operator. It adds 1 to the value of `counter` and stores that value in the `counter` variable.

> [!IMPORTANT]
>
> Make sure that the `while` loop condition does switch to false as you execute the code. Otherwise, you create an **infinite loop** where your program never ends. Let's
> not demonstrate that, because the engine that runs your code times out and you see no output from your program.
> Make sure that the `while` loop condition changes to false as you execute the code. Otherwise, you create an **infinite loop** where your program never ends. That is not demonstrated in this sample, because you have to force your program to quit using **CTRL-C** or other means.

The `while` loop tests the condition before executing the code following the `while`. The `do` ... `while` loop executes the code first, and then checks the condition. It looks like this:
The `while` loop tests the condition before executing the code following the `while`. The `do` ... `while` loop executes the code first, and then checks the condition. The *do while* loop is shown in the following code:

:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="DoLoop":::
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="DoLoop":::

This `do` loop and the earlier `while` loop work the same.
This `do` loop and the earlier `while` loop produce the same output.

Let's move on to one last loop statement.

## Work with the for loop

Another common loop statement that you see in C# code is the `for` loop. Try this code in the interactive window:
Another common loop statement that you see in C# code is the `for` loop. Try this code:

:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="ForLoop":::
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="ForLoop":::

The preceding `for` loop does the same work as the `while` loop and the `do` loop you already used. The `for` statement has three parts that control how it works:

- The first part is the **for initializer**: `int counter = 0;` declares that `counter` is the loop variable, and sets its initial value to `0`.
- The middle part is the **for condition**: `counter < 10` declares that this `for` loop continues to execute as long as the value of counter is less than 10.
- The middle part is the **for condition**: `counter < 10` declares that this `for` loop continues to execute as long as the value of `counter` is less than 10.
- The final part is the **for iterator**: `counter++` specifies how to modify the loop variable after executing the block following the `for` statement. Here, it specifies that `counter` increments by 1 each time the block executes.

Experiment with these conditions yourself. Try each of the following changes:
Expand All @@ -115,21 +125,21 @@ A `while`, `do`, or `for` loop can be nested inside another loop to create a mat

One `for` loop can generate the rows:

:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="Rows":::
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="Rows":::

Another loop can generate the columns:

:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="Columns":::
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="Columns":::

You can nest one loop inside the other to form pairs:

:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="Nested":::
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="Nested":::

You can see that the outer loop increments once for each full run of the inner loop. Reverse the row and column nesting, and see the changes for yourself.
You can see that the outer loop increments once for each full run of the inner loop. Reverse the row and column nesting, and see the changes for yourself. When you're done, place the code from this section in a method called `ExploreLoops()`.

## Combine branches and loops

Now that you saw the `if` statement and the looping constructs in the C# language, see if you can write C# code to find the sum of all integers 1 through 20 that are divisible by 3. Here are a few hints:
Now that you used the `if` statement and the looping constructs in the C# language, see if you can write C# code to find the sum of all integers 1 through 20 that are divisible by 3. Here are a few hints:

- The `%` operator gives you the remainder of a division operation.
- The `if` statement gives you the condition to see if a number should be part of the sum.
Expand All @@ -142,11 +152,13 @@ Did you come up with something like this?
<!-- markdownlint-disable MD033 -->
<details>

:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="Challenge":::
:::code language="csharp" source="./snippets/BranchesAndLoops/branches-loops.cs" id="Challenge":::
</details>
<!-- markdownlint-enable MD033 -->

You completed the "branches and loops" interactive tutorial. You can select the **list collection** link to start the next interactive tutorial, or you can visit the [.NET site](https://dotnet.microsoft.com/learn/dotnet/hello-world-tutorial/intro) to download the .NET SDK, create a project on your machine, and keep coding. The "Next steps" section brings you back to these tutorials.
You've completed the "branches and loops" tutorial.

You completed the "branches and loops" tutorial. You can select the **list collection** link to start the next tutorial.

You can learn more about these concepts in these articles:

Expand Down
Loading
Loading