October 21, 2017 Saturday
Bedtime Story
Factorial Function as a Recursion in C
Tonight let me show you how one can write
down factorial function as a recursive function in C language.
int factorial (int n)
// recursive version
{
if (n ==1) return 1;
else
return n
factorial
(n-1) ;
}
You can see from the above simple program
even if you have little knowledge of programming that the very first line makes
it clear that only positive integers can have factorials.
Then the recursion part is set into motion
with the second line defining the base case of factorial of one being one.
If any other number turns up, then it needs
to be multiplied by a number that is less than one of itself and the product is
then returned back up as the new n.
Thus the recursion is coded.
The key element of this recursion program
involving factorials is that n keeps changing.
Since the way it is written down here is
bit technical as it involves a programming language, let me simplify this
factorial recursion using a more primitive language.
I will try to define factorial of a number
n using n.
The instructions for this would begin as
follows.
If a factorial function of a number
variable n is given an input, it will have to decide between two choices.
If the number input is 1, then the output
of the factorial function would be 1.
For fac n If n == 1, then 1
If n
1, then fac n = n x fac (n-1)
So this becomes a recursive function as the
factorial function is being defined in its own terms.
Factorial of a number n is being defined in
terms of factorial of a number one less than the number n.
To analyze it more deeply, we can consider
a factorial of any number.
In our case we will take it as 3 to shorten
the procedure yet sufficient enough to get the idea of the operation.
fac 3 = 3 x fac 2
= 3 x 2 x fac 1
Now the final step is the base case which
states that fac 1 = 1
So we land up with
fac 3 = 3 x 2 x 1
= 6
The question that arises is that how do we
keep this forever changing values of n separate?
The answer is by stacking.
Stacking is another important concept in
computer science that we shall take up in the nights to come.
Stay tuned to the voice of an average story storytelling
chimpanzee or login at http://panarrans.blogspot.com
Good night mon ami and my fellow cousin ape.
Advertisements
Another great educator and a teacher that I am aware of is
Professor Subhashish Chattopadhyay in Bangalore, India.
While I narrate stories, Professor Subhashish an electronic
engineer and a former professor at BARC, does and teaches real mathematics and
physics.
He started the participation of Indian students at the
International Physics Olympiad.
Do visit him here:
All his books can be downloaded for free through this link:
For edutainment and English education of your children, I
recommend this large collection of Halloween Songs for Kids:
No comments:
Post a Comment