Tuesday, December 6, 2011

Data Structures: Arrays

A data structure is a way of storing and organizing data. There are many types of data structures, but the array is the most common. Arrays store variables of one data type, which can be accessed through indexing. Arrays are not formally supported in Python (however, there are many mutations based on arrays), so I will only go over arrays in C++ and Java.

Arrays
General Structure

  • Arrays can be defined and initialized in two ways:

          int prime_numbers [10];

          int prime_numbers [] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

  • In the first example the size is declared explicitly, and the data is added later (probably with a for loop). In the second example the size is declared implicitly by assigning ten data elements in curly braces.
  • In the first case the data elements can be set through indexing. The first data element in an array is always at index zero, so the last index is one less than the total number of elements:

          prime_numbers[0] = 2;
          prime_numbers[1] = 3;
          prime_numbers[2] = 5;
          (...)
          prime_numbers[9] = 29;


  • This can also be accomplished with a for loop:

          for (int n = 0; n < 11; n++)
         {
             prime_numbers[n] = next_prime_number;
         }


  • Data elements can be accessed similarly to how they are set:

          first_prime_number = prime_numbers[0];             // should equal 2




This is pretty much the extent of what the built-in array class can do in C++. There are more things that are possible in Java, but I'm going to wait until after I write about functions and classes to get into that.

There are also multi-dimensional arrays, which I will save until later as well.

No comments:

Post a Comment