Skip to content

Commit d9fbd6d

Browse files
committed
First edit pass on branches and loops
First edit pass updating the branches and loops tutorial.
1 parent f9f2d0e commit d9fbd6d

File tree

3 files changed

+84
-38
lines changed

3 files changed

+84
-38
lines changed

docs/csharp/tour-of-csharp/tutorials/branches-and-loops.md

Lines changed: 42 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,103 +1,106 @@
11
---
22
title: Branches and loops - Introductory tutorial
33
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.
4-
ms.date: 03/06/2025
4+
ms.date: 12/03/2025
55
---
66
# C# `if` statements and loops - conditional logic tutorial
77

88
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.
99

10-
> [!TIP]
11-
>
12-
> 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.
10+
TODO: Build an app, create a file.
1311

14-
Run the following code in the interactive window. Select **Run**:
12+
Open *Program.cs* in your favorite editor, and replace the contents with the following code:
1513

16-
:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="FirstIf":::
14+
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="FirstIf":::
1715

18-
Modify the declaration of `b` so that the sum is less than 10:
16+
Try this code by typing `dotnet run` in your console window. 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:
1917

2018
```csharp
2119
int b = 3;
2220
```
2321

24-
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.
22+
Type `dotnet run` 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've only written one of the possible branches for an `if` statement: the true branch.
2523

2624
> [!TIP]
27-
>
28-
> 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.
29-
30-
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.
25+
> 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. The compiler error can usually help you find the problem.
3126
32-
This process of checking conditions and executing statements based on those conditions is powerful. Let's explore more.
27+
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.
3328

3429
## Make if and else work together
3530

36-
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:
31+
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):
3732

38-
:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="IfAndElse":::
33+
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="IfAndElse":::
3934

40-
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.
35+
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.
4136

4237
> [!IMPORTANT]
43-
>
4438
> 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.
4539
46-
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.
40+
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:
4741

4842
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="IncludeBraces":::
4943

5044
> [!TIP]
51-
>
5245
> Through the rest of this tutorial, the code samples all include the braces, following accepted practices.
5346
54-
You can test more complicated conditions:
47+
You can test more complicated conditions. Add the following code after the code you've written so far:
5548

5649
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="ComplexConditions":::
5750

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

6053
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 `}`.
6154

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

6457
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="UseOr":::
6558

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

61+
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:
62+
63+
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="Refactor":::
64+
65+
Comment out the call to `ExploreIf()`. It will make the output less cluttered as you work in this section:
66+
67+
```csharp
68+
//ExploreIf();
69+
```
70+
71+
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.
72+
6873
## Use loops to repeat operations
6974

70-
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:
75+
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`:
7176

72-
:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="WhileLoop":::
77+
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="WhileLoop":::
7378

7479
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.
7580

76-
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.
81+
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.
7782

7883
> [!IMPORTANT]
79-
>
80-
> 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
81-
> not demonstrate that, because the engine that runs your code times out and you see no output from your program.
84+
> 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.
8285
83-
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:
86+
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:
8487

8588
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="DoLoop":::
8689

87-
This `do` loop and the earlier `while` loop work the same.
90+
This `do` loop and the earlier `while` loop produce the same output.
8891

8992
Let's move on to one last loop statement.
9093

9194
## Work with the for loop
9295

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

95-
:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="ForLoop":::
98+
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="ForLoop":::
9699

97100
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:
98101

99102
- The first part is the **for initializer**: `int counter = 0;` declares that `counter` is the loop variable, and sets its initial value to `0`.
100-
- 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.
103+
- 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.
101104
- 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.
102105

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

116119
One `for` loop can generate the rows:
117120

118-
:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="Rows":::
121+
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="Rows":::
119122

120123
Another loop can generate the columns:
121124

@@ -125,11 +128,11 @@ You can nest one loop inside the other to form pairs:
125128

126129
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="Nested":::
127130

128-
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.
131+
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()`.
129132

130133
## Combine branches and loops
131134

132-
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:
135+
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:
133136

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

145-
:::code language="csharp" interactive="try-dotnet-method" source="./snippets/BranchesAndLoops/Program.cs" id="Challenge":::
148+
:::code language="csharp" source="./snippets/BranchesAndLoops/Program.cs" id="Challenge":::
146149
</details>
147150
<!-- markdownlint-enable MD033 -->
148151

149-
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.
152+
You've completed the "branches and loops" tutorial.
153+
154+
You completed the "branches and loops" tutorial. You can select the **list collection** link to start the next tutorial.
150155

151156
You can learn more about these concepts in these articles:
152157

docs/csharp/tour-of-csharp/tutorials/snippets/BranchesAndLoops/BranchesAndLoops.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
5-
<TargetFramework>net9.0</TargetFramework>
5+
<TargetFramework>net10.0</TargetFramework>
66
<ImplicitUsings>enable</ImplicitUsings>
77
<Nullable>enable</Nullable>
88
</PropertyGroup>

docs/csharp/tour-of-csharp/tutorials/snippets/BranchesAndLoops/Program.cs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,47 @@
99
PageFive();
1010
Challenge();
1111

12+
// <Refactor>
13+
ExploreIf();
14+
15+
void ExploreIf()
16+
{
17+
int a = 5;
18+
int b = 3;
19+
if (a + b > 10)
20+
{
21+
Console.WriteLine("The answer is greater than 10");
22+
}
23+
else
24+
{
25+
Console.WriteLine("The answer is not greater than 10");
26+
}
27+
28+
int c = 4;
29+
if ((a + b + c > 10) && (a > b))
30+
{
31+
Console.WriteLine("The answer is greater than 10");
32+
Console.WriteLine("And the first number is greater than the second");
33+
}
34+
else
35+
{
36+
Console.WriteLine("The answer is not greater than 10");
37+
Console.WriteLine("Or the first number is not greater than the second");
38+
}
39+
40+
if ((a + b + c > 10) || (a > b))
41+
{
42+
Console.WriteLine("The answer is greater than 10");
43+
Console.WriteLine("Or the first number is greater than the second");
44+
}
45+
else
46+
{
47+
Console.WriteLine("The answer is not greater than 10");
48+
Console.WriteLine("And the first number is not greater than the second");
49+
}
50+
}
51+
// </Refactor>
52+
1253
void PageOne()
1354
{
1455
// <FirstIf>

0 commit comments

Comments
 (0)