+ 1
How can you set the number of loops in the "while" loop?
I don't get it. How?
5 Answers
+ 2
You need to initialize a variable before the loop that keeps count of the number of times the code has ran. So starting at '0' and with a while (x < 5) will keep running whilst x is less than 5. Add 1 to it each time and the loop should run 6 times.
+ 1
The other answer is great but I just want to add that the "for" loop is designed specifically for this purpose when you know exactly how many iterations of a loop you want. So, while "while" loops are similarly controllable with a pre-initialized "counter" variable, they are very useful when the number of potential iterations is unknown and variable, leaving "for" loops to commonly handle pre-determined numbers of loops.
0
Thanks so much!
0
To add to Antek's answer:
The way this is done is to use a 'break' statement. For example:
while(true) { //Loop forever...
...
if(/*some condition is true*/)
break; //Don't loop forever!
...
}
0
Jesus, you can't ask a question here without getting an answer in, like, two seconds! Thank you!