Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
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_digitbuilds 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.
