Conditional statements in C#

3D Game Design with Unity

🕑 This lesson will take about 18 minutes

There are two main types of loops you can use in C# to repeat sections of code. These are called the while loop and for loop.

while loop

The while loop is the easiest type of loop to use for the repetition of code. The basic syntax is as follows:

while(<condition>)
{
// do something
}

It looks very similar to an if statement. However, an if statement only runs the code it contains once. A while loop will run the code that it contains over and over again until the specified condition evaluates to false. Any code inside the { and } brackets will run inside the loop.

Here is an example of a while loop in the C# language:

int count = 0;
 
while(count <10)
{
 count++;
}
print(count);

In the example above, the count variable is initially set to 0. The loop will check if the count variable is less than 10. If it is not less than 10, it will add 1 to the count variable. This will keep repeating until the condition evaluates to false when the count variable’s value is no longer less than 10. When this occurs, the loop will end and the value of the count variable will be displayed (on the last line of the code which is outside of the loop).

It is important that a condition be specified that will allow the loop to end, otherwise, the loop will never end! This is known as an infinite loop.

for loop

The for loop is a little more complex than the while loop but at its simplest level, it is very easy to set up. The syntax looks like this:

for(<initialise counter>;<condition>;<increment the counter>)
{
// do something
}

Semi-colons separate three important components of the for loop inside the ( and ) brackets. The first part is where a counter is initialised, for example, int i=0. The second part is where the condition is specified, for example, i<10. The third part is how much to increment the counter by each time the loop runs (each iteration), for example, i++ would increment the counter by 1.

for loops are great for using as counters to repeat a section of code a certain amount of times. They are also great for repeating operations on each item in an array (looping through an array) or each character in a string. Below is an example of a for loop.

for(int i=0; i <10; i++)
{
 print(i);
 // the value of i will be displayed for each iteration of the loop
}

Next lesson: Methods in C#