Arrays

Hello, For a long time, I was thinking to write something on a topic related to DSA. So In this article, we will learn about arrays and also solve some questions based on arrays.

What is an Array?

An array is a data structure used to store multiple values together. For example, suppose we have 10 elements. We can create 10 different variables and assign a variable to 10 different elements. But what if this number grows to 20 or 1000? Then It will become very difficult to create 1000 different variables and assign elements to each variable. There comes Array. The array can store these elements in a contiguous location.

const arr = [ 10, 20, 30, 40, 50, 60]

In an array, elements are stored in a contiguous location. What does that mean?

Here contagious means If the First element is stored at position x then the next element will be stored at x + y and similarly x+2y and so on...

Advantages of using an array.

  • Random Access

Since elements are stored at contiguous locations you can it with items in Just Big O n times.

In the above array if want to get the 2nd element from the array all we need to write this.

const arr = [ 10, 20, 30, 40, 50, 60]
arr[1]

Since array stats from 0 index to access the element at 2nd position in an array, we need to write arr[1].

  • Cache Friendly (Will discuss this in some other article.)

Types of Array

  • Fixed-size array

  • Dynamic size array

Fixed size arrays are a type of array in which you can't store more than the allocated size of the array. For example in Java

int []arr = new int[100];
int []arr = new int[n];
int arr[] = {10,20,30};

Here these are the ways how you can create a fixed size array in java.

Dynamic arrays are the one which can increase its size if we add more item to it. Here is an example how you can create a dynamic size array in Java.

import java.util.ArrayList;
public class Arrays {
    public static void main(String args[]) {
        ArrayList<Integer>al = new ArrayList<Integer>();
        al.add(10);
        al.add(20);
        al.add(30);
        System.out.println(al);
    }
}

Did you find this article valuable?

Support aditya kumar by becoming a sponsor. Any amount is appreciated!