• Articles
  • Tutorials
  • Interview Questions

What is an Array? A Complete Guide With Examples

To grasp their significance, it’s essential to dive deep into the core concepts of what array is in data structure, its characteristics, along with its diverse applications across various domains. So, whether you’re working on data analysis, game development, or any other field, mastering arrays is a crucial step towards becoming a proficient programmer.

Given below are the following topics we are going to cover:

Learn Java programming through our Java Programming Course:

What is an Array?

An array is a crucial data structure in computer programming that allows for the organized storage of multiple elements under a single variable name. These elements can be of the same data type, like integers or strings, or even a mixture of different types. What sets arrays apart is their ability to be accessed using an index or a key, with each element having a unique position within the array.

The order of elements in an array is essential, as they are arranged sequentially based on their indices. This characteristic enables quick and direct access to any element within the array, making it an efficient tool for data manipulation. It’s worth noting that arrays typically have a fixed size, meaning the number of elements they can hold is predetermined at the time of declaration. However, some programming languages offer dynamic arrays that can be resized as needed.

Interested in becoming a Full Stack Developer? Take our Full Stack Development Course to take your first step.

Why Do We Need Array?

Arrays are essential in computer programming for several compelling reasons, and some are defined below:

  • Efficient Data Storage: Arrays provide a systematic way to store multiple pieces of data under a single variable. This compact arrangement minimizes the need for numerous individual variables, leading to more efficient memory usage.
  • Ordered Organization: Elements in an array are arranged in a specific order, typically indexed from 0 onward. This structured arrangement allows for easy access and manipulation of data based on its position.
  • Rapid Access to Elements: With the help of indices, elements within an array can be swiftly accessed. This allows for quick retrieval and modification of data, which is crucial in scenarios where speed is of the essence.
  • Simplified Data Processing: Arrays are invaluable for tasks involving large datasets, such as statistical analysis or image processing. They provide a structured way to manage and manipulate this data, making complex operations more manageable.
  • Streamlined Code: Without arrays, programmers would have to create and manage a multitude of variables, which can lead to cluttered and unmanageable code. Arrays condense this information, making the code more organized and easier to understand.

How is an Array Initialized?

An array can be initialized in several programming languages. I’ll provide examples in three commonly used languages: C++, Python, and JavaScript.

C++

In C++, you can initialize an array during its declaration or afterward using curly braces {}. Here’s an example:

// Initializing an array during declaration
int myArray[5] = {1, 2, 3, 4, 5};

Explanation

In this example, myArray is declared as an integer array with a size of 5 and is initialized with the values 1, 2, 3, 4, and 5.

Python

The common question that students always ask is what array in Python is. Thus, in Python, arrays are represented using lists. Lists can be initialized using square brackets []. Here’s an example:

# Initializing a list (Python's equivalent of an array)
my_list = [1, 2, 3, 4, 5]

Explanation

In this example, my_list is initialized with the values 1, 2, 3, 4, and 5.

JavaScript

In JavaScript, arrays can be initialized using square brackets []. Here’s an example:

// Initializing an array

let myArray = [1, 2, 3, 4, 5];

Explanation

In this example, myArray is initialized with the values 1, 2, 3, 4, and 5.

Get a comprehensive understanding of Recursion in Data Structure with our in-depth blog post!

Indexing in Array

Indexing in an Array refers to the method of accessing individual elements within the array. Each element in an array is assigned a specific position, known as an index, which allows for targeted retrieval and manipulation of data. Three types of indexing can be found in an array. They are as follows:

Zero-based Indexing

In zero-based indexing, the first element of the array is assigned an index of 0. Subsequent elements are assigned indices in sequential order (1, 2, 3, and so forth). This is the most prevalent type of indexing and is widely used in programming languages like C, C++, Python, and JavaScript.

Example:

Array: [10, 20, 30, 40, 50]

Indices:  0   1   2   3   4

One-based Indexing:

One-based indexing assigns the first element an index of 1. This indexing style is occasionally used in specific contexts, but it’s less common in mainstream programming languages.

Example:

Array: [10, 20, 30, 40, 50]

Indices:  1   2   3   4   5

Negative Indexing

Negative indexing allows you to access elements at the end of an array. In this scheme, the last element has an index of -1, the second to last element has an index of -2, and so forth. This method is specifically beneficial when you need to access elements from the end of an array without knowing their exact length.

Example:

Array: [10, 20, 30, 40, 50]

Indices: -5  -4  -3  -2  -1

