3
May
Posted by Derek@TheDailyLinux in Scripting » Add Comment »
Shell Script to Display Multiplication Table
I stumbled upon this while researching some other shell script solutions and thought it was pretty clever and nifty. It came from arachnoid.com and I modified it a bit to take an argument from the command line and adjust the width accordingly so the table doesn’t get messed up.
!/bin/sh
width=`echo $(( $1 * $1 )) | wc -c`
y=1
while [ $y -le $1 ]; do
x=1
while [ $x -le $1 ]; do
printf "% ${width}d" $(( $x * $y ))
let x++
done
echo ""
let y++
done
Example usage:
$ ./mult_table 12 1 2 3 4 5 6 7 8 9 10 11 12 2 4 6 8 10 12 14 16 18 20 22 24 3 6 9 12 15 18 21 24 27 30 33 36 4 8 12 16 20 24 28 32 36 40 44 48 5 10 15 20 25 30 35 40 45 50 55 60 6 12 18 24 30 36 42 48 54 60 66 72 7 14 21 28 35 42 49 56 63 70 77 84 8 16 24 32 40 48 56 64 72 80 88 96 9 18 27 36 45 54 63 72 81 90 99 108 10 20 30 40 50 60 70 80 90 100 110 120 11 22 33 44 55 66 77 88 99 110 121 132 12 24 36 48 60 72 84 96 108 120 132 144
Just for fun, I went on and modified it a bit more to accept a starting point as well, just in case you’re working with a table that doesn’t fit in your terminal screen (however, some readability improvements could be made):
#!/bin/sh
if [ $# -lt 2 ]; then
echo "Usage: $0 <start> <finish>"
else
width=`echo $(( $2 * $2 )) | wc -c`
y=$1
while [ $y -le $2 ]; do
x=$1
while [ $x -le $2 ]; do
printf "% ${width}d" $(( $x * $y ))
let x++
done
echo ""
let y++
done
fi
Example usage:
$ ./mult_table 5 12 25 30 35 40 45 50 55 60 30 36 42 48 54 60 66 72 35 42 49 56 63 70 77 84 40 48 56 64 72 80 88 96 45 54 63 72 81 90 99 108 50 60 70 80 90 100 110 120 55 66 77 88 99 110 121 132 60 72 84 96 108 120 132 144
Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:
Here are some similar posts that you may be interested in:
There's 0 Comment So Far
Share your thoughts, leave a comment!