PL/SQL Program to Reverse a Number Using While Loop
This PL/SQL program demonstrates how to reverse a number using a WHILE loop. It is a common task in coding interviews and academic practice.
PL/SQL Code to Reverse a Number
DECLARE
num NUMBER := 12345;
reversed NUMBER := 0;
rem NUMBER;
BEGIN
WHILE num > 0 LOOP
rem := MOD(num, 10);
reversed := (reversed * 10) + rem;
num := TRUNC(num / 10);
END LOOP;
DBMS_OUTPUT.PUT_LINE('Reversed Number: ' || reversed);
END;
Explanation
MOD(num, 10)extracts the last digitreversed * 10 + rembuilds the reversed numberTRUNC(num / 10)removes the last digit
FAQs
- Can I use FOR loop instead of WHILE?
- Yes, but WHILE is better when the number of iterations is unknown.
- What happens if the input is 0?
- The program will return 0 as the reversed number.