Java while & do-while Loops: Number & Digit Algorithms
while Loop (Entry-Controlled) ยท do-while Loop (Exit-Controlled) ยท When to use for vs while vs do-while ยท Digit Reversal ยท Palindrome ยท Armstrong Numbers
Comprehensive exploration of condition-driven loops in Java: mastering entry-controlled while loops and exit-controlled do-while loops, designing menu-driven console applications, and implementing classic number algorithms (digit counting, number reversal, palindrome validation, and Armstrong number verification).
1. The `while` Loop (Entry-Controlled Loop)
The while loop is an Entry-Controlled Loop: it evaluates the boolean condition before executing the loop body. If the condition is false on the first check, the body is never executed:
while (condition) {
// Code executed as long as condition is true
// MUST contain an update step!
}When to Use while vs for:
- Use for Loop: When the exact number of iterations is known in advance (e.g. iterate 10 times, loop through 50 array elements).
- Use while Loop: When the number of iterations is unknown and depends on a dynamic runtime condition (e.g. reading until end of file, processing digits until number becomes 0, waiting for user input).
2. The `do-while` Loop (Exit-Controlled Loop)
The do-while loop is an Exit-Controlled Loop: it executes the loop body first, and only evaluates the condition at the end:
do {
// Code executed AT LEAST ONCE!
} while (condition); // Note the mandatory semicolon!Key Distinction:
Because the condition is checked at the bottom, ado-while loop is guaranteed to execute at least once, even if the condition is false initially!
int x = 10;
// while loop: condition is false (10 < 5), executes 0 times
while (x < 5) {
System.out.println("While loop running");
}
// do-while loop: executes body once before checking condition!
do {
System.out.println("Do-while executed once!");
} while (x < 5);
3. Classic Number & Digit Algorithms with `while` Loops
Number manipulation algorithms rely on the modulo (%) and division (/) operators inside a while loop:
1. Extract Last Digit: int lastDigit = number % 10; (e.g. 1234 % 10 = 4)
2. Remove Last Digit: number = number / 10; (e.g. 1234 / 10 = 123)
3. Build Reversed Number: reversed = (reversed * 10) + lastDigit;
What is an Armstrong Number?
An Armstrong Number (e.g. 153, 370, 371) is a number that is equal to the sum of its own digits each raised to the power of the number of digits: $$153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153$$Beginner Example & Code Anatomy
public class Main {
public static void main(String[] args) {
System.out.println("=== 1. Reverse a Number & Palindrome Check ===");
int originalNumber = 12321;
int temp = originalNumber;
int reversedNumber = 0;
int digitCount = 0;
// while loop processes number digit by digit until temp becomes 0
while (temp > 0) {
int lastDigit = temp % 10; // Extract rightmost digit
reversedNumber = (reversedNumber * 10) + lastDigit; // Shift and append
temp = temp / 10; // Discard rightmost digit
digitCount++;
}
System.out.println("Original Number : " + originalNumber);
System.out.println("Total Digits : " + digitCount);
System.out.println("Reversed Number : " + reversedNumber);
System.out.println("Is Palindrome? : " + (originalNumber == reversedNumber));
System.out.println("
=== 2. Armstrong Number Verification (153) ===");
int testArm = 153;
int armTemp = testArm;
int armSum = 0;
while (armTemp > 0) {
int digit = armTemp % 10;
armSum += (digit * digit * digit); // digit^3
armTemp /= 10;
}
System.out.println("Calculated Cube Sum: " + armSum);
System.out.println("Is 153 Armstrong? : " + (testArm == armSum));
}
}
๐ Line-by-Line Code Explanation
int lastDigit = temp % 10;
Extracts the last digit using modulo 10.
reversedNumber = (reversedNumber * 10) + lastDigit;
Shifts existing reversed digits to the left (multiplying by 10) and adds the new digit.
temp = temp / 10;
Integer division by 10 strips off the rightmost digit, moving toward loop termination when temp reaches 0.
originalNumber == reversedNumber
Palindrome check: a number is a palindrome if its reverse matches the original.
Practical Real-World Example
public class BankATMMenuSimulation {
public static void main(String[] args) {
// Simulating a menu-driven banking session using do-while
int userChoice = 3; // Simulated user choice: 3 (Check Balance)
double currentBalance = 25000.00;
System.out.println("=== ATM Terminal Session (do-while) ===");
int simulatedAttempts = 0;
do {
System.out.println("
[MENU OPTIONS]");
System.out.println("1. Deposit Cash");
System.out.println("2. Withdraw Cash");
System.out.println("3. Check Account Balance");
System.out.println("4. Exit Session");
System.out.println("User Selected Option: " + userChoice);
switch (userChoice) {
case 1 -> System.out.println("Action: Deposit Module Initialized.");
case 2 -> System.out.println("Action: Withdrawal Module Initialized.");
case 3 -> System.out.printf("Action: Current Account Balance is โน%,.2f%n", currentBalance);
case 4 -> System.out.println("Action: Session Ended. Please take your card.");
default -> System.out.println("Invalid Selection. Try again.");
}
simulatedAttempts++;
// Exit after simulation run
if (simulatedAttempts >= 1) break;
} while (userChoice != 4);
System.out.println("Session gracefully closed.");
}
}
- Forgetting update step in while loop: "while (x > 0) { System.out.println(x); }" causes a CPU-locking infinite loop. Always decrement/update (x--).
- Forgetting semicolon at the end of do-while: "do { ... } while (cond)" fails compilation. A semicolon is required: "while (cond);".
- Modifying the original variable: When reversing a number, store it in a temporary variable "temp = num;" so the original number is preserved for final equality comparison.
Test your understanding by writing the code directly in your editor or running in our online Java compiler:
// Coding Challenge:
// Write a program to count the sum of digits of a number (e.g. number = 54321):
// 5 + 4 + 3 + 2 + 1 = 15.
// Output: "Sum of digits of 54321 = 15"
public class Main {
public static void main(String[] args) {
int number = 54321;
int sum = 0;
// TODO: Use a while loop to compute sum of digits
}
}
๐ก Frequently Asked Questions & Interview Insights
โ What is the main architectural difference between while and do-while?
"while" checks its condition at the entry gate and may run 0 times if condition is false. "do-while" checks condition at the exit gate and is guaranteed to execute at least once.
โ How do you handle negative numbers in digit reversal?
Take the absolute value "Math.abs(num)" before the while loop, extract digits, and re-apply the negative sign if original was negative.
โ Can a while loop condition contain multiple logical criteria?
Yes! "while (attempts < 3 && !isAuthenticated) { ... }" is standard pattern in security login routines.
๐ Quick Chapter Recap
- while loop is entry-controlled: evaluates condition before running.
- do-while loop is exit-controlled: executes body at least once.
- Extract last digit with % 10; remove last digit with / 10.
- Palindromes and Armstrong numbers are verified using digit extraction while loops.