This may be a stupid question, but how does the efficiency of a while loop compare to that of a for loop? I\'ve always been taught that if you can use a for loop,
As mentioned in all the answers here, any decent compiler would compile both loops into the same machine code.
Your machine code (taking MIPS as an ex) would be a bunch of normal assembly statements followed by a branch (onequal/notequal) in both cases making your efficiency consistent.
However, you could debate over the coding style issue over here (Not efficiency).
For Loops :
*Probable Usage : When a collection of items already exists and you want to go over it and retrieve the number of times a certain property appears.
While Loops :
You're not aware of how many times the loop is going to run. There is an exit case which is set/reached sometime while the loop is running (if you want to simulate a for loop, you'll use something like a counter (extra code))
Do not know by how much your loop is going to increment by. Your increment/next move can be set dynamically. While you can do this in a for loop, you'll have to account for the increment at each iteration as well causing some unreadable code which can be avoided when if you use a while loop.
*Probable Usage : Grepping a stream for some data. You're not aware of how long the stream is so your exit case is when the stream ends. Since it's a stream and you might be getting data line by line, you might want to skip over white lines altogether making your increments not consistent.