The Wayback Machine - https://web.archive.org/web/20250123105657/https://www.geeksforgeeks.org/introduction-to-arrays-data-structure-and-algorithm-tutorials/
Open In App

Getting Started with Array Data Structure

Last Updated : 05 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Array is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming.

Basic terminologies of Array

  • Array Index: In an array, elements are identified by their indexes. Array index starts from 0.
  • Array element: Elements are items stored in an array and can be accessed by their index.
  • Array Length: The length of an array is determined by the number of elements it can contain. 

Memory representation of Array

In an array, all the elements are stored in contiguous memory locations. So, if we initialize an array, the elements will be allocated sequentially in memory. This allows for efficient access and manipulation of elements.

Memory-Representation-of-Array-(1)

Declaration of Array

Arrays can be declared in various ways in different languages. For better illustration, below are some language-specific array declarations:

C++
// This array will store integer type element
int arr[5];      

// This array will store char type element
char arr[10];   

// This array will store float type element
float arr[20];  
C
// This array will store integer type element
int arr[5];      

// This array will store char type element
char arr[10];   

// This array will store float type element
float arr[20];  
Java
// This array will store integer type element
int arr[];     

// This array will store char type element
char arr[];   

// This array will store float type element
float arr[];  
Python
# In Python, all types of lists are created same way
arr = []
C#
// This array will store integer type element
int[] arr;

// This array will store char type element
char[] arr2;

// This array will store float type element
float[] arr3;
Javascript
// JS code
let arr = []

Initialization of Array

Arrays can be initialized in different ways in different languages. Below are some language-specific array initializations:

C++
int arr[] = { 1, 2, 3, 4, 5 };
char arr[5] = { 'a', 'b', 'c', 'd', 'e' };
float arr[10] = { 1.4, 2.0, 24, 5.0, 0.0 };
C
int arr[] = { 1, 2, 3, 4, 5 };
char arr[5] = { 'a', 'b', 'c', 'd', 'e' };
float arr[10] = { 1.4, 2.0, 24, 5.0, 0.0 };
Java
int arr[] = { 1, 2, 3, 4, 5 };
char arr[] = { 'a', 'b', 'c', 'd', 'e' };
float arr[] = { 1.4f, 2.0f, 24f, 5.0f, 0.0f };
Python
# This list will store integer type elements
arr = [1, 2, 3, 4, 5]

# This list will store character type elements (strings in Python)
arr = ['a', 'b', 'c', 'd', 'e']

# This list will store float type elements
arr = [1.4, 2.0, 24.0, 5.0, 0.0]  # All float values
C#
int[] arr = { 1, 2, 3, 4, 5 };
char[] arr = { 'a', 'b', 'c', 'd', 'e' };
float[] arr = { 1.4f, 2.0f, 24f, 5.0f, 0.0f };
JavaScript
let arr = [ 1, 2, 3, 4, 5 ];
let arr = [ 'a', 'b', 'c', 'd', 'e' ];
let arr = [ 1.4, 2.0, 24, 5.0, 0.0 ];

Why do we Need Arrays?

Assume there is a class of five students and if we have to keep records of their marks in examination then, we can do this by declaring five variables individual and keeping track of records but what if the number of students becomes very large, it would be challenging to manipulate and maintain the data.

What it means is that, we can use normal variables (v1, v2, v3, ..) when we have a small number of objects. But if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.

Importance-of-Array

Types of Arrays

Arrays can be classified in two ways:

  • On the basis of Size
  • On the basis of Dimensions
Types-of-Arrays

Types of Arrays on the basis of Size:

1. Fixed Sized Arrays:

We cannot alter or update the size of this array. Here only a fixed size (i,e. the size that is mentioned in square brackets []) of memory will be allocated for storage. In case, we don’t know the size of the array then if we declare a larger size and store a lesser number of elements will result in a wastage of memory or we declare a lesser size than the number of elements then we won’t get enough memory to store all the elements. In such cases, static memory allocation is not preferred.

C++
// Method 1 to create a fixed sized array. 
// Here the memory is allocated at compile time.
int arr[5]; 
// Another way (creation and initialization both)
int arr2[5] = {1, 2, 3, 4, 5}; 

