Recursion problem

broadcast28
03-10-2004, 04:07 AM
Hi
I need to Create a Visual Basic application that takes in a number of people and displays the number of handshakes exchanged.

The recursive formula is
HandShake(N) = (N-1) + HandShake(N-1)

And this is the function.
Function HandShake(n As Integer) As Integer

If n = 1 Then

' Number of handshakes between 1 person

HandShake = 0
Else
HandShake = (n - 1) + HandShake(n - 1)
End If

End Function

However I am unsure on how to create a form to call this function.


any suggestions would be appreciated
:eek:

Marathon Man
03-10-2004, 04:32 AM
Do you need to use recursion, the formula is handshakes = (n*(n-1))/2.

an5w3r
03-10-2004, 05:43 AM
Private Sub Command1_Click()
Function HandShake(n As Integer) As Integer

If n = 1 Then

' Number of handshakes between 1 person

HandShake = 0
Else
HandShake = (n - 1) + HandShake(n - 1)
End If

End Function

Private Sub Form_Load()
MsgBox HandShake(4)
End Sub

Andyh
03-10-2004, 05:43 AM
MarathonMan is correct but if you want to call the function from a form just have the call in a button click, the input can either be from a text box or from an input statement


Private Sub Command1_Click()
Dim n As Integer
n = CInt(Me.Text1)
'compares both answers
MsgBox CStr(HandShake(n)) + ":" + CStr((n * (n - 1)) / 2)

End Sub

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum