Recursive Factorial Function in BASH Programming
As you may know, the famous factorial can be done in Recursion via:
f(n) = n * f(n-1) where f(0) = f(1) = 1
BASH supports function declaration and recursion - just like other modern programming language. See below the Recursive function to compute the factorial values.
#!/bin/bash
function f() {
local n=$1
if [[ $n -eq 0 ]]; then
echo 1
else
echo $((n*$(f $n-1)))
fi
}
for i in {1..10}; do
echo "$i!=$(f $i)"
done
This BASH script prints the first 10 factorial numbers:
1!=1
2!=2
3!=6
4!=24
5!=120
6!=720
7!=5040
8!=40320
9!=362880
10!=3628800
We use "local" to keep the variables at scope of function, and we can use $() to call a function recursively.
See also: Teaching Kids Programming – Recursion in Five Minutes
Reposted to Blog
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^
NEW! Following my Trail (Upvote or/and Downvote)
Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com
My contributions
- Video Downloader
- Steem Blockchain Tools
- Free Cryptos API
- VPS Database
- Computing Technology Blog
- A few useless tools
- And some other online software/tools
- Merge Files/Videos
- LOGO Turtle Programming Chrome Extension
- Teaching Kids Programming - Youtube Channel and All Contents
Delegation Service
Important Update of Delegation Service!
Support me
If you like my work, please:
- Buy Me a Coffee, Thanks!
- Become my Sponsor, Thanks!
- Voting for me:
https://steemit.com/~witnesses type in justyy and click VOTE
- Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
- Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
- Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses
hello, sir @justyy plz fix the voting bot. Every day I need to contact you to get upvote. It's already 40 minutes but my today's post gets no upvote.
my post: https://steemit.com/hive-129948/@rme/php-half-dozones-string-operations-in-php
done.
thank you :D