Sania Syed wrote:Oh I think I got what you mean - so what exactly is the difference between for loop and while loop ?
Nothing, really. Any for loop can be turned into an equivalent while loop and vice versa.
For loops are traditionally used with a counter, when you're going to do something a specific number of times, and while loops are traditionally used when you don't know at the start of the loop how many iterations there will be and you're going to just keep going until some condition other than a simple counter is met. There's no execution advantage of one over the other, but if you start using them in non-standard ways, it can confuse people who read your code--including you.
Generally speaking, there is no difference. I believe all three loops (for, while, do-while) can all be interchanged with each other.
However, CONVENTIONS say that if you know exactly how many times a loop should run (i.e. iterating through a collection), a for-loop should be used. If you don't know how many times (i.e. validating user input, reading from a file, etc), a while loop should be used.
These aren't hard, fast rules, but most programmers would expect these to be followed, just like a class name should start with a capital letter.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Sania Syed wrote:I am trying to understand for loops...
There is another advantage of for loops, and that is that their syntax allows you to define variables entirely within the scope of the loop itself; so, for example, your loop could have (and probably should have) been written:and that's why I generally prefer them - sometimes even in cases where others might write a while loop.
Isn't it funny how there's always time and money enough to do it WRONG?
Artlicles by Winston can be found here