0

if I can use for loop as while loop... why would I need while loop?

25th Sep 2016, 5:13 AM
Or Orsatti
Or Orsatti - avatar
3 ответов
+ 4
In for loop, you exactly know how many times the code will execute. On the other hand you dont know exactly how many times the statement will execute. for example in a game.. while (player_alive=="Alive") user dont know when would he die.
25th Sep 2016, 9:48 AM
Umair Ahmad
Umair Ahmad - avatar
0
A "for" loop cannot do anything that a "while" loop can't, a "while" loop cannot do anything that a "for" loop can't, but sometimes a "for" loop is more elegant, and sometimes you don't need the initialisation and the increment (and if you don't, you should use the "while" loop). For a loop that repeats forever, use: while(true) { // do something }
29th Sep 2016, 10:43 AM
Samuel Neo
Samuel Neo - avatar
0
Another great example would be hammering a nail. You don't know that the nail will go in in 'x' number of times; so you use the while statement.
10th Oct 2016, 7:34 AM
Dhruv R Pisharody