Tuesday, March 18, 2014

Factorial – Linux Shell Scripting

Problem Question


Write a script to calculate the factorial of a given number

Explanation of Problem


Here we wish to write a Linux Shell Script that would accept one command line parameter and find the factorial of that number.

Code



#*Factorial*
#@Shell: Bash
#@Author: Toxifier
#@URL: http://letsplaycoding.blogspot.com/
#@Date: 18-03-2014
fact=1
for (( i=1;i<=$1;i++ ))
 do
  fact=$(($fact*$i))
 done
echo Factorial of $1 is $fact

Explanation of Code


Please note the number of whitespaces in the above script. In Linux Shell Scripts, a single extra whitespace could lead to hours of unnecessary debugging like a missing semicolon in a C program.

fact=1 -> We initialise a variable ‘fact’ that would hold the value of the final answer. We initialise it to one because we are going to multiply it recursively (1 being the multiplicative identity).

for (( i=1;i<=$1;i++ )) -> Our main loop where we multiply the number(say n) with all numbers from 1 to (n – 1). We do this by using fact=$(($fact*$i)), where the variable ‘fact’ is multiplied by the loop counter (‘i’) and at the same time we store the value in ‘fact’ itself since we have to multiply it with more numbers(probably). The loop counter ‘i’ helps by taking the values ‘1’ to ‘n – 1’ to be multiplied by the number whose factorial was to be found.

do done -> The for loop block delimiters.

echo Factorial of $1 is $fact -> echo command of the linux shell used to display the string following it to the standard output display of the terminal. ‘$1’ represents he first command line argument (the number whose factorial is to be calculated).

Output(s)



No comments:

Post a Comment

Need help?