Tutorials

Arrays


Array Insert


In previous chapter we saw the ways to declare, instantiate and initialize array.

We will insert element in the array now.

 

The above array has maximum capacity of 10 elements.

We can see the elements will be inserted at a particular index. And all the operations that we perform on this array would be with respect to index.

 

In java

 

int myArray[] = {3, 34, 27, 68, 9, 34, 45, 89, 99, 56};

 

Writing above statement in java will create an array that will contain specified 10 elements. 

Elements will be stored exactly as shown in the bove diagram.

 

In C

int myArray[10]={3, 34, 27, 68, 9, 34, 45, 89, 99, 56};

 

Writing above statement in C will create an array that will contain specified 10 elements. 

Elements will be stored exactly as shown in the bove diagram.

 

Inserting at index

Insertion of new element can be done at :

  1. end of the array
  2. at any specified index

Insertion of new element is only possible if the space allocated to the array is enough to store the new element.

Suppose we have an array arr[8]={11,12,14,15,16}

 

Insert element in Array by tutorialsinhand.com

 

In the above array we want to insert element 13 at index 2.

  • Element at index 2 needs to be shifted to index 3, element at index 3 to index 4 and so on.
  • Make sure there is enough space to adjust the element while shifting. 
  • In above diagram, we have three empty space so element can be added easily.


Please Share this page
Views : 22