To learn about Queue, go through our Queue in Java Blog.

Get 100% Hike!

Master Most in Demand Skills Now !

Types of Array in Data Structure

Within the field of data structures, arrays can be classified into various categories, depending on their attributes and implementation. Below are some prevalent array types in C++:

  • One-Dimensional Array: A one-dimensional array is a linear collection of elements where each element is identified by a single index. It is the most basic form of an array and is often used to represent lists or sequences of data.

Syntax:

datatype arrayName[size];

Example:

#include <iostream>
int main() {
    int numbers[5] = {10, 20, 30, 40, 50};
    // Accessing elements of the array
    std::cout << "Elements of the array: ";
    for(int i = 0; i < 5; i++) {
        std::cout << numbers[i] << " ";
    }
    return 0;
}

In this C++ example, we declare an array named numbers of size 5, which can hold integers. The elements of the array are initialized with the values 10, 20, 30, 40, and 50.

After declaring the array, we use a for loop to iterate over the elements and print them to the console.

Output:

Elements of the array: 10 20 30 40 50

This demonstrates how to declare and use a one-dimensional array in C++. The elements of the array can be accessed using their indices (0 to 4 in this case).

  • Multi-Dimensional Array: A multi-dimensional array in data structure is an array with more than one dimension. It can be thought of as an array of arrays, where each element is itself an array. Common types include 2D arrays (matrices), 3D arrays, and so on.

Syntax for 2D array:

datatype arrayName[rows][columns];

Example for 2D array:

