How To Ideas | How To Articles | How To Tutorials


0

How To reverse the digits of a number using Shell Scripting


In this tutorial, I will share a simple script to reverse a number provided through command line in Unix/Linux Operating System. The script will print the reversed digits of provided number and if no number or more than one numbers are provided, then it will print an error. Algorithm is fairly simple :

  1. Let n be the given number.
  2. Set rev and rem equals to 0.
  3. Find last digit of n and store in rem as rem = n % 10.
  4. Now calculate rev as rev = rev * 10 + rem.
  5. Remove the last digit from n by using n = n / 10.
  6. Check if n is greater than 0, if yes goto step 3, else step 7.
  7. Print the number rev which is reverse of number n.

Instructions:

  1. Enter the following line which tell the terminal while running the script to use bash to run the script.
    #!/bin/bash
  2. Now check if only a single argument is provided, if yes then its Ok, otherwise print an error message regarding this and exit the script.
    if [ $# -ne 1 ]
    then
        echo "Usage : $0 number"
        echo "To print the reverse of input number"
        echo "example for 1234 answer will be 4321"
        echo "provide a single number as parameter to script"
        exit 1
    fi
  3. Now assign the 1st parameter value to n, 0 to rev and rem both. (here n, rev, rem are temporary variables)
    n=$1
    rev=0
    rem=0
  4. Now in a while loop, which will run until value of n is greater than 0, apply the algorithm discussed above as follows.
    while [ $n -gt 0 ]
    do
        rem=`expr $n % 10`
        rev=`expr $rev \* 10 + $rem`
        n=`expr $n / 10`
    done
  5. Now print the value of variable rev which contains the digits in the reverse order as compared to original number provided.
    echo "Reversed number is : $rev"

Here is an image of the working sample of the script. (Script name is reverse stored in Documents folder)

Reverse Number using Shell Scripting

Reverse Number using Shell Scripting

You can download the sample script from here.

Incoming search terms:

  • program for reverse of a number in unix (1)
  • reverse of 4 digit no in linux prpgramming (1)
  • reverse of a digit/shell program (1)
Filed in: Shell Scripting Tags: , , , , , , , , ,

Leave a Reply

Submit Comment



© 6205 How To Ideas. All rights reserved.
Proudly designed by Theme Junkie.