Re: for loop or while loop
Quote:
Originally posted by slamit93
last question that I am not sure how to answer on my study guide:
When should a while loop be used and when should a for loop be used?
In my understanding, they basically do the exact same thing, and I can pretty much write either type of loop to do the exact same thing... I guess, is it just preferential to use a for loop when you only want the loop to go through a certain number of iterations, and you should use a while loop when you just want a particuliar condition to be met for the loop to keep running?
If you are going to iterate a known number of times, you should use a for loop.
If you don't know how many times you are going to loop, but know that it is at least 1, you should use a do-while loop.
If you don't know how many times you are going to loop, and it might not even be 1 loop, you should use a while loop.
As has been pointed out, you could use one 'loop-type' to do what the other do with a little tweaking and clever layout, but these are the general purposes.