LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   palindromes within a range (https://www.linuxquestions.org/questions/linux-newbie-8/palindromes-within-a-range-934328/)

kakalig2007 03-13-2012 10:46 PM

palindromes within a range
 
I cannot find what's wrong with my code, but it is not printing anything.Please help....
#!/bin/bash
echo Enter range
read l h
for (( num=l;num<=h;num++ ))
do
a=$num
rev=0
while [ $num -ne 0 ]
do
let rem=num%10
let rev=rev*10+rem
let num=num/10
done

if [ $a -eq $rev ]
then
break
fi
echo $a
done

jhwilliams 03-13-2012 11:21 PM

Suggestion: You should explain what you're trying to do, and then ask an actual question.

Also, check out the [ code ] tags and indentation -- makes it a lot nicer to read posts.

Satyaveer Arya 03-13-2012 11:22 PM

Checkout this code:

Code:

echo "Enter a String : "
read string
i=0
len=${#string}
#get the mid value upto which the comparison would be done
mid=$(($len/2))
while [ $i -lt $mid ]
  do
    if [ "${string:$i:1}" != "${string: -$(($i+1)):1}" ]
      then
      echo "\"$string\" IS NOT a Palindrome"
      exit
    fi
    i=$(($i+1))
done
echo "\"$string\" is a Palindrome"


rigor 03-13-2012 11:49 PM

Hi kakalig2007,

Are you trying to find numeric palindromes?

To try to see what your code is doing, you can use:

Code:

set -x
to turn on "debug" output for your code, to be able to see some substitutions
and to watch your code work. I'd also use some indenting, it might make it
easier to find things in the code. With those changes, the code might look
like this:

Code:

#!/bin/bash

set -x

echo Enter range
read l h

for ((  num=l ;  num <= h ;  num++  ))
    do

        a=$num
        rev=0

        while [  $num  -ne  0  ]
            do
                let rem=num%10
                let rev=rev*10+rem
                let num=num/10
            done

        if [  $a  -eq  $rev  ]
            then
                break
            fi
           
        echo $a

    done


But I would probably change the way the numbers are reversed, to just use
the rev command. That could look like this:

Code:

#!/bin/bash

set -x

echo Enter range
read l h

for ((  num=l ;  num <= h ;  num++  ))
    do

        original=$num
        reversed=`echo $original | rev`
       
        if [  $reversed  -eq  $original  ]
            then
                echo $original
        fi

    done


grail 03-13-2012 11:53 PM

Try placing set -xv at the start of the script to see where it might be going wrong or not behaving as you expect.

Also, I find it odd that you use (()) for the for loop but then all other arithmetic is done using other, more antiquated, methods?


All times are GMT -5. The time now is 04:54 AM.