PDA

View Full Version : loops



Master Maniac
04-29-2008, 06:18 PM
...else?
for?

i understand while loops, but what do the others do? and what are all the others?

Joe123
04-29-2008, 06:28 PM
else isn't a loop.


if(thisistrue){
//do this
}
else{ //if it's not true
//do this
}


for is a temporary loop:


int i;
for(i = 0; i < 10; i ++){
//do this 10 times
}

The for loop uses an integer, and takes 3 inputs.
The first is the 'i = 0;'. This sets the integer to it's first value. You could put any number there you like, but 0 is probably the most frequent.
The second is the 'i < 10'. This means the loop will continue until the integer 'i' hits 10.
The third is the 'i ++'. This part says that the integer 'i' will be incremented by 1 each time the loop runs, so it will run 10 times (including time 0).


int i;
for(i = 20; i > 5; i -= 2){
//do this 13 times
}

You don't have to set it up like in that first example though.




int i;
for(i = 0; i < 10; i ++){
//do this 10 times
}

i = 0;
while(i < 10){
//do this 10 times
i++;
}

Those two are equivalent.




At first, the for loop seems a little redundant, but where it picks up its usefulness is when you actually use the integer 'i' in a function inside the loop.



int i;
for(i = 0; i < 10; i ++){
Link->X = 20+i;
Waitframe();
}

This is a pretty lame example, but if I use a better one it might be a bit overcomplicated.
Anyway, this will set Link's X to 20, then move him across by 1 pixel each frame for 10 frames.

Master Maniac
04-29-2008, 06:40 PM
ahh... ok thank you =)

Joe123
04-29-2008, 06:52 PM
No problem ;-)