+ 1

How can you set the number of loops in the "while" loop?

I don't get it. How?

14th Dec 2016, 8:21 AM
Sir S Yolo
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.
14th Dec 2016, 9:15 AM
Kerrash
Kerrash - avatar
+ 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.
14th Dec 2016, 10:02 AM
Antek
0
Thanks so much!
14th Dec 2016, 11:07 AM
Sir S Yolo
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! ... }
14th Dec 2016, 12:17 PM
Ettienne Gilbert
Ettienne Gilbert - avatar
0
Jesus, you can't ask a question here without getting an answer in, like, two seconds! Thank you!
14th Dec 2016, 1:19 PM
Sir S Yolo