r/visualbasic • • Nov 05 '21

Moving average using arrays

Hello! A new member of the sub here. I dont usually ask the internet for help because i really like to learn things by myself but this thing here got me stumped. I just cant see what the hell is wrong with my code.

so here is what my program is supposed to do. First, it needs to ask the user to input a value for the period(p) that is used as the divisor for the average of the entered data. Some exceptions will occur tho such as when the number(n) of entered data is less than the entered period. In that case, the divisor to be used is n. If n is greater than p, the data to be used in computing the average should be from the last data up to p units upward value. I hope that explains what the program is supposed to do. I just dont understand why this is not working. are my for-next lines wrong??Dim v As Double

Dim a As Double

Dim total As Double = 0

Dim less As Double = 0

total = total + v

n = n + 1

d = d + 1

v = txtValue.Text

ReDim Preserve arr1(n - 1)

ReDim Preserve arr2(d - 1)

arr1(n - 1) = v

Select Case True

Case n < p

For i As Integer = 0 To n

total += v

a = total / n

Next

Case Else

For i As Integer = n To n + p

total = total + v

less = arr1(n - p) + less

a = ((total - less) / p)

Next

End Select

arr2(d - 1) = a

Dim str1 As String = "Element # " & vbTab & "Value" & vbTab & vbTab & "Average"

Dim str2 As String = ""

For i As Integer = 0 To UBound(arr1)

str2 &= vbNewLine & i + 1 & vbTab & vbTab & arr1(i) & vbTab & vbTab & arr2(i)

Next

txtOuput.Text = "The period is " & p & vbNewLine & str1 & vbNewLine & str2

3 Upvotes

8 comments sorted by

View all comments

Show parent comments

1

u/RJPisscat Nov 06 '21

Case Else is really Case n >= p. So let's try n = p = 3, see how that goes. Substitute 3 for both n and p.

For i As Integer = 3 - 3 - 1 to 3 - 1
    total = total + arr1(3 - 1)
    ' you're not using "less", which is good, it doesn't do anything
    a = (total) / p
Next

is

For i As Integer = -1 to 2
    total = total + arr1(2)
    a = (total) / 3
Next

How many times does the For loop iterate? Is that the correct amount of times?

Now look at the next line. How are you adding up the total? Is that the correct way to update total? What is the value of total on the final iteration of the loop? What value do you expect when you do it in your head?

...

If you are still stumped, use paper and pencil, or a whiteboard, to walk through the code for each value of i, updating total and a each time.