Novalyphe
Number of posts: 14 Location: U.K. Points: Registration date: 2008-05-19
 | Subject: Basic Looping Sun May 18, 2008 11:19 pm | |
| The two most popular loop structures are for and while. in a while loop is written as such: | Code: | while (condition) { Code }
|
The while loops checks whether or not the condition is true or false, if it is true then the code in the braces in executed and then the condition is checked again after each execution. If the condition is false then the code is skipped and the program continues from the closing brace.
A for loop is slightly different and the syntax is:
| Code: | for (iterator; condition; incrementer) { code }
|
for loops are useful when you want to step through arrays or when you want a user to be able to define how many iterations of a piece of code will occur. They work by checking if the condition is true, executing the code if it is, and then performing the incrementer. Once the condition becomes false then the program continues from then closing brace.
If you want the piece of code to be executed at least once (regardless of the status of the condition), then the most likely choice would be a do-while loop. This works in a very similar manner to a while loop except you would put do at the start of your code block and then your while (condition at the end).
| Code: | do { code } while (condition);
|
do-while loops can be useful when you want a message to repeat until a certain input is provided, as the message will always be printed the first time, but will only be repeated if an incorrect input is entered.
Hope this helps. Any questions feel free to PM. |
|
Akira Nami
Number of posts: 2 Points: Registration date: 2008-05-18
 | Subject: Re: Basic Looping Sun May 18, 2008 11:28 pm | |
| Honestly, I love the while and for loops... the do loops make me hate c++ because of how they are... then again they do make stuff easier in some cases. |
|
TheDolph
Number of posts: 2 Points: Registration date: 2008-05-21
 | Subject: Re: Basic Looping Thu May 22, 2008 7:32 am | |
| while(1) { malloc(5000); } lol, nice loop tute btw |
|