How Do i Do A Recursion

seanvoth

Well-known member
Joined
Aug 5, 2006
Messages
58
Programming Experience
1-3
Someone told my i should use Recursion And i cant find anything on it so can someone help me thanks:eek:
 
this simplest recursion is:
VB.NET:
Private Sub MySub
  Call MySub
End Sub

this sub simply keeps calling itself
 
The basics of recurson is that it is a formula that uses itself.

the first parameter always got to have a "start".
Eks:

&1 <-- first recurson
&1 = 1

&2
&2 = 2&-1 * 2
&2 = &1 * 2
&2 = 1 * 2
&2 = 2

&3
&3 = &3-1 * 2
&3 = &2 * 2
&3 = 2 * 2
&3 = 4

and so it goes..
Can be made like this:

Here is an example:
VB.NET:
Private Function Kompleks(ByVal n As Long) As Long
If n = 0 Then
Return 4
ElseIf n = 1 Then
Return 7
ElseIf (n Mod 2) = 0 Then
Return Kompleks(n - 2) + 4
Else
Return Kompleks(n - 2) + 7
End If
End Function
You just call thisone.. more or less like:

VB.NET:
for i = 0 to 100
something = kompleks(i)

next

It depends on the rules you place for the recurson.. Like, you can have it the same all the way, such as i made it at the first example..
Or you can change it depending on how far out in the recurson you have come..
rather hard to explain, since im not that good at it myself :p
 
If you'd like to study a bit on the general structure of recursive programming, google on "n-ary recursion" and look for some simple permutation examples that you can test and play with.

I just had to use recursion in an app I was working on to select all related nodes in a connected branching structure.
 
i like to think of recursion as pretty much a while loop but with the inside of the loop as a method.

i got to say though, i don't think i've even written a recursive function since my uni days... i imagine they would be useful for some types of applications, but i guess I've never come across a situation where it would be the best solution.

i think they're harder to understand for a start, plus i wouldn't think they'd be that efficient, as you would have to propagate up the call stack.

i dunno, it would be interesting to hear point of views from people who do use them actually and what the advantages are.
 
Recursive functions are common and useful when dealing with something that has nested levels, for example folders as mentioned a parent folder has child folders which in turn have their own child folders, for example forms Controls collection where each control in turn have their own Controls collection etc, for example TreeView Nodes collection where each node in turn have their own Nodes collection etc. So you code the method to do simple work on the single given parent and just call the same method recursively with the child and childs-child etc. Recursion is also common with algoritms that work on the result from the calling function and repeat the same method on that, like some mathematical formulas and other computations do. Some words from Wiki.
 
Back
Top