إشعار
يتطلب الوصول إلى هذه الصفحة تخويلاً. يمكنك محاولة تسجيل الدخول أو تغيير الدلائل.
يتطلب الوصول إلى هذه الصفحة تخويلاً. يمكنك محاولة تغيير الدلائل.
Tutorial: C#
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.
In this tutorial, you:
- Launch a GitHub Codespace with a C# development environment.
- Explore
ifandelsestatements. - Use loops to repeat operations.
- Work with nested loops.
- Combine branches and loops.
Prerequisites
You must have one of the following options:
- A GitHub account to use GitHub Codespaces. If you don't already have one, you can create a free account at GitHub.com.
- A computer with the following tools installed:
- The .NET 10 SDK.
- Visual Studio Code.
- The C# DevKit.
Use if statements
To start a GitHub Codespace with the tutorial environment, open a browser window to the tutorial codespace repository. Select the green Code button, and the Codespaces tab. Then select the + sign to create a new Codespace using this environment. If you completed other tutorials in this series, you can open that codespace instead of creating a new one.
When 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:
int a = 5; int b = 6; if (a + b > 10) Console.WriteLine("The answer is greater than 10.");Try this code by typing the following command in the integrated terminal:
cd tutorials dotnet branches-loops.csYou should see the message "The answer is greater than 10." printed to your console.
Modify the declaration of
bso that the sum is less than 10:int b = 3;Type
dotnet branches-loops.csagain 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 only wrote one of the possible branches for an
ifstatement: the true branch.
Tip
As you explore C# (or any programming language), you might make mistakes when you write code. The compiler finds and reports 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.
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 an else branch.
Add the last two lines in the following code snippet (you should already have the first four):
int a = 5; int b = 3; if (a + b > 10) Console.WriteLine("The answer is greater than 10"); else Console.WriteLine("The answer is not greater than 10");The statement following the
elsekeyword executes only when the condition being tested isfalse. Combiningifandelsewith boolean conditions provides all the power you need to handle both atrueand afalsecondition.Important
The indentation under the
ifandelsestatements is for human readers. The C# language doesn't treat indentation or white space as significant. The statement following theiforelsekeyword 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 allifandelseclauses.The following example is the same as what you created in the previous example, with the addition of
{and}. Modify your code to match the following code:int a = 5; int b = 3; if (a + b > 10) { Console.WriteLine("The answer is greater than 10"); } else { Console.WriteLine("The answer is not greater than 10"); }Tip
Through the rest of this tutorial, the code samples all include the braces, following accepted practices.
You can test more complicated conditions. Add the following code after the code you wrote so far:
int a = 5; int b = 3; int c = 4; if ((a + b + c > 10) && (a == b)) { Console.WriteLine("The answer is greater than 10"); Console.WriteLine("And the first number is equal to the second"); } else { Console.WriteLine("The answer is not greater than 10"); Console.WriteLine("Or the first number is not equal to the second"); }The
==symbol tests for equality. Using==distinguishes the test for equality from assignment, which you saw ina = 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". Add the following code after what you wrote so far:if ((a + b + c > 10) || (a == b))Modify the values of
a,b, andcand 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:ExploreIf(); void ExploreIf() { int a = 5; int b = 3; if (a + b > 10) { Console.WriteLine("The answer is greater than 10"); } else { Console.WriteLine("The answer is not greater than 10"); } int c = 4; if ((a + b + c > 10) && (a > b)) { Console.WriteLine("The answer is greater than 10"); Console.WriteLine("And the first number is greater than the second"); } else { Console.WriteLine("The answer is not greater than 10"); Console.WriteLine("Or the first number is not greater than the second"); } if ((a + b + c > 10) || (a > b)) { Console.WriteLine("The answer is greater than 10"); Console.WriteLine("Or the first number is greater than the second"); } else { Console.WriteLine("The answer is not greater than 10"); Console.WriteLine("And the first number is not greater than the second"); } }Comment out the call to
ExploreIf(). It makes the output less cluttered as you work in this section://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 for creating larger programs is loops. Use loops to repeat statements that you want to execute more than once.
Add this code after the call to
ExploreIf:int counter = 0; while (counter < 10) { Console.WriteLine($"Hello World! The counter is {counter}"); counter++; }The
whilestatement checks a condition and executes the statement following thewhile. 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 thecountervariable is the increment operator. It adds 1 to the value ofcounterand stores that value in thecountervariable.Important
Make sure that the
whileloop condition changes to false as you execute the code. Otherwise, you create an infinite loop where your program never ends. That behavior isn't demonstrated in this sample, because you have to force your program to quit by using CTRL-C or other means.The
whileloop tests the condition before executing the code following thewhile.The
do...whileloop executes the code first, and then checks the condition. The do while loop is shown in the following code:int counter = 0; do { Console.WriteLine($"Hello World! The counter is {counter}"); counter++; } while (counter < 10);This
doloop and the earlierwhileloop 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:
for (int counter = 0; counter < 10; counter++) { Console.WriteLine($"Hello World! The counter is {counter}"); }The preceding
forloop does the same work as thewhileloop and thedoloop you already used. Theforstatement has three parts that control how it works:- The first part is the for initializer:
int counter = 0;declares thatcounteris the loop variable, and sets its initial value to0. - The middle part is the for condition:
counter < 10declares that thisforloop continues to execute as long as the value ofcounteris less than 10. - The final part is the for iterator:
counter++specifies how to modify the loop variable after executing the block following theforstatement. Here, it specifies thatcounterincrements by 1 each time the block executes.
- The first part is the for initializer:
Experiment with these conditions yourself. Try each of the following changes:
- Change the initializer to start at a different value.
- Change the condition to stop at a different value.
When you're done, move on to the next section to write some code yourself and use what you learned.
There's one other looping statement that isn't covered in this tutorial: the foreach statement. The foreach statement repeats its statement for every item in a sequence of items. You most often use it with collections. It's covered in the next tutorial.
Created nested loops
You can nest a while, do, or for loop inside another loop to create a matrix by combining each item in the outer loop with each item in the inner loop. Let's build a set of alphanumeric pairs to represent rows and columns.
Add the following
forloop that generates the rows:for (int row = 1; row < 11; row++) { Console.WriteLine($"The row is {row}"); }Add another loop to generate the columns:
for (char column = 'a'; column < 'k'; column++) { Console.WriteLine($"The column is {column}"); }Finally, nest the columns loop inside the rows to form pairs:
for (int row = 1; row < 11; row++) { for (char column = 'a'; column < 'k'; column++) { Console.WriteLine($"The cell is ({row}, {column})"); } }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 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
ifstatement gives you the condition to see if a number should be part of the sum. - The
forloop can help you repeat a series of steps for all the numbers 1 through 20.
Try it yourself. Then check how you did. As a hint, you should get 63 for an answer.
Did you come up with something like this?
int sum = 0;
for (int number = 1; number < 21; number++)
{
if (number % 3 == 0)
{
sum = sum + number;
}
}
Console.WriteLine($"The sum is {sum}");
You completed the "branches and loops" tutorial. You can learn more about these concepts in these articles:
Cleanup resources
GitHub automatically deletes your Codespace after 30 days of inactivity. If you plan to explore more tutorials in this series, you can leave your Codespace provisioned. If you're ready to visit the .NET site to download the .NET SDK, you can delete your Codespace. To delete your Codespace, open a browser window and navigate to your Codespaces. You should see a list of your codespaces in the window. Select the three dots (...) in the entry for the learn tutorial codespace and select delete.