LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   shell script related to square of number question (https://www.linuxquestions.org/questions/programming-9/shell-script-related-to-square-of-number-question-787502/)

studywell09 02-06-2010 09:52 PM

shell script related to square of number question
 
Hi,
Im trying to write a shell script to input few numbers and print every number that is a square of atleast one number given as input.The code i have written is as follows,

echo "Enter total no. of numbers"
read tot
no=0
i=0
num=0
echo "Enter $tot Numbers"
while test $i -lt $tot
do
read no
a[i]=$no
i=`expr $i + 1`
done

echo "DISPLAY NOS"
i=0
while test $i -lt $tot
do
echo ${a[$i]}
i=`expr $i + 1`
done

echo "SQUARE"
i=0
while test $i -lt $tot
do
num=${a[$i]}
for (( j = 0 ; j < $tot ; j++ ))
do
x=${a[$j]}
if test `expr $num \* $num` -eq $x
echo "$x is the square of $num"
fi
j=`expr $j + 1`
done
i=`expr $i + 1`
done

It accepts the nos and displays them too.But later on this error appears,
SQUARE
./m10: line 33: syntax error near unexpected token `fi'
./m10: line 33: ` fi'

What is my mistake?

paulsm4 02-07-2010 12:53 AM

"if" needs a "then" for the "fi" to work

neonsignal 02-07-2010 01:01 AM

Once you put the 'then' back, you will discover you have incremented j twice in the for loop, which means it skips every second number.

studywell09 02-07-2010 04:02 AM

Thanks for your reply.I have added the then and removed the extra incrementation of j.But now it gives me the error ,
'integer expression expected' when i multiply num using expr.
Is my way of storing the array value in the variable wrong??Should it be,
num={${a[$i]}} instead??
Please reply..

neonsignal 02-07-2010 04:44 AM

Quote:

But now it gives me the error, 'integer expression expected' when i multiply num using expr.
I suspect it is a problem with the input data. Are you entering each number on a new line?

studywell09 02-07-2010 05:11 AM

Yes, i am entering each number on a new line..

paulsm4 02-07-2010 02:32 PM

studywell09 -

To understand what a variable really looks like (even though you *think* it it should be an integer, it might be a letter like "a", or a blank space)...

... then "echo" is your friend:

http://dollhousewiki.fox.com/page/Echo


All times are GMT -5. The time now is 01:39 AM.