0

I have written code for an array of numbers which prints out. I'm now writing code to split the array into even and off numbers. I've started off with an if statement to separate the numbers but i'm struggling to find a solution on how to do it. My code below is failing as it's unable to split the numbers.

Sub main()
    a=Array(5,10,15,20)
for each x in a
    Msgbox(x)

    If MyArray(I) / 2 = MyArray(I) 
        List1.AddItem MyArray(I) ' Even Integers
    Else
        List2.AddItem MyArray(I) ' Odd Integers
    End if
next


End Sub 
1

1 Answer 1

1

As Lankymart suggests, the simplest approach would be to use Mod() and check if the remainder is 1 or 0, but you can also do it with the approach you seemed to be working towards:

If MyArray(index)/2 = Int(MyArray(index)/2) Then
    ' Even number
Else
    ' Odd number
End If

Mod() approach:

If MyArray(index) Mod 2 = 0 Then
    ' Even number
Else
    ' Odd number
End If

Here's a complete subroutine that demonstrates what you are trying to do:

Dim arr(4) As Integer
Dim arrEven() As Integer
Dim iEvenValues As Integer
Dim arrOdd() As Integer
Dim iOddValues As Integer
Dim iCounter As Integer

' Initialize array
arr(0) = 5
arr(1) = 10
arr(2) = 15
arr(3) = 20

For iCounter = 1 To UBound(arr)

    If arr(iCounter - 1) Mod 2 = 0 Then
        iEvenValues = iEvenValues + 1
        ReDim Preserve arrEven(iEvenValues)
        arrEven(iEvenValues - 1) = arr(iCounter - 1)
    Else
        iOddValues = iOddValues + 1
        ReDim Preserve arrOdd(iOddValues)
        arrOdd(iOddValues - 1) = arr(iCounter - 1)
    End If
Next

Dim sValues As String
sValues = "Even values (" & iEvenValues & "):"
For iCounter = 1 To UBound(arrEven)
    sValues = sValues & " " & arrEven(iCounter - 1)
Next

MsgBox sValues

sValues = "Odd values (" & iOddValues & "):"
For iCounter = 1 To UBound(arrOdd)
    sValues = sValues & " " & arrOdd(iCounter - 1)
Next

MsgBox sValues
Sign up to request clarification or add additional context in comments.

3 Comments

How would it fit in with my array though thats where im confused. This is my code so far a=Array(5,10,15,20) for each x in a Msgbox(x) If MyArray(a)/2 = Int(MyArray(a)/2) Then ' Even number Else ' Odd number End If next
I get a mismatch error when i pass my array though the loop
For i = Array(5,10,15,20) If i mod 2 = 1 Then Msgbox(i & " is odd.<br>") Else Msgbox(i & " is even.<br>") End If I'm unable to pass my array through

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.