#include <iostream>
int main() {
    int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    // Accessing elements of the 2D array
    std::cout << "Elements of the 2D array:" << std::endl;
    for(int i = 0; i < 3; i++) {
        for(int j = 0; j < 3; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}

In this C++ example, we declare a 2D array named matrix of size 3×3, which can hold integers. The elements of the 2D array are initialized in the nested curly braces.

After declaring the array, we use nested for loops to iterate over the elements. The outer loop iterates over the rows, and the inner loop iterates over the columns. We print the elements on the console.

Output:

Elements of the 2D array:

1 2 3 

4 5 6 

7 8 9 

This showcases how to declare and use a 2D array (in this case, a 3×3 matrix) in C++. Elements of the 2D array can be accessed using two indices: matrix[i][j], where i represents the row and j represents the column.

Syntax for 3D array:

data_type array_name[x][y][z];

Example for 3D array:

#include <iostream>
int main() {
    int cube[2][2][2] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
    // Accessing elements of the 3D array
    std::cout << "Elements of the 3D array:" << std::endl;
    for(int i = 0; i < 2; i++) {
        for(int j = 0; j < 2; j++) {
            for(int k = 0; k < 2; k++) {
                std::cout << cube[i][j][k] << " ";
            }
            std::cout << std::endl;
        }
        std::cout << std::endl;
    }
    return 0;
}

In this C++ example, we declare a 3D array named cube of size 2x2x2, which can hold integers. The elements of the 3D array are initialized in the nested curly braces.

After declaring the array, we use nested for loops to iterate over the elements. The three nested loops correspond to the three dimensions (x, y, and z) of the 3D array. We print the elements on the console.

Output:

Elements of the 3D array:

1 2 

3 4 

5 6 

7 8 

This demonstrates how to declare and use a 3D array (in this case, a 2x2x2 cube) in C++. Elements of the 3D array can be accessed using three indices: cube[i][j][k], where i, j, and k represent the x, y, and z coordinates, respectively.

  • Static Array: A static array has a fixed, predetermined size that cannot be changed after initialization. The size of a static array must be specified at compile time.

Syntax:

datatype arrayName[size] = {element1, element2, ...};

Example:

int staticArray[5] = {1, 2, 3, 4, 5};

  • Dynamic Array: A dynamic array, also known as a resizable array, can change in size dynamically during program execution. It automatically grows or shrinks as elements are added or removed.

Syntax (Python – using lists):

dynamicArray = []
dynamicArray.append(element)

Example:

dynamicArray = []
dynamicArray.append(1)
dynamicArray.append(2)
dynamicArray.append(3)

Various Array Operations in Python

In Python, arrays are commonly represented using lists. Here are various array operations in Python:

  • Accessing Elements: Retrieve the value of an element at a specific index.

Syntax:

element = array[index]

Example:

# Example of accessing an element in an array
numbers = [10, 20, 30, 40, 50]
# Accessing the third element (index 2)
element = numbers[2]
# Print the element
print(element)  

Output: 30

  • Updating Elements: Modify the value of an element at a specific index.

Syntax:

array[index] = newValue

Example:

# Example of updating an element in an array
numbers = [10, 20, 30, 40, 50]
# Updating the second element (index 1) to 25
numbers[1] = 25
# Print the updated array
print(numbers)  

Output: [10, 25, 30, 40, 50]

  • Insertion: Add a new element to the array at a specified index. This may involve shifting existing elements to accommodate the new ones.

Syntax:

array.insert(index, element)

Example:

# Example of inserting an element in an array
numbers = [10, 20, 30, 40, 50]
# Inserting 35 at index 2
numbers.insert(2, 35)
# Print the updated array
print(numbers)  

Output: [10, 20, 35, 30, 40, 50]

  • Deletion: Remove an element from the array at a specified index. This may involve shifting the remaining elements to fill the gap.

Syntax:

del array[index]

Example:

# Example of deleting an element from a list
numbers = [10, 20, 30, 40, 50]
# Deleting the fourth element (index 3)
del numbers[3]
# Print the updated list
print(numbers)  

Output: [10, 20, 30, 50]

  • Traversal: Visit each element of the array exactly once. This can be done using loops like ‘for’ or ‘while’.

Syntax:

for element in array:
    # Process element

Example:

# Example of iterating through an array
numbers = [10, 20, 30, 40, 50]
# Iterate through the array
for number in numbers:
    print(number)

Output:

10

20

30

40

50

  • Search: Determine whether a specific element exists in the array and, if so, find its index.

Syntax:

if element in array:
    index = array.index(element)

Example:

# Example of checking if an element exists in an array and getting its index
numbers = [10, 20, 30, 40, 50]
# Checking if 30 exists in the array
if 30 in numbers:
    index = numbers.index(30)
    print(f"Element 30 found at index {index}")
else:
    print("Element not found")

Output:

Element 30 found at index 2

  • Sorting: Arrange the elements of the array in a specific order (e.g., ascending or descending).

Syntax:

sorted_array = sorted(array)

Example: 

# Example of sorting an array
numbers = [40, 10, 30, 20, 50]
# Creating a sorted version of the array
sorted_numbers = sorted(numbers)
# Print the sorted array
print(sorted_numbers)  

Output: [10, 20, 30, 40, 50]

Want a comprehensive list of interview questions? Here are the Full Stack developer interview questions!

Examples of Array in Different Programming Language

Below are examples of working with arrays in different programming languages, along with explanations and their respective outputs:

  • C++

Code: 

#include <iostream>
using namespace std;
int main() {
    // Creating an array of integers
    int numbers[5] = {10, 20, 30, 40, 50};
    // Accessing elements
    cout << "Third element: " << numbers[2] << endl;
    // Updating elements
    numbers[1] = 25;
    // Iterating through the array
    for(int i = 0; i < 5; i++) {
        cout << numbers[i] << " ";
    }
    return 0;
}

Explanation:

  • This C++ program creates an array numbers with 5 elements: {10, 20, 30, 40, 50}.
  • It accesses and prints the third element, which is 30.
  • It then updates the second element, changing it from 20 to 25.
  • Finally, it iterates through the array and prints each element.

Output:

Third element: 30

10 25 30 40 50

  • Python

Code: 

# Creating a list (Python's equivalent of an array)
numbers = [10, 20, 70, 40, 50]
# Accessing elements
print("Third element:", numbers[2])
# Updating elements
numbers[1] = 25
# Iterating through the list
for number in numbers:
    print(number, end=" ")

Explanation:

  • This Python script creates a list of numbers with elements [10, 20, 70, 40, 50].
  • It accesses and prints the third element, which is 70.
  • It then updates the second element, changing it from 20 to 25.
  • Finally, it iterates through the list and prints each element.

Output:

Third element: 70

10 25 70 40 50 

  • Java

Code: 

public class Main {
    public static void main(String[] args) {
        // Creating an array of integers
        int[] numbers = {10, 20, 30, 40, 50};
        // Accessing elements
        System.out.println("Third element: " + numbers[2]);
        // Updating elements
        numbers[1] = 25;
        // Iterating through the array
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(numbers[i] + " ");
        }
    }
}

Explanation:

  • This Java program creates an array numbers with elements {10, 20, 30, 40, 50}.
  • It accesses and prints the third element, which is 30.
  • It then updates the second element, changing it from 20 to 25.
  • Finally, it iterates through the array and prints each element.

Output:

Third element: 30

10 25 30 40 50 

  • JavaScript

Code:

// Creating an array of numbers
let numbers = [10, 20, 70, 40, 50];
// Accessing elements
console.log("Third element:", numbers[2]);
// Updating elements
numbers[1] = 25;
// Iterating through the array
for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}

