Tuesday, 28 May 2013

Recursion

Let Us C, Ch-5.

In my first post I wrote that I'm am going to learn about pointers. Have learnt a bit, at least as much as that lesson taught (I know what the differences between '*i', '&i" and, 'i' are), but nothing interesting really.

So going straight to one of the next lessons. This program seems worth recording.
Still have a while to understand Recursion enough to write my own exercise program. When I look through the program, I can understand how it does what it is doing.

This program finds the factorial of a number. At least I learned that a factorial is the product of a number and all numbers before it.

Factorial of 1= 1
Factorial of 2= 2 X 1= 2
Factorial of 3=3 X 2 X 1 = 6
Factorial of 4= 4 X 3 X 2 X 1= 24
So on and so forth. (More about Factorials at http://en.wikipedia.org/wiki/Factorial ).

The following is the same program in the book with very minor modifications.

#include <stdio.h>

int rec(int x);

main()
{
    int a,fact;

    printf("\nEnter The number you want to find the Factorial of: ");
    scanf(" %d",&a);

    fact=rec(a);
    printf("\nThe factorial value of %i= %i",a,fact);
}

int rec(int x)
{
    int f;

    if(x==1)
    {
        return(1);
    }

    else
    {
        f=x*rec(x-1); //Recursion right here because the function
                      //    rec(x) calls itself subtracting 1 from x.
                      //     Whatever x may be, it is multiplied by 1 less than itself.
                      //     But when it calls itself, it finds the line  f=x*rec(x-1);
                      //    again, and calls itself again and again.
                      //     This will go on until the condition 'if(x==1)' is met

        return(f); //Then it finally returns the finished product to main.
    }
}

No comments:

Post a Comment