A while loop is an entry-controlled loop that repeatedly executes a target statement block as long as a given boolean condition remains true. It is most appropriate when the total number of iterations is not known in advance.
while (condition) {
// Statements executed repeatedly
// Update expression (increment/decrement)
}
#include <iostream>
int main() {
int num = 4589;
int reversedNum = 0;
std::cout << "Original Number: " << num << "\n";
while (num > 0) {
int remainder = num % 10; // Extract last digit
reversedNum = (reversedNum * 10) + remainder; // Append digit
num /= 10; // Remove last digit
}
std::cout << "Reversed Number: " << reversedNum << "\n";
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Compare entry-controlled vs exit-controlled loops.
Definite iteration with counters.
Terminating loops early or skipping iterations.