Hey there, Gamers and Game Makers! in this week's blog, we're going to continue our introduction to C# in visual studio by looking at loops. Specifically a for loop and a while loop. Loops are used when we want to repeat a sequence of code several times over as long as a particular condition is met. The first loop we'll be looking at is the for loop. The for loop is used when we know the sequence is to be executed a certain number of times. For example, we might only want it to run as long as an index is below a certain value. A for loop starts off with the keyword for followed by the condition. With for loops we tend to have an index variable that keeps count of the iterations through the loop along with what's called an exit condition. The exit condition is what the index is compared too. If we did not have an exit condition, the loop would never end. The following for loop iterates through the loop as long as the index is less than the count variable. It writes out the current index step each time. Once we reach the exit condition, the loop ends. A while loop can work in a very similar way. However there are a few very important differences. As you can see, I've initialized my index variable outside the loop and the increment of the index is handled after each execution of the code. Same as before, if we don't have an exit condition, the loop would never end. Try coming up with your own loops and see what results you get.
Until next time! |
Archives
April 2019
Categories |