Quantcast
Channel: VBForums - CodeBank - Visual Basic 6 and earlier
Viewing all articles
Browse latest Browse all 1489

Single for-loop traversal over 2D/3D arrays

$
0
0
This source code shows the traversal of a two-dimensional array by one for-loop structure. A 2D-array variable (A) is declared. A string variable t is initially set to empty. A variable v is set to zero and it represents the main counter of the for-loop. Another two variables (ie. i and j) are initialized with value zero and are the main coordinates for element identification. Each dimension of array A is stored in variables n and m, namely the number of rows in n and the number of columns in m. The upper limit of the for-loop is calculated based on the two known dimensions n and m. Thus, m times n establishes the upper limit of the for-loop. Here, the value of the counter v from the for-loop is used to calculate the i and j values that are used as an index to traverse the array variable A. The value of variable j is computed as the v % m and the result of this expression indicates the reminder (ex. 5 mod 3 is 2). The secret to this implementation is a condition that increments a variable i (rows) each time j (columns) equals zero. Thus, in this manner this approach provides the i and j values that a nested for-loop provides. At each iteration, the value from an element is added to the content of variable t. Once the end of the for-loop is reached, the value collected in variable t is printed in the output for inspection.

Please also see: Single "for-loop" traversal over three dimensional arrays.

Code:

Sub main()

    Dim A(0 To 1, 0 To 2) As String
    Dim i As Integer
    Dim t As String

    A(0, 0) = "a"
    A(0, 1) = "b"
    A(0, 2) = "c"
    A(1, 0) = "d"
    A(1, 1) = "e"
    A(1, 2) = "f"
   
   
    n = UBound(A, 1) - LBound(A, 1) + 1  ' rows
    m = UBound(A, 2) - LBound(A, 2) + 1  ' columns
   
    i = 0
    j = 0
   
    For v = 0 To (n * m) - 1
   
        j = v Mod m

        If (v <> 0 And j = 0) Then i = i + 1
       
        t = t & v & " A(" & i & "," & j & ")="
        t = t & A(i, j) & vbCrLf

    Next v
   
    Debug.Print (t)

End Sub

Some mirrored examples in different programming languages (including VB6), may also be of interest.

Viewing all articles
Browse latest Browse all 1489

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>