Introduction to Array

Introduction to Array
Introduction to Array

In computer science, an array is a collection of elements or items of same type, stored at continuous memory locations. Each value is identified by at least one key or array index, which makes it easy to access the position of element faster and easy.

To understand this in a simpler way, think of fleet of stairs as an array and each step is placed with your friends. Now, you can easily identify the position of your friend by knowing the count of the stair step they are standing on.

Look at the above example and imagine a top-level view of a staircase where ‘Sam’ is at the base of the staircase and ‘David’ is at the top. You can identify your friend by the step number on which they are/were.

Types of indexes:

  1. 0 – based indexes – first element is indexed by 0
  2. 1 – based indexes – first element is indexed by 1
  3. N – based indexes – first element is indexed by any nth number

Advantages of using arrays

  1. Arrays allows easier and random processing of data
  2. Used to represent multiple data items of same type by single name only

Disadvantages of arrays

  1. Static nature of an array: memory allocated to the array cannot be increased or decreased
  2. Since array is of fixed size, memory wastage is more. We cannot allocate neither lesser nor extra memory because it can cause a problem in either of the cases
  3. Elements are stored in consecutive memory locations, so insertion and deletion are quite time-consuming

Array Examples

In C/C++/Java

//Character array 
char array_1[] = {'a', 'b', 'c', 'd', 'e'};

//Integer array
int array_2[] = {1, 2, 3, 4, 5};

//if you want to access the element at ith position then simple type
array_1[2] will give an output: ‘c’
array_2[3] will give an output: 4

In PHP

$cars = array("Audi", "Ferrari", "Toyota");
$car_number = array("Audi"=>3278, "Ferrari"=>1290, "Toyota"=>8855)

$cars[1] will give you an output: 'Ferrari'
$car_number['Toyota'] will give an output: 8855

 

You may also like...

Leave a Reply