Saturday, January 31, 2009

A question from the Reader-Sum of Numbers divisible by 4

A reader emailed me and asked for help. He wants to create a function to calculate the sum of numbers between 1 and 100 that are divisible by 4. Here is the solution:

Function SumOfNum(ByVal x As Integer) As Integer

Dim i As Integer
SumOfNum = 0
For i = 1 To 100
If i Mod x = 0 Then
SumOfNum = SumOfNum + i
Else
SumOfNum = SumOfNum
End If
Next i



End Function

Private Sub Command1_Click()
Dim w As Integer
x = Text1.Text
w = SumOfNum(x)
Label1.Caption = w

End Sub


When you run the program, enter 4 into textbox 1 and you can get the answer. If you key in other numbers, you will get the sum of numbers divisible by that number. Anyone has better solution can email me or write in the comments of this blog.

No comments: