Shell script to find factorial of a number using recursion
A shell script is a computer program designed to be run by the Unix shell, a command line interpreter. This blog is about a shell scripting program to find the factorial of a number using recursion.
Logic
The logic is simple. If the number 'n' is 1, return 1. Else return 'n' * 'factorial(n-1)'.
Things to note:
- After writing the script, change the mod of the script to enable execution. This is done by:
or
Output of the program
Good to read
1) Java program to convert mobile number pad to characters
2) Difference between "diff" and "sdiff" command
3) Java program to return first non repeated character in a string
Logic
The logic is simple. If the number 'n' is 1, return 1. Else return 'n' * 'factorial(n-1)'.
Program
#!/bin/sh factorial() { if [ "$1" -gt "1" ]; then a=`expr $1 - 1` b=`factorial $a` c=`expr $1 \* $b` echo $c else echo 1 fi } echo "Enter a number:" read x factorial $x
Things to note:
- After writing the script, change the mod of the script to enable execution. This is done by:
chmod +x factorial.sh
or
chmod 755 factorial.sh
Output of the program
Enter a number: 4 24
Good to read
1) Java program to convert mobile number pad to characters
2) Difference between "diff" and "sdiff" command
3) Java program to return first non repeated character in a string
ReplyDeleteIn the main program, it prompts the user to enter a non-negative integer. Latent Resident Artist It then checks if the input is a valid non-negative integer using a regular expression.