// Method 2 to create a fixed sized array
// Here memory is allocated at run time (Also
// known as dynamically allocated arrays)
int *arr = new int[5]; 
C
// Method 1 to create a fixed sized array. 
// Here the memory is allocated at compile time.
int arr1[5];
// Another way (creation and initialization both)
int arr2[5] = {1, 2, 3, 4, 5}; 


// Method 2 to create a fixed sized array
// Here memory is allocated at run time (Also
// known as dynamically allocated arrays)
int *arr = (int*)malloc(n * sizeof(int));
Java
// Fixed sized array examples
int[] arr1 = new int [5];

// Another way (Array creation and 
// initialization both)
int[] arr2 = {1, 2, 3, 4, 5};
Python
# Create a fixed-size list of length 5, 
# initialized with zeros
arr = [0] * 5

# Output the fixed-size list
print(arr)
C#
// Fixed sized array examples
int[] arr1 = new int [5];

// Another way (Array creation and 
// initialization both)
int[] arr2 = {1, 2, 3, 4, 5};


2. Dynamic Sized Arrays:

The size of the array changes as per user requirements during execution of code so the coders do not have to worry about sizes. They can add and removed the elements as per the need. The memory is mostly dynamically allocated and de-allocated in these arrays.

C++
#include<vector>

// Dynamic Integer Array
vector<int> v;
C
// C does not seem to support
// dynamic sized arrays as of now
Java
// Dynamic Integer Array
ArrayList<Integer> arr = new ArrayList<>();
Python
# Dynamic Array
arr = []
C#
// Similar to Java
ArrayList myList = new ArrayList(); 
JavaScript
// Dynamic Sized Array
let arr = new Array();  

Types of Arrays on the basis of Dimensions:

1. One-dimensional Array(1-D Array): You can imagine a 1d array as a row, where elements are stored one after another.

One-Dimensional-Array(1-D-Array)

2. Multi-dimensional Array: A multi-dimensional array is an array with more than one dimension. We can use multidimensional array to store complex data in the form of tables, etc. We can have 2-D arrays, 3-D arrays, 4-D arrays and so on.

Two-Dimensional-Array(2-D-Array-or-Matrix)

  • Three-Dimensional Array(3-D Array): A 3-D Multidimensional array contains three dimensions, so it can be considered an array of two-dimensional arrays.

Three-Dimensional-Array(3-D-Array)

Operations on Array

1. Array Traversal:

Array traversal involves visiting all the elements of the array once. Below is the implementation of Array traversal in different Languages:

