Data Structures-Arrays Overview

Array

What are Arrays?

The array is a fixed-size sequenced collection of variables belonging to the same data types. The values are stored in contiguous memory location. The syntax for declaring array is:

Data_type   Array_name[Array_size];

Here, Data_type is the type of data which we need to declare for the Arrays. Array_name is the name given to the array and Array_size is the size given to the array.

Every item stored in an array is termed as element. Each memory location of an element in an array is denoted by a numerical index which is used for identifying the element.

                      

From the above figure,

  • The Array stores element in a contiguous memory location such as 100, 101, 102, 103, etc.
  • The each element in the Array can be easily identified by the index number.
  • We can identify number using the index value. The memory location of next index depends on the data type we use. 

Types of indexing in Array

  • Zero-based indexing : The first element in the array is indexed by subscript of 0
  • One-based indexing : The first element in the array is indexed by subscript of 1
  • N-based indexing : The base index of an array can be easily chosen. The n-based indexing allow negative index values and other scalar data types like enumerations, or characters can be used as an array index.

Why do you need Arrays for Building Specific Data Structure?

A program works with many variables which hold comparable forms of data. If we are not using arrays, the number of variables declared will increase. By using arrays, the number of variable reduces i.e., a single name is given for multiple values. Here in arrays, we deal with index values.

Example

Instead of storing the marks of the student scored in five subjects in separate variable, we can store it in array of the student_name[5].

John[5] = {60,66,72,68,80}

Here in the above example, the indices hold the subject name.

Collecting input data in Arrays

Arrays are mainly used for making a collection of input data which arrive in random order. An excellent example can be counting of votes in an election. The program can be written to tally the votes of a four candidates in an election. The candidate names are nothing but the index of the array such as cand 0, cand 1, cand 2, cand 3, etc. The votes arrives once at a time, where a vote for Candidate i is denoted by the number i. So according to the example, the structure would be like:

int votes[4];

Advantages of using arrays:

  • Arrays allow random access of elements. This makes accessing elements by position faster.
  • Arrays have a better cache locality that makes a big difference in performance.