Explanation:

  • This JavaScript program (Node.js) creates an array numbers with elements [10, 20, 70, 40, 50].
  • It accesses and prints the third element, which is 70.
  • It then updates the second element, changing it from 20 to 25.
  • Finally, it iterates through the array and prints each element.

Output:

Third element: 70

10

25

70

40

50

  • Ruby

Code:

# Creating an array of numbers
numbers = [10, 20, 70, 40, 50]
# Accessing elements
puts "Third element: #{numbers[2]}"
# Updating elements
numbers[1] = 25
# Iterating through the array
numbers.each do |number|
    puts number
end

Explanation:

  • This Ruby script creates an array numbers with elements [10, 20, 70, 40, 50].
  • It accesses and prints the third element, which is 70.
  • It then updates the second element, changing it from 20 to 25.
  • Finally, it iterates through the array and prints each element.

Output:

Third element: 70

10

25

70

40

50

These examples demonstrate how to create, access, update, and iterate through arrays in different programming languages. The outputs shown are the results when these scripts are executed.

Advantages of Array

Arrays provide numerous benefits in programming, including:

  • Predictable Memory Allocation: Since the size of an array is determined when it is created, memory allocation is predictable. This can be important in scenarios where memory usage needs to be controlled.
  • Ease of Implementation: Arrays are fundamental data structures and are typically supported directly by programming languages. This makes them easy to implement and work with.
  • Multidimensional Arrays: Arrays can be extended to multiple dimensions (2D, 3D, etc.) to represent complex data structures like matrices, tables, or cubes.
  • Compact Code: Using arrays often results in more concise and readable code, especially in scenarios where you need to handle a collection of data.
  • Efficient for Specific Use Cases: In cases where you need to perform specific operations like matrix manipulation or numerical computations, arrays can be the most efficient data structure.

Learn what a Linear Data Structure is and how it works!

Disadvantages of Array

In the above section, we have seen the advantages of array. Now let us also come up with some of the disadvantages that are as follows:

  • Fixed Size: In many programming languages, the size of an array needs to be specified at the time of declaration. This can lead to inefficiencies if the size needs to change dynamically.
  • Contiguous Memory Allocation: Arrays require contiguous memory allocation. This can be a limitation when the available memory is fragmented, or when large blocks of contiguous memory are not available.
  • Inefficient Insertions and Deletions: Inserting or deleting elements in the middle of an array can be inefficient, as it requires shifting all the elements after the insertion or deletion point.
  • Wastage of Memory: If an array is declared with a larger size than necessary, it may result in unused or wasted memory.
  • Inflexible Size: In some languages, the size of an array cannot be changed after it is created. This means that if you need to store more elements than originally anticipated, you may need to create a new, larger array.

Applications of Array 

Arrays have a wide range of applications in computer programming. Here are some common use cases:

  • Storing and Retrieving Data: Arrays are used to store a collection of data items of the same type, such as numbers, characters, or objects.
  • Representing Matrices and Tables: 2D arrays are often used to represent grids, tables, or matrices in mathematics, graphics, and simulations.
  • Implementing Data Structures: Arrays in data structures are the foundation for other data structures like stacks, queues, and heaps. For example, a stack can be implemented using a one-dimensional array.
  • Handling Multiple Data Items: Arrays are used when you need to work with multiple related data items, such as storing test scores for a group of students.
  • Image Processing: In image processing, arrays are used to represent pixels. Each element in the array represents the color or intensity value of a pixel.

Conclusion

The significance of arrays is going to remain more reliable in the upcoming years. As technology progresses, we can anticipate enhancements in the efficiency and optimization of array implementations across programming languages. Moreover, the rise of specialized hardware architectures and parallel processing will further solidify the pivotal role of arrays in tasks involving data manipulation and numerical computations.

Still have queries? You can post your doubts on our Community page.

Course Schedule

Name Date Details
Python Course 11 May 2024(Sat-Sun) Weekend Batch
View Details
Python Course 18 May 2024(Sat-Sun) Weekend Batch
View Details
Python Course 25 May 2024(Sat-Sun) Weekend Batch
View Details

Full-Stack-ad.jpg