Inserting an element in an array requires two functions i.e. append () and insert(). These two functions help to insert the element at our desired position.
Adding or Appending at end of array
Adding or appending an element in an array is basically adding a new element at the end of the array.
For performing an append function in an array, we simply have to require the length of the array. If the length of the array is provided we can then use length as the index number of the last element and then append the array.
Pseudo code
Array[length]=x; length++;
Implementation
#include <iostream> using namespace std; struct Array { int A[20]; int size; int length; }; void Display(struct Array arr) { cout<<"Elements of the array are "; for(int i=0;i<arr.length;i++) { cout<<arr.A[i]<<" "; } } void Append(struct Array *arr, int x) { if(arr->size>arr->length) //comparing size and length { arr->A[arr->length++] = x; } } int main() { struct Array arr = {{10,20,30,50,60},10,5}; //array Elements, size, length Append(&arr,70); // array element, appending element Display(arr); }
The append operation has a constant time complexity.
Inserting an element at specific location
The appending of elements in the array is adding the element at the end of the array. But inserting an element at the specific position requires the shifting of the other elements.
The position at which the new element has to be inserted has to be cleared. The clearing of the position is done by shifting the other elements by one place ahead. This creates an empty cell at which we will insert the new element.
There is also a corner case in which it has to be checked if the index at which the element has to be inserted is not beyond the length of the array.
The length of the array at the end also has to be incremented.
With taking care of the above specifications we will create our program.
Pseudo code
Insert(index,x) { for(i=length; i>index; i++) { A[i] = A[i-1]; } A[index]=x; length++; }
Implementation
#include <iostream> using namespace std; struct Array { int A[20]; int size; int length; }; void Display(struct Array arr) { cout<<"Elements of the array are "; for(int i=0;i<arr.length;i++) { cout<<arr.A[i]<<" "; } } void Insert(struct Array *arr, int index, int x) { if(index>=0 && index<=arr->length) { for(int i=arr->length;i>index;i--) { arr->A[i]=arr->A[i--]; } arr->A[index] = x; arr->length++; } } int main() { struct Array arr = {{10,20,30,50,60},10,5}; Insert(&arr,5,90); Display(arr); }
Perform the above function on the CPP compiler.
Aayush Kumar Gupta is the founder and creator of ExploringBits, a website dedicated to providing useful content for people passionate about Engineering and Technology. Aayush has completed his Bachelor of Technology (Computer Science & Engineering) from 2018-2022. From July 2022, Aayush has been working as a full-time Devops Engineer.