Grasshopper

algorithmic modeling for Rhino

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 each other, 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.

Hoped you enjoyed this tutorial

Thank you

Mihai Pruna

Views: 2767

Comments are closed for this blog post

About

Translate

Search

Videos

  • Add Videos
  • View All

© 2024   Created by Scott Davidson.   Powered by

Badges  |  Report an Issue  |  Terms of Service