Why we have "while" and "for" two different techniques for iteration? For do-while, we can use if we want to execute the loop once before checking condition. similarly is there any difference between while and for.
Thanks in advance.
Why we have "while" and "for" two different techniques for iteration? For do-while, we can use if we want to execute the loop once before checking condition. similarly is there any difference between while and for.
Thanks in advance.
The idea is that the different loop statements can help to convey the kind of flow of control that might be expected of the loop. For example, upon seeing a for loop, you would expect that there would be some kind of iteration over a range such that the iterator is incremented or otherwise points to an item further in the range until the range is exhausted, whereas with a while loop you might expect something more generic.Originally Posted by krkr
True, but you would need to either repeat the loop condition (violating the Don't Repeat Yourself principle), or you would need to pull out the loop condition into a function that can be called twice (good idea for a complex condition, but unnecessary hassle for a simple one).Originally Posted by krkr
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Code:for (int counter = 0; counter < 10; ++counter) { if (counter == 0) /* Skip first line for some reason.. */ continue; /* Still calls increment above */ } int counter = 0; while (counter < 10) { if (counter == 0) continue; /* Oops counter never increments because we call continue before the increment below */ ++counter; }
means for better readability? Could you please provide sample code for this.Originally Posted by laserlight
For example, upon seeing a for loop, you would expect that there would be some kind of iteration over a range such that the iterator is incremented or otherwise points to an item further in the range until the range is exhausted, whereas with a while loop you might expect something more generic.
You should have seen a great deal of such sample code by now. There's one provided by nonpuz in post #3, though I personally avoid the use of continue. You could easily write your own sample code, and if you cannot, then you should not be worrying about this to begin with.Originally Posted by krkr
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)