understanding while and for statement

hi, i'm starting to learn to program with c++, using "C++ without fear book" and i'm on chapter 2. but as i keep trying to read over and over. Also research and looked at this website FAQ, i dont understand whats the difference. Is there a difference? or do they do the same thing? Only difference is that the "FOR" statement is cleaner and more organize? sorry if this is a stupid question.

>> Only difference is that the "FOR" statement is cleaner and more organize?
That is the difference. The for statement is cleaner and more organized for certain tasks. For other looping needs, you don't need to follow the same pattern, so a while loop might be more appropriate.

Making your code clear and organized is an important aspect to programming.

Another note, that book is not one I'd recommend for learning modern C++ programming techniques. You'll still learn a lot, but if you want to really program C++ you'll end up having to unlearn a few things. If you have the chance you might try a different book (e.g. Accelerated C++ or You Can Do It!).

Generally for statements are used when you know a process will repeat for a certain amount of time. A while loop is good if the condition for which the process is carried out can change during runtime. Lets say you want to do a fibbonacci sequence for up to 6 numbers, you would put the algorithm for the fibonnaci sequence in a for loop. Now lets say you want a menu to be displayed as long as the user doesn't press q. Then a while loop would be more more concise. You can make a for loop do what a while loop can do and vice versa, but either is more suited as far as syntax goes for different purposes.

I would say that without that line, the continue brings control back to the top of the loop body... but i is still 5, so we have an infinite loop. With a for loop instead, the increment would still be performed despite the continue, so there will not be an infinite loop.

Originally Posted by Bjarne Stroustrup (2000-10-14)

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.

So basically, as long as the variable in a while loop is incremented manually before a continue, the two loops function the same, which is close enough to my statement that the two loops above were equivalent.