Branches and loops

This quick start teaches you how to write code that examines variables and changes execution path based on those variables. You'll use your browser to write C# interactively and see the results of compiling and running your code. This quick start contains a series of lessons that explore branching and looping constructs in C#. These lessons teach you the fundamentals of the C# language.

You will learn how to...

Make decisions using the if statement

Run the following code in the interactive window. To do that, type the following code block in the interactive window and click the Run button:

int a = 5;
int b = 6;
if (a + b > 10)
    Console.WriteLine("The answer is greater than 10.");

Modify the declaration of b so that the sum is less than 10:

int b = 3;

Click 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'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'll make mistakes when you write code. The compiler will find 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 will help you learn the structure of C# code.

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 is skipped.

This process of checking conditions and executing statements based on those conditions is very powerful. Let's explore more.

Note

This online coding experience is in preview mode. If you encounter problems, please report them on the dotnet/try repo.

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 this:

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 else keyword executes only when the condition being tested is false. Combining if and else with boolean conditions provides all the power you need.

Important

The indentation under the if and else statements is for human readers. The C# language doesn't treat indentation or whitespace as significant. The statement following the if or else keyword will be executed based on the condition. All the samples in this quick start follow a common practice to indent lines based on the control flow of statements.

Because indentation is not 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 just created. Try it.

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 quick start, the code samples all include the braces, following accepted practices.

You can test more complicated conditions:

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 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");
}

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":

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("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");
}

Note

This online coding experience is in preview mode. If you encounter problems, please report them on the dotnet/try repo.

Use loops to repeat operations

Another important concept to create larger programs is loops. You'll use loops to repeat statements that you want executed more than once. Try this code in the interactive window:

int counter = 0;
while (counter < 10)
{
  Console.WriteLine($"Hello World! The counter is {counter}");
  counter++;
}

The while statement checks a condition and executes the statement following the while. It will repeat 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.

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 will time out and you'll see no output from your program.

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:

int counter = 0;
do
{
  Console.WriteLine($"Hello World! The counter is {counter}");
  counter++;
} while (counter < 10);

This do loop and the earlier while loop work the same.

Let's move on to one last loop statement.

Note

This online coding experience is in preview mode. If you encounter problems, please report them on the dotnet/try repo.

Work with the for loop

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

for(int counter = 0; counter < 10; counter++)
{
  Console.WriteLine($"Hello World! The counter is {counter}");
} 

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

The first part is the for initializer: for 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 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 should be incremented by 1 each time the block executes.

Experiment with these yourself. Try each of the following:

  • Change the initializer to start at a different value.
  • Change the condition to stop at a different value.

When you're done, let's move on to write some code yourself to use what you've learned.

Note

This online coding experience is in preview mode. If you encounter problems, please report them on the dotnet/try repo.

Combine branches and loops

Now that you've seen 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.
  • The for loop 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.

Note

This online coding experience is in preview mode. If you encounter problems, please report them on the dotnet/try repo.

Congratulations!

You've completed the "branches and loops" quick start.

You can continue these quick starts on your own development environment. Learn the basics of local development and then pick a quick start. You can try this same exercise, move directly to the next quick start, or start again at with the numbers in C# quickstart.

You can learn more about these concepts in these topics:

If and else statement
While statement
Do statement
For statement

You learned how to...

Next Tutorial

Interpolated strings in C#

Contributors

  • dotnet bot
  • Bill Wagner
  • Ron Petrusha
  • Maira Wenzel
  • Zoltán Bedi

See all 6 contributors or become a contributor by suggesting improvements on github.