0
if I can use for loop as while loop... why would I need while loop?
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.
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
}
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.