hey

i need help understanding recursions :s could someone give me an example of a recursion and help with steps on how to change it to a for loop?
for example
for(int i; i <= 10; i++)
how would i change this into a for loop?


thanx in advance
mina :)

A classic recursion example :
This function computes x! , which is x * (x-1) * (x-2) * ... * 1. This formula is widely used when dealing with probabilites.

The first version is recursive :

unsigned long fact(unsigned long x)
{
       if(fact==1 || fact==0)return 1;
       else return x*fact(x-1);
}

The second version is non-recursive (see the difference)

unsigned long fact(unsigned long x)
{
    unsigned long i, result=1;
    for(i=0; i<x; i++)result*=i;
    return result;
}

In general non-recursive versions of algorithms are more fast and use less memory, but finding a non-recursive way to solve a problem is not always trivial.

Bye

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.