The right one

--Originally published at Codebuster

Okay, so we have all this incredibly useful loops, but how will we know which to use in each program?

No, its not decided by random, nor is it something to panic over. In order to know which repetition to use all you have to do is go back to what they mean, and analize what you want to achieve with your program, what kind of algorithm you want to use, so its important to remember:

  • While: is used when you want to do something until a condition is met, but you don’t really know how many times the loop will repeat itself. It is very common when using it with input from the user, since you don’t know how many tries it will get them to meet your demand.
  • For: For is usually present when we want to do something to every character, string, item and so forth. So as you see, you generally already know how many times the loop will repeat itself

So there it goes, not as hard at all.

iejfioejiofw.gif

Ps: here is a kind of long (but nice) video discussing differences between for and while looks: