Topic 16 of 83
While Loop
Overview
A while loop repeatedly executes a block of code as long as a specified condition is true. It is best used when the number of iterations is unknown beforehand.
Syntax
cpp
int count = 0;
while (count < 5) {
cout << count << " ";
count++; // Don't forget to update the condition!
}Common Pitfalls
- Creating an infinite loop by forgetting to update the loop variable inside the loop body.
Interview Tips
- Be prepared to explain when to choose a `while` loop over a `for` loop (use `while` when reading files, network streams, or taking user input until a sentinal value is hit).
Real-World Example
Extracting digits from a number.
example
cpp
#include <iostream>
using namespace std;
int main() {
int n = 1234;
int reversed = 0;
while (n > 0) {
int digit = n % 10;
reversed = (reversed * 10) + digit;
n /= 10;
}
cout << "Reversed: " << reversed << endl;
return 0;
}