DS Arrays

What is Array?

Arrays are defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in programming language which can store the primitive type of data such as int, char, double, float, etc. Array is the simplest data structure where data element are stored in continuous memory location but each data element can be randomly accessed by using its index number.

What is index number?
Each slot/data in the array can be referenced with a number and the reference number is index.

we declare array by: int arr[5]; (in C) or int[] arr = new int[5]; (in Java).

What is a Static Array?

A static array is a fixed length container containing n elements indexable from the range [0, n-1] where n is total number of elements.

When and Where Static Array is used used?

Almost in every program we see the use of array. It makes our program more reliable. Hence here are some purposes:

  • Storing and accessing sequential data
  • Temporarily storing objects
  • Used by IO routines as buffers
  • Lookup tables and inverse lookup tables
  • Can be used to return multiple values from a funtion
  • Used in dynamic programming to cache answers to subproblems.

In above image, you can see that each value as its index. Index increases by 1 for next data.

What is Dynamic Array?

Only difference from static array is the dynamic array can grow and shrink in size. Take a look at this example:

              A = [34, 4]
A.add(-7)     A = [34, 4, -7]
A.add(34)     A = [34, 4, -7, 34]
A.remove(4)   A = [34, -7, 34]

Advantages of using an array:

To store the large number of data, we need to define a large number of variables. It would be very difficult to remember names of all the variables while writing the programs. Instead of naming all the variables with a different name, it is better to define an array and store all the elements into it.

  • Any element in the array can be directly accessed by using the index.

  • Traversing an array is a very simple process, we just need to increment the base address of the array in order to visit each element one by one.

  • It uses single name for the group of variables of the same type therefore, it is easy to remember the name of all the elements of an array.

Take a look at this example written in C programming:

Without Array:

#include <stdio.h> void main () { int mark1 = 56, mark2 = 78, mark3 = 88, mark4 = 76, mark5 = 56; int sum = mark1 + mark2 + mark3 + mark4 + mark5; printf("Total Marks: %d", sum); }
We've used 5 different variables to store same type of data. i.e. marks

With Array:

#include <stdio.h> void main () { int marks[5] = {56,78,88,76,89}; int sum=0, i; for (i=0; i<5; i++) { sum = sum + marks[i]; } printf("Total Marks: %d", sum); }

We've used only one variable to store all marks and accessed all elements with index via loop.

Time Complexity Previous Next Operations in Arrays