+ 5
What is the difference between "for" loop and "while" loop?
Why do we need "for" loop when we have "while" loop and vice versa?
7 ответов
+ 19
Because programming is supposed to reflect your problem-solving skills in real life.
There are better ways to explain yourself. E.g. How long do you work in the office?
- You can say that you work for 5 days starting from Monday.
- You can also say that you work while it isn't a holiday.
Some conditions will cause you to pick either one over another. This depends on how well you know the situation. Keeping your code as readable as possible depending on the situation is important for code maintainability.
+ 8
A for loop, loops until a certain time. Where as with a while loop, you may not know how many times you'd like it to loop so you say while. For example if you were making a game where you want it to loop through something until the player dies, you'd use a while loop because you wouldn't know when the player is going to die.
The good thing about a for loop is that you can make something happen for a certain time. For example you may want a sprite to walk across the screen for a certain amount of steps before it stops.
+ 5
Yeah.... I know this. But why do we need while when we have for loop?
+ 5
Hatsy Rei, u mean I can choose one of them, according with my situation (which one is more suitable in a some situation)?
Anyway, thanks!
+ 3
They work on the same principle. The only difference, in the languages I know, is that the for already includes in its syntax a code to go increasing a counter.
Example:
for(int i=0; i<n; i++) {
//code
}
The while use the counter in the last line.
Example:
int i=0;
while (i<n) {
//code
i++;
}
+ 2
Basically, for has the declaration, verification and increment at first line while while has only verification.