C++14
int arr[] = { 1, 2, 3, 4, 5 };
int len = sizeof(arr) / sizeof(arr[0]);
// Traversing over arr[]
for (int i = 0; i < len; i++) {
    cout << arr[i] << " ";
C
int arr[] = { 1, 2, 3, 4, 5 };
int len = sizeof(arr) / sizeof(arr[0]);
// Traversing over arr[]
for (int i = 0; i < len; i++) {
    printf("%d ", arr[i]);
}
Java
int arr[] = { 1, 2, 3, 4, 5 };
// Traversing over arr[]
for (int i = 0; i < arr.length; i++) {
    System.out.print(arr[i] + " ");
Python
# This list will store integer type elements
arr = [1, 2, 3, 4, 5]

# Traversing over arr
for i in range(len(arr)):
    print(arr[i], end=" ")
C#
int[] arr = { 1, 2, 3, 4, 5 };
// Traversing over arr[]
for (int i = 0; i < arr.Length; i++)
    Console.Write(" " + arr[i]);
JavaScript
let arr = [1, 2, 3, 4, 5]
// Traversing over arr[]
for (let x of arr)
    console.log(x)

2. Insertion in Array:

We can insert one or multiple elements at any position in the array. Below is the implementation of Insertion in Array in different languages:

C++
// Function to insert element
// at a specific position
void insertElement(int arr[], int n, int x, int pos)
{
    // shift elements to the right
    // which are on the right side of pos
    for (int i = n - 1; i >= pos; i--)
        arr[i + 1] = arr[i];
 
    arr[pos] = x;
}
C
// Function to insert element
// at a specific position
void insertElement(int arr[], int n, int x, int pos)
{
    // shift elements to the right
    // which are on the right side of pos
    for (int i = n - 1; i >= pos; i--)
        arr[i + 1] = arr[i];

    arr[pos] = x;
}
Java
static void insertElement(int arr[], int n, int x, int pos)
{
    // shift elements to the right
    // which are on the right side of pos
    for (int i = n - 1; i >= pos; i--)
        arr[i + 1] = arr[i];
    arr[pos] = x;
}
Python
# Example usage
arr = [1, 2, 3, 4, 5]
x = 10  # Element to be inserted
pos = 2  # Position to insert the element

arr.insert(pos, x)

# Print the updated list
print("Updated List:", arr)
C#
static void insertElement(int[] arr, int n, int x, int pos)
{
    // shift elements to the right
    // which are on the right side of pos
    for (int i = n - 1; i >= pos; i--)
        arr[i + 1] = arr[i];
    arr[pos] = x;
}
JavaScript
// javascript Program to Insert an element
// at a specific position in an Array
function insertElement(arr, n, x, pos)
{
    // shift elements to the right
    // which are on the right side of pos
    var i = n - 1;
    for (i; i >= pos; i--)
    {
        arr[i + 1] = arr[i];
    }
    arr[pos] = x;
}

3. Deletion in Array:

We can delete an element at any index in an array. Below is the implementation of Deletion of element in an array:

C++
// To search a key to be deleted
int findElement(int arr[], int n, int key);

// Function to delete an element
int deleteElement(int arr[], int n, int key)
{
    // Find position of element to be deleted
    int pos = findElement(arr, n, key);

    if (pos == -1) {
        cout << "Element not found";
        return n;
    }

    // Deleting element
    int i;
    for (i = pos; i < n - 1; i++)
        arr[i] = arr[i + 1];

    return n - 1;
}

// Function to implement search operation
int findElement(int arr[], int n, int key)
{
    int i;
    for (i = 0; i < n; i++)
        if (arr[i] == key)
            return i;
    // Return -1 if key is not found
    return -1;
}
C
// C program to implement delete operation in a
// unsorted array
#include <stdio.h>
 
// To search a key to be deleted
int findElement(int arr[], int n, int key);
 
// Function to delete an element
int deleteElement(int arr[], int n, int key)
{
    // Find position of element to be deleted
    int pos = findElement(arr, n, key);
 
    if (pos == -1) {
        printf("Element not found");
        return n;
    }
 
    // Deleting element
    int i;
    for (i = pos; i < n - 1; i++)
        arr[i] = arr[i + 1];
 
    return n - 1;
}
 
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
    int i;
    for (i = 0; i < n; i++)
        if (arr[i] == key)
            return i;
     // Return -1 if key is not found
    return -1;
}
Java
// function to search a key to
    // be deleted
    static int findElement(int arr[], int n, int key)
    {
        int i;
        for (i = 0; i < n; i++)
            if (arr[i] == key)
                return i;
         // Return -1 if key is not found
        return -1;
    }
 
    // Function to delete an element
    static int deleteElement(int arr[], int n, int key)
    {
        // Find position of element to be
        // deleted
        int pos = findElement(arr, n, key);
 
        if (pos == -1) {
            System.out.println("Element not found");
            return n;
        }
 
        // Deleting element
        int i;
        for (i = pos; i < n - 1; i++)
            arr[i] = arr[i + 1];
 
        return n - 1;
    }
Python
# Initialize a list
arr = [10, 20, 30, 40, 50]

# Value to delete
key = 40

# Remove the element with the specified value
# if present in the list
if key in arr:
   arr.remove(key)
else:
   print("Element Not Found")

# Output the modified list
print(arr)  # Output: [10, 20, 30, 50]
C#
int findElement(int[] arr, int n, int key)
{

    int i;
    for (i = 0; i < n; i++)
        if (arr[i] == key)
            return i;

    return -1;
}

// Function to delete an element
int deleteElement(int[] arr, int n, int key)
{
    // Find position of element
    // to be deleted
    int pos = findElement(arr, n, key);

    if (pos == -1) {
        Console.WriteLine("Element not found");
        return n;
    }

    // Deleting element
    int i;
    for (i = pos; i < n - 1; i++)
        arr[i] = arr[i + 1];

    return n - 1;
}
JavaScript
// function to search a key to  be deleted
function findElement(arr,n,key)
{
    let i;
    for (i = 0; i < n; i++)
        if (arr[i] == key)
            return i;
    return -1;
} 
     
// Function to delete an element
function deleteElement(arr,n,key)
{
    // Find position of element to be deleted
    let pos = findElement(arr, n, key);
      
    if (pos == -1)
    {
        document.write("Element not found");
        return n;
    }
    // Deleting element
    let i;
    for (i = pos; i< n - 1; i++)
        arr[i] = arr[i + 1];
    return n - 1;
}

4. Searching in Array:

We can traverse over an array and search for an element. Below is the implementation of Searching of element in an array:

C++
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
    int i;
    for (i = 0; i < n; i++)
        if (arr[i] == key)
            return i;
 
    // If the key is not found
    return -1;
}
C
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
    int i;
    for (i = 0; i < n; i++)
        if (arr[i] == key)
            return i;
 
    // If the key is not found
    return -1;
}
Java
// Function to implement search operation
int findElement(int arr[], int n, int key)
{
    for (int i = 0; i < n; i++)
        if (arr[i] == key)
            return i;

    // If the key is not found
    return -1;
}
Python
# Function to implement search operation
def find_element(arr, n, key):
    for i in range(n):
        if arr[i] == key:
            return i
    return -1
