The while Loop
Use a while loop when you don't know how many iterations you need — you just keep going while a condition stays true.
int number = 1;
while (number <= 5) {
cout << number << "\n";
number++;
}
while vs for
Reach for for when you have a known count or are iterating over a range. Use while when the stopping condition depends on something that changes inside the loop, like reading input or waiting for a flag.
Both can do the same job, but choosing the right one makes your intention clear.
Try it Yourself →