jnb92
jnb92

Reputation: 1

Dynamically Resizing Arrays

I ran into the following issue when dealing with adding to variable array sizes. The loop runs one time more then it should essentially. But I'm curious as to what would cause this behavior? Am I not quite understanding how the loop exit functions are being called?

Here's the code:

Module Module1

Sub Main()
    Dim num(-1)
    Dim i = 0
    Console.WriteLine("Input numbers to be added, q to stop:")
    Dim input
    Dim total = 0
    Do
        ReDim Preserve num(UBound(num) + 1) : num(UBound(num)) = i 'resize the array each time before an element is added.
        input = Console.ReadLine
        If IsNumeric(input) Then 'attempt to break loop on non numeric input
            num(i) = CInt(input)
            i += 1
        Else
            Exit Do
        End If
    Loop
    total = 0
    For Each n In num
        total += n
    Next
    Console.WriteLine(Join(num))
    Console.WriteLine("Total: " & total)

    Console.ReadLine()

For input: 1 2 3 4 5 q, the output I get is:

1 2 3 4 5 5
Total: 20

It adds the last element twice, which is interesting as it is not only running twice but somehow using the last numeric input even though the final input was not numeric. Does anyone know why that would be?

Upvotes: 0

Views: 113

Answers (2)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

You both (jnb92, PankajJaju) should not grow the array before you are sure the input is numerical and has to be stored.

Dim input
Do
    input = Console.ReadLine()
    If IsNumeric(input) Then 'attempt to break loop on non numeric input
        ReDim Preserve num(UBound(num) + 1)
        num(UBound(num)) = CInt(input)
    Else
        Exit Do
    End If
Loop

Update wrt comment:

Your

ReDim Preserve num(UBound(num) + 1) : num(UBound(num)) = i

assigns i to num for each input; your

num(i) = CInt(input)

overwrites that with your numerical input, but not for the terminating "q". So for your (one and only?) test case, the spurious last elemement is (accidentially) 5.

Upvotes: 3

Pankaj Jaju
Pankaj Jaju

Reputation: 5471

I've used your script and tried to create a working solution

    Dim num, input,  total, i
    num = Array()

    i = 0
    Do
        input = Inputbox("Input numbers to be added, q to stop:")
        If IsNumeric(input) Then 'attempt to break loop on non numeric input
            ReDim Preserve num(UBound(num) + 1) 'resize the array each time before an element is added.
            num(i) = CInt(input)
            i = i + 1
        Else
            Exit Do
        End If
    Loop

    total = 0
    For Each n In num
        total = total + n
    Next
    msgbox Join(num)
    msgbox "Total: " & total

Edit - Updated answer based on @Ekkehard.Horner comments

Upvotes: 0

Related Questions