I understand how for loops work. They're used to list integers if the integer meets the requirements. I understand that. (Question: Are they only for numerical values or can they be used for alphabetical values?)
But, what exactly and when exactly would I use that for gaming? The only time I can think of for loops as useful is when you would list high scores after a game over...
Loops are useful whenever you want things to happen more than once. It allows you to get something to repeat without having to repeat the code. In games you often have something called a game loop where you handle input, update the game logic and draw the graphics on the screen, and because you want this to happen over and over again you put it in a loop.
1 2 3 4
while (game is running)
handle input
update game
draw game
Each and every one of these sub-tasks could contain loops as well. When handling input you might want to use a loop to loop over all the new input events that has been generated since last time. When updating the game logic you might want to loop over all players (and enemies) in the game to update their positions, and similarly when you draw the game you probably want to loop over everything that needs to be drawn.
@Peter
Yeah, I understand that loops in general are important. I use while loops a lot, but what about for loops. When exactly would I need those if they just list numerical values that meet the requirements apprehended?
They're used to list integers if the integer meets the requirements.
While this is their main use, in practice they have a very wide variety of applications. Generally, you can use for loops to traverse any kind of structure that can be mapped onto a list. Even more generally, you can even use for loops for things that have nothing to do with traversal:
1 2 3
//WARNING: contrived example follows!
for (int n = rand();;)
std::cout <<rand()*n<<std::endl;
But, what exactly and when exactly would I use that for gaming?
For example,
1 2 3
for (polygon_iterator it = 3d_model.polygons.begin(); it != 3d_mode.polygons.end(); ++it){
it->make_blue();
}
@Helios So they can be used for movement is basically what you're saying? I'm also pretty new to coding in C++ so your last code confuses me a little bit. It is being incremented every time it does not doesn't equal 3d_mode.polygons.end()? Is that for traversing through a plane?
@Mutexe I always thought they had different uses. I'm more comfortable with while loops as of now just because I've been using them longer. Do different loops execute faster than others?
@Jakee @Ganado
Wow, I never knew that. I was reading up more on pointers and arrays and I didn't realize they were used in unison with for loops. I also didn't know the spawn code was a for loop lol.