Arrays

Arrays

Definition of Arrays

  • An array is a data structure that consists of elements of the same data type.
  • Basically, an array is a collection of like-typed variables that are referred to by a common name.
  • It can hold a fixed number of values of a single type, which makes it a static data structure.

Structure of Arrays

  • Arrays are structured as a sequence of elements, each with a corresponding index or numeric key.
  • The index (or key) is used to access individual elements in the array.
  • An array can be multi-dimensional. For example, a 2-dimensional array is like a matrix.

Usage of Arrays

  • Arrays are commonly used to store data that is naturally ordered, like a list of student grades or a list of names in a phone directory.
  • Arrays allow you to access or modify data efficiently using the index.
  • All elements in an array exist in contiguous memory locations allowing fast access.

Operations on Arrays

  • Basic operations that you can perform on an array include: initialize, insert, search, delete and update.
  • The initialize operation is used to only define the size of an array.
  • The insert operation is used to add an element at a given index in the array.
  • The search operation allows you to find a specific element in an array.
  • The delete operation allows you to remove an element from a particular index in an array.
  • The update operation allows you to change or update the value of an element in the array.

Array Indexing

  • Indexing in arrays usually starts from zero. So the first element of an array has index 0, the second element has index 1, and so on.

Arrays and Memory

  • As arrays store all elements in contiguous blocks of memory, they are space-efficient and allow easy accessing of its elements.
  • However, because of their fixed size, arrays may not be ideal when we need to add or remove data dynamically. In such cases, other data structures like lists or linked lists may be more appropriate.

Manipulating Arrays in Programming

  • In programming, you often need to use loops (such as for loops or while loops) to manipulate arrays, such as to initialise them or to process each element.
  • Array elements can be used just like normal variables – you can display them, perform arithmetic operations on them, and so on.