How to iterate over multiple arrays?
I'm new to this, so sorry if my question was asked before. I have searched but could not find or possibly recognize an answer. I am using visual studio 2008 and create an application in vb.net.
I have 4 arrays named: - account1 account2 account3 account4. They all have 4 elements. I want to effectively assign values to elements in arrays. I thought two for the next loops would do it. My pseudo code looks something like this:
for i=1 to 4
for c= 0 to 3
account(i)(c)= 'mydata' /so account(i) would be account1 etc and c the element
next c
next i
and hence all elements of all arrays get populated without me to set up a fornext loop for each individual array name. How can I achieve this please.
Hopefully I've provided enough information to be helpful and that you can help. Thanks to everyone and all the advice.
If I understand correctly, why not:
For i as integer = 0 to 3
account1(i) = "Account1"
account2(i) = "Account2"
account3(i) = "Account3"
account4(i) = "Account4"
Next
Edit VB.Net for Qua's answer :
dim accounts(4,4) as integer
for i as integer = 0 To accounts.GetUpperBound(0)
for j as integer = 0 To accounts.GetUpperBound(1)
accounts(i, j) = new integer 'not needed for intergers, but if you had a class in here'
accounts(i, j) = i*j;
next
next
a source to share
You should create a multidimensional array instead of 4 arrays, which will allow you to completely loop through the arrays.
int[,] accounts = new int[4,4] // 4 accounts with 4 elements
for (int i = 0 ; i < accounts.GetUpperBound(0); i++)
for (int j = 0 ; i < accounts.GetUpperBound(1); j++)
accounts[i,j] = i*j;
next
next
a source to share
As I read your example code, I don't think you need to use 2 separate loops, as if I were right, you are assigning the same value to the i-th position of your array for example:
array1 (i) = array2 (i) = array3 (i) = array4 (i)
In the above example, you can write something like this (in pseudocode):
for i = 0 to 3
account1(i) = MyData
account2(i) = MyData
account3(i) = MyData
account4(i) = MyData
next i
I think this is clearer than trying to write a loop for variable names, especially for the number of arrays you support
Another option, which may be more appropriate if you have many arrays, is to maintain a list of arrays, which can then be iterated over quite simply.
PseudoCode for this option:
for each array in listOfArrays
for i = 0 to 3
array(i) = MyData
next i
next
This is definitely clearer than trying to generate array names dynamically and is more maintainable, as well
a source to share