Game Development Reference
In-Depth Information
Listing 6-6. A for Loop Over an Array
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
unsigned int array[10];
for (unsigned int i=0; i<10; ++i)
{
array[i] = i * 2;
cout << "Loop Iteration: " << array[i] << endl;
}
return 0;
}
This example shows how we can use the for loop index variable to index into an array. Here we
initialize each element of the array via iteration and print the results to the console. We can use this
technique to execute code on each element of an array, which is especially useful when writing
games.
Sometimes we do not know beforehand how many iterations of a given loop we would like to
execute. Thankfully C++ provides us with another loop statement that can handle this case, the
while loop.
The while Loop
A while loop just executes until its accompanying statement evaluates to false. Listing 6-7 shows a
simple example.
Listing 6-7. A while Loop
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
unsigned int array[10];
unsigned int count = 0;
while (count < 10)
{
array[count] = count * 2;
cout << "Loop Iteration: " << array[count++] << endl;
}
return 0;
}
 
Search WWH ::




Custom Search