Loops are how we repeat the same part of the code more than once. This can simply mean doing the same thing until the code being looped over prompts the loop to end or it could be a predetermined number of times as specified by the loop code itself.

  • The courses above are up to 95% off - by clicking on ad above.


About this tutorial

Skill level 1
Time to read: 10 minutes

New Concepts:

  1. C#  while loops
  2. Breaking out of a loop
  3. C# for loops

Projects related to or that demonstrate these concepts

We will look at two types of loop that C# offers us. They are known as while loops and for loops.

While loops

While loops are quite straightforward to understand. Think back to the if statements and their conditions. We could put the same combination of operators and variables in the conditional expression of a while loop. We use these expressions to decide whether, or for how long, the code in the while loop will execute. A look at some actual code will help.

int a = 5;

while(a > 0){

	a--;
	// a decreases by one each pass through the loop

}

This is what is happening. Outside of the while loop int a is declared and initialized to 5. Then the while loop begins. Its condition is a > 0. So the while loop will continue looping through the code in its body until the condition evaluates to false. So the code above will execute 5 times.

On the first time through the loop a equals 5 then 4 then 3 etc. But once a is equal to zero it is no longer greater than zero. Then the execution will break out of the while loop and continue to run after the closing curly brace }.

Just like an if statement, it is possible that the while loop will not execute even once. Take a look at this while loop code.

int v = 5;

while(v > 5){

	// more code here.
	// but it will never run unless v is greater than 5

}

Also, there is no limit to the complexity of the expression or the amount of code that can go in the loop body.

int playerLives = 3;
int alienShips = 10;

while(playerLives !=0 && alienShips !=0 ){

	// Entire game code here.
	// ...
	// ...
	// etc.

}

//continue here when either playerLives or alienShips = 0

The above while loop would continue to execute until either playerLives or alienShips was equal to zero. As soon as one of those conditions occurred the expression would evaluate to false and the program would continue to execute from the first line of code after the loop.

It is worth noting that once the body of the loop has been entered it will always complete, even if the expression evaluates to false part way through. This is because it is not tested again until the code tries to start another pass. For example.

int x = 1;

while(x > 0){

	x--;
	// x is now 0 so the condition is false
	// But this line still runs
	// and this one
	// and me!

}

The above loop body will execute exactly once. We can also set up a while loop that will run forever, unsurprisingly called an infinite loop. Here is one.

int score = 0;

while(true){

	score++;
	// Whoopie! High score coming!

}

  • The courses above are up to 95% off - by clicking on ad above.

Breaking out of a loop

We might use an infinite loop like this so that we can decide when to exit the loop from within its body. We would do this by using the break keyword when we are ready to leave the loop body. Like this next C# code sample.

int x = 0;

while(true){

	x++; // I am going to get mighty big!

	break; // No you're not haha
	// Code doesn't reach here

}

And you might have been able to guess that we can combine any of the decision making tools like if, else with our while loops and the for loop we will look at in a minute. For example, look at this C# code.

int x = 0;
int tooBig = 10;

while(true){

	x++; //I am going to get mighty big!
	if(x == tooBig){
		break;
	} // No you're not haha.

	//code reaches here only until x = 10

}

It would be simple to go on for many more pages demonstrating the versatility of while loops but at some point we want to start making games. So here is one last concept concerned with loops.

C# for loops

C# for loops have a slightly more complicated syntax than while loops. This is because they take three parts to set up. Have a look at the code first then we can discuss it.

for(int i = 0; i < 10; i ++){

	// Something that needs to happen 10 times goes here

}

Here is what all the parts of the condition do.

for(declaration and initialization; condition; change after each pass through loop)

To clarify further we have:
• Declaration and initialization: We create a new int variable i and initialize it to .
• Condition: Just like the other loops, it refers to the condition that must be true for the loop to continue.
• Change after each pass through loop: In the example i++ means that 1 is added/incremented to i on each pass.

for(int i = 10; i > 0; i--){

	// countdown

}

// blast off x = 0

The for loop takes control of initialization, condition evaluation as well as the control variable, upon itself.

Now we know how we can repeat sections of our code we can move on to another C# topic. If you remember we used the Start method in the Unity & C# part 1 project we will now examine methods in much more detail. Organizing C# game code with methods.