C++20 sections · 1024 units
Open in Course

for vs while

When to use each

Use for when you know the iteration count upfront: looping 10 times, processing array indices, counting in a range. Use while when the count depends on runtime conditions: reading until end-of-file, waiting for user input, searching until a match is found.

For loops are cleaner for counting because initialization, condition, and update are grouped. While loops are clearer when the update logic is complex.