I am attempting to re-write this bash function in C, but the a little unsure of how to convert this function into a C loop.
Here I have variables set. This I already have
n=10
r=4
This is where I get a little lost on how to re-write this. This seems to be calling the function with its own function and I pretty sure C will not do that (safely at least ) Also it does not need to be a function at all, I just need to plug in the same variables and have it come out with the same result.
factorial() {
if (($1)); then
echo $(($1 * $(factorial $(($1-1)))))
else
echo 1
fi
}
The last bit, is what would be the best way to express the code below in C? Would the bracketing in bash carry over?
result=$(($(factorial $n)/($(factorial $r)*$(factorial $(($n-$r))))))
It’s totally legal for C functions to call themselves – this is called recursion. In C, it would look like this:
You could also write this directly as a loop:
Hope this helps!