Recursive Factorial Function in BASH Programming


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

tex_a255cac4fb52295b3b35bbeb6d3e9ae1 Recursive Factorial Function in BASH Programming bash script math recursive where tex_0ce30466f44bd40a032c7217bb0b7c75 Recursive Factorial Function in BASH Programming bash script math recursive

BASH supports function declaration and recursion – just like other modern programming language. See below the Recursive function to compute the factorial values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/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
#!/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
2
3
4
5
6
7
8
9
10
1!=1
2!=2
3!=6
4!=24
5!=120
6!=720
7!=5040
8!=40320
9!=362880
10!=3628800
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) —

GD Star Rating
loading...
275 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

Leave a Reply