What is Array?
What is an Array?
An array is a collection of items of same data type stored at contiguous memory locations.
This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index 0 and the difference between the two indexes is the offset.
For simplicity, we can think of an array as a flight of stairs where on each step is placed a value (let’s say one of your friends). Here, you can identify the location of any of your friends by simply knowing the count of the step they are on.
Remember: “Location of next index depends on the data type we use”.
n
Is the array always of a fixed size?
In C language, the array has a fixed size meaning once the size is given to it, it cannot be changed i.e. you can’t shrink it nor can you expand it. The reason was that for expanding if we change the size we can’t be sure ( it’s not possible every time) that we get the next memory location to us for free. The shrinking will not work because the array, when declared, gets memory statically allocated, and thus compiler is the only one that can destroy it.
Types of indexing in an array:
- 0 (zero-based indexing): The first element of the array is indexed by a subscript of 0.
- 1 (one-based indexing): The first element of the array is indexed by the subscript of 1.
- n (N-based indexing): The base index of an array can be freely chosen. Usually, programming languages allowing n-based indexing also allow negative index values, and other scalar data types like enumerations, or characters may be used as an array index.
How an Array is initialized?
By default the array is uninitialized, and no elements of the array are set to any value. However, for the proper working of the array, array initialization becomes important. Array initialization can be done by the following methods:
1. Passing no value within the initializer: One can initialize the array by defining the size of the array and passing no values within the initializer.
Syntax:
int arr[ 5 ] = { };
2. By passing specific values within the initializer: One can initialize the array by defining the size of the array and passing specific values within the initializer.
Syntax:
int arr[ 5 ] = { 1, 2, 3, 4, 5 };
Note: The count of elements within the “{ }”, must be less than or equals to the size of the array
If the count of elements within the “{ }” is less than the size of the array, the remaining positions are considered to be ‘0’.
Syntax:
int arr[ 5 ] = { 1, 2, 3 } ;
3. By passing specific values within the initializer but not declaring the size: One can initialize the array by passing specific values within the initializer and not particularly mentioning the size, the size is interpreted by the compiler.
Syntax:
int arr[ ] = { 1, 2, 3, 4, 5 };
4. Universal Initialization: After the adoption of universal initialization in C++, one can avoid using the equals sign between the declaration and the initializer.
Syntax:
int arr[ ] { 1, 2, 3, 4, 5 };
To know more about array initialization, click here.
What are the different operations on the array?
Arrays allow random access to elements. This makes accessing elements by position faster. Hence operation like searching, insertion, and access becomes really efficient. Array elements can be accessed using the loops.
1. Insertion in Array:
We try to insert a value to a particular array index position, as the array provides random access it can be done easily using the assignment operator.
Pseudo Code:
// to insert a value= 10 at index position 2;
arr[ 2 ] = 10;
Time Complexity:
- O(1) to insert a single element
- O(N) to insert all the array elements [where N is the size of the array]
Here is the code for working in an array:
C++
#include <iostream> using namespace std; int main() { // initialize an integer array with three elements, all // of which are initially set to 0 int arr[3] = { 0, 0, 0 }; // set the first element to 1 arr[0] = 1; // set the second element to 2 arr[1] = 2; // set the third element to 3 arr[2] = 3; // print the contents of the array to the console using // a for loop for ( int i = 0; i < 3; i++) { cout << arr[i] << " " ; } return 0; } |
Python3
arr = [ 0 , 0 , 0 ] arr[ 0 ] = 1 arr[ 1 ] = 2 arr[ 2 ] = 3 print (arr) |
Java
import java.util.Arrays; // Import the Arrays class from the java.util package public class GFG { // Declare a public class named GFG public static void main(String[] args) { // Declare a public static method named main that // accepts a String array as a parameter int [] arr = new int [ 3 ]; // Declare an integer array named // arr with three elements arr[ 0 ] = 1 ; // Assign the value 1 to the first // element of the array arr[ 1 ] = 2 ; // Assign the value 2 to the second // element of the array arr[ 2 ] = 3 ; // Assign the value 3 to the third // element of the array System.out.println(Arrays.toString( arr)); // Print the contents of the array to the // console using the Arrays.toString() // method } } // Code Contributed by Satyam Nayak |
C#
using System; // Import the System namespace which includes // the Console class class GFG { // Declare a class named GFG static void Main( string [] args) { // Declare a static method named Main that accepts a // string array as a parameter int [] arr = new int [3]; // Declare an integer array named // arr with three elements arr[0] = 1; // Assign the value 1 to the first // element of the array arr[1] = 2; // Assign the value 2 to the second // element of the array arr[2] = 3; // Assign the value 3 to the third // element of the array Console.WriteLine( string .Join( ", " , arr)); // Print the contents of the array to the // console as a comma-separated string // using the string.Join() method } } // code contributed by Satyam Nayak |
Javascript
const arr = new Array(3); // Declare an array named arr with three elements arr[0] = 1; // Assign the value 1 to the first element of the array arr[1] = 2; // Assign the value 2 to the second element of the array arr[2] = 3; // Assign the value 3 to the third element of the array console.log(arr.toString()); // Print the contents of the array to the console as a string using the toString() method |
1 2 3
2. Access elements in Array:
Accessing array elements become extremely important, in order to perform operations on arrays.
Pseudo Code:
// to access array element at index position 2, we simply can write
return arr[ 2 ] ;
Time Complexity: O(1)
Here is the code for working in an array:
C++
#include <iostream> using namespace std; int main() { int arr[] = { 1, 2, 3, 4 }; // accessing element at index 2 cout << arr[2] << endl; return 0; } |
Java
public class GFG { public static void main(String[] args) { int [] arr = { 1 , 2 , 3 , 4 }; // accessing element at index 2 System.out.println(arr[ 2 ]); } } // This code is contributed by ishankhandelwals. |
Python3
arr = [ 1 , 2 , 3 , 4 ] # accessing element at index 2 print (arr[ 2 ]) # This code is contributed by ishankhandelwals. |
C#
using System; class GFG { static void Main( string [] args) { int [] arr = { 1, 2, 3, 4 }; // accessing element at index 2 Console.WriteLine(arr[2]); } } // This code is contributed by ishankhandelwals. |
Javascript
let arr = [1, 2, 3, 4]; // accessing element at index 2 console.log(arr[2]); // This code is contributed by ishankhandelwals. |
3
3. Searching in Array:
We try to find a particular value in the array, in order to do that we need to access all the array elements and look for the particular value.
Pseudo Code:
// searching for value 2 in the array;
Loop from i = 0 to 5:
check if arr[i] = 2:
return true;
Time Complexity: O(N), where N is the size of the array.
Here is the code for working with an array:
C
#include <stdio.h> int main() { int arr[4]; arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; for ( int i = 0; i < 4; i++) printf ( "%d\n" , arr[i]); return 0; } |
C++
#include <iostream> using namespace std; int main() { int arr[10]; arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; for ( int i = 0; i < 4; i++) cout << arr[i] << endl; return 0; } |
Java
public class GFG { public static void main(String args[]) { int [] arr = new int [ 4 ]; arr[ 0 ] = 1 ; arr[ 1 ] = 2 ; arr[ 2 ] = 3 ; arr[ 3 ] = 4 ; for ( int i = 0 ; i < arr.length; i++) { System.out.println(arr[i]); } } } |
C#
// Include namespace system using System; public class GFG { public static void Main(String[] args) { // Creating an integer array // named arr of size 10. int [] arr = new int [10]; // accessing element at 0 index // and setting its value to 5. arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; // access and print value at 0 // index we get the output as 5. for ( int i = 0; i < 4; i++) Console.WriteLine(arr[i]); } } |
Python3
# code import array gfg = array.array( 'i' , [ 1 , 2 , 3 , 4 ]) for gfg2 in gfg: print (gfg2) |
Javascript
let arr = []; arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } // This code is contributed by agfro1cac. |
1 2 3 4
Here the value 5 is printed because the first element has index zero and at the zeroth index, we already assigned the value 5.
Types of arrays :
- One-dimensional array (1-D arrays)
- Multidimensional array
C++
// cpp program to display all elements of an initialised 2D // array. #include <iostream> using namespace std; int main() { int i, j; int matrix[3][2] = { { 4, 5 }, { 34, 67 }, { 8, 9 } }; // use of nested for loop // access rows of the array. for (i = 0; i < 3; i++) { // access columns of the array. for (j = 0; j < 2; j++) { cout << "matrix[" << i << "][" << j << "]=" << matrix[i][j] << endl; } } return 0; } |
Java
// Declare a public class named Main public class Main { // Declare the main method that accepts a String array // as a parameter public static void main(String[] args) { // Declare and initialize a 2D integer array named // matrix int [][] matrix = { { 4 , 5 }, { 34 , 67 }, { 8 , 9 } }; // Use nested for loops to access rows and columns // of the array. // The outer loop iterates through each row of the // array for ( int i = 0 ; i < 3 ; i++) { // The inner loop iterates through each column // of the array for ( int j = 0 ; j < 2 ; j++) { // Print the value of the current element to // the console System.out.println( "matrix[" + i + "][" + j + "]=" + matrix[i][j]); } } } } |
Python3
# Define a class named Main class Main: # Define a main method that accepts a string array as a parameter @staticmethod def main(): # Define a 2D integer array named matrix matrix = [[ 4 , 5 ], [ 34 , 67 ], [ 8 , 9 ]] # Use nested for loops to access rows and columns of the array # The outer loop iterates through each row of the array for i in range ( 3 ): # The inner loop iterates through each column of the array for j in range ( 2 ): # Print the value of the current element to the console print ( "matrix[{}][{}]={}" . format (i, j, matrix[i][j])) # Call the main method of the Main class Main.main() |
C#
using System; class Program { static void Main( string [] args) { int [, ] matrix = { { 4, 5 }, { 34, 67 }, { 8, 9 } }; // use of nested for loop // access rows of the array. for ( int i = 0; i < 3; i++) { for ( int j = 0; j < 2; j++) { Console.WriteLine( "matrix[{0}][{1}]={2}" , i, j, matrix[i, j]); } } } } // this code is contributed by snehalsalokhe |
Javascript
// JavaScript program to display all elements of an initialised 2D array. // define the matrix let matrix = [[4, 5], [34, 67], [8, 9]]; // use nested for loop to access rows and columns of the array for (let i = 0; i < 3; i++) { for (let j = 0; j < 2; j++) { console.log(`matrix[${i}][${j}] = ${matrix[i][j]}`); } } // this code is contributed by Chetan Bargal |
matrix[0][0]=4 matrix[0][1]=5 matrix[1][0]=34 matrix[1][1]=67 matrix[2][0]=8 matrix[2][1]=9
To learn about the differences between One-dimensional and Multidimensional arrays, click here.
Space complexity: The space complexity of this code is O(1) because we are not creating any new variables or data structures that depend on the input size. We are simply using a constant amount of memory to store the 2D array and the loop variables.
Time complexity: The time complexity of the nested for loop used in this code is O(n^2), where n is the number of rows in the 2D array. This is because we are iterating over all the elements of the array, which requires n x m iterations (where m is the number of columns in the array), resulting in a time complexity of O(n^2).
Advantages of using arrays:
- Arrays allow random access to elements. This makes accessing elements by position faster.
- Arrays have better cache locality which makes a pretty big difference in performance.
- Arrays represent multiple data items of the same type using a single name.
Disadvantages of using arrays:
You can’t change the size i.e. once you have declared the array you can’t change its size because of static memory allocation. Here Insertion(s) and deletion(s) are difficult as the elements are stored in consecutive memory locations and the shifting operation is costly too.
Now if take an example of the implementation of data structure Stack using array there are some obvious flaws.
Let’s take the POP operation of the stack. The algorithm would go something like this.
- Check for the stack underflow
- Decrement the top by 1
What we are doing here is, that the pointer to the topmost element is decremented, which means we are just bounding our view, and actually that element stays there taking up the memory space. If you have an array (as a Stack) of any primitive data type then it might be ok. But in the case of an array of Objects, it would take a lot of memory.
Examples –
// A character array in C/C++/Java
char arr1[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’};// An Integer array in C/C++/Java
int arr2[] = {10, 20, 30, 40, 50};// Item at i’th index in array is typically accessed as “arr[i]”.
For example:
arr1[0] gives us ‘g’
arr2[3] gives us 40
Usually, an array of characters is called a ‘string’, whereas an array of ints or floats is simply called an array.
Applications on Array
- Array stores data elements of the same data type.
- Arrays are used when the size of the data set is known.
- Used in solving matrix problems.
- Applied as a lookup table in computer.
- Databases records are also implemented by the array.
- Helps in implementing sorting algorithm.
- The different variables of the same type can be saved under one name.
- Arrays can be used for CPU scheduling.
- Used to Implement other data structures like Stacks, Queues, Heaps, Hash tables, etc.
To learn more about the advantage, disadvantages, and applications of arrays, click here.
Frequently asked questions (FAQs) about Array Data Structures
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. What are the 3 types of arrays?
- Indexed arrays
- Multidimensional arrays
- Associative arrays
3. What data structure is an array?
An array is a linear data structure.
4. Difference between array and structure?
The structure can contain variables of different types but an array only contain variables of the same type.
Please Login to comment...