« December 2006 | Main | April 2007 »

March 31, 2007

A simple tutorial on recursion

One of the neatest tricks for avoiding unnecessary 'for' or 'while' loops in your program is using a function recursively.

Engineers and Scientists without a computer science background usually rely on simple iterative techniques in their codes. But sometimes we end up with a bunch of nested loops that make the program very slow in execution and cumbersome to debug. Using recursion is an elegant way to avoid loops when an operation is performed iteratively.

Here's how it works: Basically a function calls itself from inside. The call is made only if a condition is satisfied...otherwise you will have an infinite series of instances of the same function running inside eachother, the coding equivalent of an image in an image in an image.......

Here is a simple C example, using recursion to raise a number to a certain power.

//the function declaration. x is the number to be raised, lim is the power, cur is the current power.(explained below):

int power(int x,int lim,int cur)

 

{if (cur<lim)

 

//if the current power is less than the set power, x is multiplied with another call of the power function, with the current power incremented by one:

 

return x*power(x,lim,cur+1);

else

return x;

//if the desired power has been reached, the function simply returns x...then exits. the previous function also exits, and so on, until we are back in the main program.

}

 

main()

{

//note that the first 'cur' value is 1...the next one will be 2...last one will be 3. 3^3 is 27 and that's what the function will return

raised=power(3,3,1);

printf("%d", raised);

 

} 

 

 

Yes, I know there already exists a power function in every language and the above algorithm is going in a very roundabout way to solve a simple arithmetic operation. Tongue out However, this example is the simplest way to illustrate the use of recursion in a program.
For a more complex problem that can be solved through the use of recursive functions, see the traveling salesman problem.



March 26, 2007

Free Scientific Computing Magazine!

Who doesn't like free stuff? Well, I know I do!

 

The folks at Scientific Computing Magazine offer free subscriptions to the paper version of their magazine (website http://www.scientific-computing.com) to qualified entities. It took a while to get my first copy, but hey, it was free. The content is great, on a par with any other computing, scientific or engineering magazine out there. The topics covered are quite diverse, but this particular issue seemed to focus on a lot of chemistry packages.

 

Subscribe here and if you qualify you can expect the first issue of the magazine to arrive in a few months.


Hosting by Yahoo!