Algorithms, Blockchain and Cloud

Recursive Factorial Function in BASH Programming


As you may know, the famous factorial can be done in Recursion via:

where

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

–EOF (The Ultimate Computing & Technology Blog) —

258 words
Last Post: Teaching Kids Programming - Swap Characters to Equalize Strings
Next Post: Teaching Kids Programming - Count Odd Numbers in an Interval Range

The Permanent URL is: Recursive Factorial Function in BASH Programming (AMP Version)

Exit mobile version