C#
// Function to implement
// search operation
int findElement(int[] arr, int n, int key)
{
    for (int i = 0; i < n; i++)
        if (arr[i] == key)
            return i;

    // If the key is not found
    return -1;
}
JavaScript
// Function to implement search operation 
function findElement( arr, n, key)
{
    let i;
    for (i = 0; i < n; i++)
        if (arr[i] == key)
            return i;
 
    return -1;
}

Complexity Analysis of Operations on Array

Time Complexity:

Operation

Best Case

Average Case

Worst Case

Traversal

θ(N)

θ(N)

θ((N)

Insertion

θ((1)

θ(N)

θ(N)

Deletion

θ(1)

θ(N)

θ(N)

Searching

θ(1)

θ(N)

θ(N)

Auxiliary Space

Operation

Best Case

Average Case

Worst Case

Traversal

θ(1)

θ(1)

θ(1)

Insertion

θ(1)

θ(N)

θ(N)

Deletion

θ(1)

θ(N)

θ(N)

Searching

θ(1)

θ(1)

θ(1)

Next Read: Applications, Advantages and Disadvantages of Array

Frequently Asked Questions (FAQs) on Arrays

1. What is an array in data structure with example?

An array is a collection of items of the same data type stored at contiguous memory locations. Ex. int arr[5] = {1,2,3,4,5};

2. Why array is a data structure?

Arrays store elements of the same type, they are classified as homogeneous data structures. They can store numbers, strings, characters, boolean values (true and false), objects, and so on.

3. What data structure is an array?

 An array is a linear data structure that stores similar elements in contiguous memory locations.

4. What are the types of arrays?

There are majorly two types of arrays:

  • One dimensional array
  • Multidimensional array

5. How is data stored in an array?

An array is a collection of items of the same data type stored at contiguous memory locations or says the elements are stored one after another in memory. An array uses an index system starting at 0 and going to (n-1), where n is its size.

6. Difference between array and structure?

The structure can contain variables of different types but an array only contains variables of the same type. 

7. What are the limitations of an array?

An array is a collection of items of the same data type. That means, in an integer array only integer values can be stored, while in a float array only floating values and character array can have only characters. Thus, no array can have values of two data types.

8. What are the advantages of an array?

There are multiple advantages of array data structure and some of them are:

  • Arrays allow random access to elements. This makes accessing elements by position faster.
  • Arrays store multiple data of similar types with the same name.
  • Array data structures are used to implement the other data structures like linked lists, stacks, queues, trees, graphs, etc.

9. What is the purpose of using arrays?

An array is used when several variables of the same type need to be used, and it can be defined as a sequence of objects of the same type.  

10. What is a multidimensional array?

A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form. Data in Multidimensional Arrays are stored in row-major order. 




Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg