Displaying Square and Cube


Shell script for displaying square and cube of natural numbers.This will be good for students preparing for bank and other competitive exam for quick reference.


-------------------------------------------------------------------------------------------------------------------------------------------------
HOW THIS SCRIPT WORKS:
In this script a 'for' loop with i's value changing from 1 to 25 is run. Inside this loop square and cube of i is calculated and displayed. 
i**2 is same as  i*i  and  i**3  is same as  i*i*i 
One-liner for finding square of 3 is  echo $((3**2))
One-liner for finding cube of 3 is  echo $((3**3))
-------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------

#!/bin/bash

#for showing the square and cube of first 25 natural numbers or more
num=$1
#for displaying only 25 numbers
if [[ "$1" = "$null" ]];then
{
echo -e "\e[1;31mno.| sqre| cube |\e[0m"
for (( i=1; i<=25; i++ ));do
if (( $i <= 3 ));then 
       echo -e "\e[1;34m$i\e[0m  : $((i**2))   : $((i**3))"
elif (( $i <= 9 && $i > 3 ));then
       echo -e "\e[1;34m$i\e[0m  : $((i**2))  : $((i**3))"
elif (( $i > 9 ));then
       echo -e "\e[1;34m$i\e[0m : $((i**2)) : $((i**3))"
fi
done
}
#for displaying more than 25
else
{
echo -e "\e[1;31mno.| sqre| cube |\e[0m"
for (( i=1; i<=$1; i++ ));do
if (( $i <= 3 ));then 
       echo -e "\e[1;34m$i\e[0m  : $((i**2))   : $((i**3))"
elif (( $i <= 9 && $i > 3 ));then
       echo -e "\e[1;34m$i\e[0m  : $((i**2))  : $((i**3))"
elif (( $i > 9 ));then
       echo -e "\e[1;34m$i\e[0m : $((i**2)) : $((i**3))"
fi
done
}
fi


-------------------------------------------------------------------------------------------
just calling the script will show square and cube of first 25 natural numbers.If more than 25 is needed you should specify it.For example this script is named mtable in my system.Calling in mtable in terminal will result in :




If  I want more than 25 , say 78 , then I should type  mtable 78 and press enter which will result in :




So you wanted square and cube of which number ? ..89 ?

Enjoy Linux !!


Don't know what to do with these codes ??  click here

No comments:

Post a Comment