Showing posts with label Arrays. Show all posts
Showing posts with label Arrays. Show all posts

Thursday, March 19, 2009

Introduction to Programming :: Multidimensional Arrays

In the last post arrays were discussed and implemented. The next step to arrays is multidimensional arrays. Multidimentsional arrays can be as large as needed but they do use up more and more memory depending on the number of dimensions. Declaring multidimensional arrays is similar to what was previously discussed. A bidimensional array is declared as follows: int newArray [2] [4]; In order to reference a location, specify the name of the array and the locations as follows: newArray [1] [2]; . This may be hard to visualize but what this means is [row] [column]. By calling newArray[1][2]; the user is trying to reference row 1, column 2. Row 1 column 2 yields a value of 4. Remember that declaring a variable such as int newArray [2] [4]; is defining the dimensions of the array. If a reference to the location newArray[2] [4] was made; the program would not work. The correct way is to reference newArray [1] [3] instead.



The following code will fill the table above. This is controlled by two for loops. The first loop controls which row is being filled. The second for loop is computing inside the first loop in order to increment a counter and fill the columns in the row. Example: first row is filed 1,2,3,4; second row is filled 2,4,6,8.

Tuesday, March 17, 2009

Introduction to Programming :: Arrays

Cplusplus.com defines an array as: "An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier."

In order to intialize an array you simply declare it as follows: int newArray [10]; (type name [ size ];) This creates an array of integers and declares the name and size. There are many ways to fill an array. An example would be int newArray [3] = { 1, 2, 3,}. Arrays can consist of any data type and can also include records, meaning multiple fields per item. (this will be discussed in future posts.) Array data is accessed by looking at a memory location. (newArray[2];) Assuming we have an array of integers 1,2,3 array location [2] is equal to the integer 3. The first memory location in the array is referenced by newArray[0]. The following code is an example of initializing an array and using a for loop to print out the values of the entire array.




In the next post expect to see more about arrays and multidimensional arrays.