Reverse a Number in PL/SQL

PL/SQL is a block-structured language that combines SQL's functionality with procedural commands. In this article, we will discuss a program in PL/SQL to reverse a given number.

Input : 98765
Output : 56789
Explanation : reverse number of 98765 is 56789.

Input : 56784
Output : 48765
Explanation : Reverse number of '56784' is '48765'.

Algorithm to Reverse a Number

The algorithm to reverse a number involves extracting digits from the original number and building the reversed number step by step:

  • Take out the last digit from the number by finding the remainder of num/10.
  • Add the last digit to another variable reversed_num by multiplying the current reversed_num by 10.
  • Remove the last digit from the original number by dividing it by 10.
  • Repeat steps 1−3 until the original number becomes 0.
  • Finally, display the reversed_num.

Visual Representation

Reversing Number: 1234 Step Number Last Digit Reversed Operation 1 1234 4 4 0×10 + 4 = 4 2 123 3 43 4×10 + 3 = 43 3 12 2 432 43×10 + 2 = 432 4 1 1 4321 432×10 + 1 = 4321 Final Result: 4321

PL/SQL Implementation

Here's a complete PL/SQL program to reverse a number ?

DECLARE
    num number;
    reverse_num number := 0;
    
BEGIN
    num := 98765;
    
    -- Display the original number
    dbms_output.put_line('Original number: ' || num);
    
    -- Process to reverse the number
    WHILE num > 0 LOOP
        reverse_num := (reverse_num * 10) + mod(num, 10);
        num := trunc(num / 10);
    END LOOP;
    
    -- Display the reversed number
    dbms_output.put_line('Reversed number: ' || reverse_num);
END;
/

The output of the above code is ?

Original number: 98765
Reversed number: 56789

How the Code Works

The program uses the following key components:

  • MOD function: mod(num, 10) extracts the last digit of the number
  • TRUNC function: trunc(num / 10) removes the last digit from the number
  • WHILE loop: Continues until all digits are processed
  • Mathematical formula: (reverse_num * 10) + last_digit builds the reversed number

Conclusion

In this article, we explored how to reverse a number using PL/SQL. The algorithm is straightforward and demonstrates fundamental programming concepts like loops, arithmetic operations, and built-in functions. This technique is useful in various applications where digit manipulation is required.

Updated on: 2026-03-14T20:44:41+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements