Arrays

Arrays

What is an Array?

  • An array is a data structure that holds a fixed number of values of a single type.
  • Arrays allow you to store multiple values in a single variable, which is useful when you want to group similar data together.

Array Characteristics

  • Each value in an array is identified by an index, which represents the position of the element within the array.
  • The first index of an array is usually zero, not one.
  • To access a particular item in the array, we use the name of the array followed by the index in square brackets. For example, if ‘arr’ is an array, and we want the third element, we would write ‘arr[2]’.

Creating Arrays

  • When creating an array, you need to declare the type of data it will hold (e.g., integers, floats, characters).
  • The size of the array must also be declared when it is created, and this does not generally change once the array is initialised.

Array Operations

  • Arrays can be manipulated in several ways. Common actions include adding a new item to the array, changing an existing item, and searching for items within the array.

  • Adding items to an array can often only be done if there is space. If the array is full, it’s generally not possible to add more items.

  • Changing items involves targeting an item with its index and assigning a new value to it.

  • Searching in an array entails checking each item until you find the one you’re looking for. This is the case unless your array is sorted, then you can use more efficient search algorithms.

Multidimensional Arrays

  • Multidimensional arrays are arrays of arrays. They are used to store complex data structures like matrices.
  • Index positions in multidimensional arrays are identified using multiple indices, one for each dimension.

Utilities and Sorting

  • There are also built-in functions for arrays, depending on the programming language, which provide additional functionality.
  • For instance, sorting an array rearranges the elements in a specific order, either ascending or descending. This can be achieved usually by calling a built-in sorting function.

Arrays play a crucial role in programming. They provide a simple way to store, sort and access multiple data points quickly and efficiently.