The two important types of loops in programming are the while loop, and the perhaps somewhat more complicated for loop. The while loop is simply the key word “while”, followed by a condition in parentheses, then a group of actions all contained in brackets.
Like so:
while(Sleeping){
Play_Soft_Music(); //Gotta have that soft music.
}
However, there is a better type of loop that can be used in place of this: the for loop. Here’s how one works: think of it as a function; you type the keyword ‘for’, then in parentheses, you initialize your counting variable, then a semi-colon, then the condition that must be met for the loop to run through each time, then another semi-colon, and finally, the increment statement. Here’s an example:
for (itemsPlaced=0; itemsPlaced < totalItems; itemsPlaced++){
//Place items throughout the level.
}
This code counts the number of itemsPlaced, starting at 0 when we begin. The code continues as long as the number of items placed is less than the number of total items. Each time we go through the loop, we increase the value of itemsPlaced. Although the use of for loops still may not be immediately apparent to you now, you’ll see in time how useful they can be, ESPECIALLY in conjunction with arrays and setting up each value within the array like so:
for (x=0; x<5; x++){
MyArray [x] = x*5; //Assign the xth element of the array to x*5
//This produces 0, 5, 10, 15, 20, etc.
}