Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Visual Basic (http://www.programmingforums.org/forum18.html)
-   -   Redim Problem (http://www.programmingforums.org/showthread.php?t=621)

Johnny_English Sep 22nd, 2004 9:48 AM

Hello,
I'm a beginner in VB and I'm having trouble with my code. It's a prime number calculator. Here is the function:

:

Public Function prime(x As Integer)
  Dim primes(0) As Integer
  primes(0) = 2
  For y = 2 To x
    bound= UBound(primes)
    For Index = 0 To bound
      If (y Mod primes(Index)) = 0 Then
        Exit For
      End If
    Next Index
    If Index = bound Then
        ReDim Preserve primes(boun + 1)
        primes(bound + 1) = y
    End If
  Next y
End Function

It receives the argument x passed by main.

When I run the code I get "Array already dimentioned."

Infinite Recursion Sep 22nd, 2004 10:09 AM

Some of your variables are misspelled, others are undefined... I don't have VB on hand right now, but try this:

:

Public Function prime(ByVal x As Integer)
    Dim primes(0) As Integer
    Dim bound, y, Index As Integer

    primes(0) = 2
    For y = 2 To x
      bound = UBound(primes)
      For Index = 0 To bound
        If (y Mod primes(Index)) = 0 Then
          Exit For
        End If
      Next Index
      If Index = bound Then
        ReDim Preserve primes(bound + 1)
        primes(bound + 1) = y
      End If
    Next y
  End Function


Berto Sep 22nd, 2004 10:09 AM

edit: ignore what i wrote if you read it.

Infinite Recursion Sep 22nd, 2004 10:38 AM

it was pretty good advice too Berto.

The code above compiles and runs fine in VB .NET

Berto Sep 22nd, 2004 10:41 AM

nah i said something that was wrong, by a mile so thought i should get rid of it.

Ooble Sep 22nd, 2004 11:15 AM

In VB (not sure about VB .NET, but as you're not using that, it's irrelevant), if you want to redimension an array, you have to define it without any dimensions:
:

Dim primes() as Integer

Then redimension it at the start.


All times are GMT -5. The time now is 4:11 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC