PL/SQL Program to Reverse a Number Using WHILE Loop with Full Explanation

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 digit
  • reversed * 10 + rem builds the reversed number
  • TRUNC(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.

Related Tools & Articles

Written by | Updated on