Pages

Monday, June 24, 2013

How to Build a Computer Table

How to Build a Computer Table

You can build a computer table using the most general of programming concepts, the array and the nested loop. These concepts can be used with any programming language. The array is often used to store large amounts of information. The nested loop is basically two loops, one inside the other. Of course, you can use a spreadsheet or a database program to create a table, too. But the array and the nested loop are the general logic concepts that are often used in programming. You can build a simple table in Visual Basic using an array and two loops.

Instructions

Building a Computer Table

    1

    Start Excel, open a new spreadsheet, and hold "Alt" and "F11" to enter the Visual Basic Editor. Select "Insert" and "Module" and click in the new module to start copying code.

    2

    Type in the following code.

    Sub TestArray()
    ' Comments start with quote sign
    'Activate worksheet and go to cell A1
    Worksheets("Sheet1").Activate
    Application.Goto Reference:=Worksheets("Sheet1").Range("A1")

    ' Setup a 2-dimensional array having 5 places in first dimension and 5 places in second dimension
    Dim Vis(1 To 5, 1 To 5) As Integer

    ' Start Outer loop in nested loop structure
    For i= 1 To 5

    'Start inner loop in nested loop structure
    For a=1 To 5
    'Store a value in array (For this example, program simply counts and stores)
    Vis(I, a) = (I * 5) + a -- 5
    'Put the array value in your spreadsheet so you can see it
    ActiveCell.Value = Vis(I, a)
    'Move down one cell on your spreadsheet
    ActiveCell.Offset (rowOffset:=1, columnOffset:=0).Activate
    'end of inner loop
    Next a
    ActiveCell.Offset(rowOffset:=-5, columnOffset:=1).Activate
    'end of outer loop
    Next I
    End Sub

    3

    Note that you have defined a 2-dimensional array in the statement, "Dim Vis(1 To 5, 1 To 5) As Integer."

    4

    Note the nested loops created with two "For...Next statements."

    5

    Run the program by clicking the blue triangle under "Run", and click the green "X" in the upper left to return to the spreadsheet and view the output of the program. Review the spreadsheet and understand that a 2-dimensional array that has a 5x5 structure has 25 storage positions. Confirm that your spreadsheet looks something like this:

    16111621
    27121722
    38131823
    49141924
    510152025

0 comments:

Post a Comment