Console arrays and loops

callumh27

Member
Joined
Oct 6, 2009
Messages
7
Programming Experience
Beginner
Hi i'm new to VB, we have just started to learn it in school, but I have come across a problem.

I want the computer to automate the creation and assignment of arrays, but I just get errors with my code.

Here is what I have so far.


Dim k As Integer
Dim test(k) As Integer

For i = 1 To 5

k = i - 1

test(k) = i

Next

Console.Write(test(k))

Console.ReadLine()
End Sub




Can someone show me how to do this properly?


Could someone also show me how to print the entire contents of an integer array?


Thanks

Callum


Edit:

I have also tried, this but it just returns a 0 rather than the first value of the array which should be a 1.


Dim array(5) As Integer
Dim i As Integer
Dim k As Integer
Dim x As Integer


For i = 1 To 5

k = i
x = i - 1


ReDim array(k)

array(x) = i

Next

Console.WriteLine(array(0))

Console.ReadLine()
 
Last edited:
First of all:


Dim k As Integer
Dim test(k) As Integer


won't work because you haven't given a value to k, which must be done before you can dim an array with that value.


Now let's suppose you give k a value of 5:

Dim k As Integer = 5
Dim test(k) As Integer


You were trying to do this, which won't do what you want:

For i = 1 To 5
k = i - 1
test(k) = i
Next


You are assigning the value of i-1 to the 5th index of the test array, and nothing is being assigned to the other indexes. This is what you meant to do:

For i = 0 To 5
test(i) = i
Next

That will assign the values ranging from 0 to 5 to the matching indexes in your array.

Then, to print them out separately, do this:

For i = 0 To 5
Console.WriteLine(test(i))
Next
 
Back
Top