Inserting an element into an array is a common operation in programming. This looks simple but has its own challenges due to the fixed size nature of arrays in many programming languages.
We are going to learn it best way possible with clear explanations and code examples in multiple programming languages.
🛠️ Ways to Insert an Element into an Array
Inserting an element into an array depends on the position where you want to insert it. Here are some common methods:
Insert at the Start
Insert at a Specific Position
Insert at the End
1️⃣ Insert an element at the Start of an Array
To insert an element at the start of an array, we need to shift all existing elements one position to the right to make space for the new element at index 0.
Steps to insert an element at the start of an array
Before we write code, we should first understand the steps involved in insertion.
Declare two global variables:
size → tracks the current number of elements
capacity → tracks the maximum size of the array
Create a function insertAtStart(array, element).
Inside insertAtStart:
Check if the array is full (size == capacity).
If full, print an error and return.
If not full, Run a loop from size - 1 to 0 to shift elements one position to the right using:
array[i] = array[i - 1]
Now index 0 is free.
Insert the new element at index 0.
Increment size by 1.
Inside the main function:
Create an array with a fixed capacity.
Call insertAtStart for each insertion.
Print the array after each insertion.
Why Size and Capacity declared as Global Variables?
Capacity: Capacity is fixed for the array and does not change during insertions. So we can declare it as a global variable.
Size: Size changes with each insertion. We need to maintain it externally or else we will need to traverse the entire array to calculate size every time we want to insert an element which will increase time complexity of insertion operation.
Size should be maintained externally
Its always better to maintain size of the array externally rather than calculating it inside the function.
Code Examples to Insert Element at Start of Array
Now lets see how to implement this in different programming languages.
Select your preferred programming language for
code examples:
Language
Program to insert element at start of array in C
InsertAtStart.c
#include<stdio.h>
#include<stdlib.h>
// Declare global variables for size and capacity
int size =0;
int capacity =4;
// function to insert element at start
int*insertAtStart(int*arr, intelement) {
// If array is full, return error that element cannot be inserted
if (size == capacity) {
printf("Array is full. Cannot insert element.\n");
return arr;
}
// Shift elements to the right
for (int i = size; i >0; i--) {
arr[i] = arr[i -1];
}
// Insert element at index 0
arr[0] = element;
size++;
return arr;
}
// main function
intmain() {
// Hardcoded values to insert (instead of taking user input)
int inputs[]= {10, 20, 30, 40, 50, 60};
int inputsCount =sizeof(inputs) /sizeof(inputs[0]);
// Initial array allocation
int*arr = (int*)malloc(capacity *sizeof(int));
// Insert elements
for (int i =0; i < inputsCount; i++) {
int element = inputs[i];
printf("Inserting %d at start\n", element);
arr =insertAtStart(arr, element);
printf("Current array: ");
for (int j =0; j < size; j++) {
printf("%d", arr[j]);
}
printf("\n");
}
free(arr);
// wait for user input before closing
printf("Press Enter to continue...");
getchar();
return0;
}
The output of the above code will be:
Inserting 10 at start
Current array: 10
Inserting 20 at start
Current array: 2010
Inserting 30 at start
Current array: 302010
Inserting 40 at start
Current array: 40302010
Inserting 50 at start
Array is full. Cannot insert element.
Current array: 40302010
Inserting 60 at start
Array is full. Cannot insert element.
Current array: 40302010
Program to insert element at start of array in C++
InsertAtStart.cpp
#include<iostream>
usingnamespace std;
// Declare global variables for size and capacity
int size =0;
int capacity =4;
// function to insert element at start
int*insertAtStart(int*arr, intelement) {
// If array is full, return error that element cannot be inserted
if (size == capacity) {
cout <<"Array is full. Cannot insert element."<< endl;
return arr;
}
// Shift elements to the right
for (int i = size; i >0; i--) {
arr[i] = arr[i -1];
}
// Insert element at index 0
arr[0] = element;
size++;
return arr;
}
// main function
intmain() {
// Hardcoded values to insert (instead of taking user input)
int inputs[] = {10, 20, 30, 40, 50, 60};
int inputsCount =sizeof(inputs) /sizeof(inputs[0]);
// Initial array allocation
int*arr =newint[capacity];
// Insert elements
for (int i =0; i < inputsCount; i++) {
int element = inputs[i];
cout <<"Inserting "<< element <<" at start"<< endl;
arr =insertAtStart(arr, element);
cout <<"Current array: ";
for (int j =0; j < size; j++) {
cout << arr[j] <<"";
}
cout << endl;
}
delete[] arr;
// wait for user input before closing
cout <<"Press Enter to continue...";
cin.get();
return0;
}
The output of the above code will be:
Inserting 10 at start
Current array: 10
Inserting 20 at start
Current array: 2010
Inserting 30 at start
Current array: 302010
Inserting 40 at start
Current array: 40302010
Inserting 50 at start
Array is full. Cannot insert element.
Current array: 40302010
Inserting 60 at start
Array is full. Cannot insert element.
Current array: 40302010
Program to insert element at start of array in Java
// If array is full, return error that element cannot be inserted
if (size == capacity) {
System.out.println("Array is full. Cannot insert element.");
return arr;
}
// Shift elements to the right
for (int i = size; i >0; i--) {
arr[i] = arr[i -1];
}
// Insert element at index 0
arr[0] = element;
size++;
return arr;
}
// main function
publicstaticvoidmain(String[] args) {
// Hardcoded values to insert (instead of taking user input)
int[] inputs = {10, 20, 30, 40, 50, 60};
// Initial array allocation
int[] arr =newint[capacity];
// Insert elements
for (int element : inputs) {
System.out.println("Inserting "+ element +" at start");
arr =insertAtStart(arr, element);
System.out.print("Current array: ");
for (int j =0; j < size; j++) {
System.out.print(arr[j] +"");
}
System.out.println();
}
}
}
The output of the above code will be:
Inserting 10 at start
Current array:10000
Inserting 20 at start
Current array:201000
Inserting 30 at start
Current array:3020100
Inserting 40 at start
Current array:40302010
Inserting 50 at start
Array is full. Cannot insert element.
Current array:40302010
Inserting 60 at start
Array is full. Cannot insert element.
Current array:40302010
As you can see from the output, by default Java initializes array elements to 0 because we are using int type array. So it shows 0 for uninitialized elements.
Program to insert element at start of array in Python
InsertAtStart.py
# Declare global variables for size and capacity
size =0
capacity =4
definsert_at_start(arr, element):
global size
global capacity
# If array is full, return error that element cannot be inserted
if size == capacity:
print("Array is full. Cannot insert element.")
return arr
# Shift elements to the right
arr.append(0) # Increase size of array
for i inrange(size, 0, -1):
arr[i] = arr[i -1]
# Insert element at index 0
arr[0] = element
size +=1
return arr
defmain():
# Hardcoded values to insert (instead of taking user input)
inputs = [10, 20, 30, 40, 50, 60]
arr = []
# Insert elements
for element in inputs:
print(f"Inserting {element} at start")
arr = insert_at_start(arr, element)
print("Current array:", arr)
if__name__=="__main__":
main()
The output of the above code will be:
Inserting 10 at start
Current array: [10]
Inserting 20 at start
Current array: [20, 10]
Inserting 30 at start
Current array: [30, 20, 10]
Inserting 40 at start
Current array: [40, 30, 20, 10]
Inserting 50 at start
Array is full. Cannot insert element.
Current array: [40, 30, 20, 10]
Inserting 60 at start
Array is full. Cannot insert element.
Current array: [40, 30, 20, 10]
Program to insert element at start of array in JavaScript
InsertAtStart.js
// Declare global variables for size and capacity
let size =0;
let capacity =4;
functioninsertAtStart(arr, element) {
// If array is full, return error that element cannot be inserted
if (size === capacity) {
console.log("Array is full. Cannot insert element.");
return arr;
}
// Shift elements to the right
arr.push(0); // Increase size of array
for (let i = size; i >0; i--) {
arr[i] = arr[i -1];
}
// Insert element at index 0
arr[0] = element;
size++;
return arr;
}
functionmain() {
// Hardcoded values to insert (instead of taking user input)
const inputs = [10, 20, 30, 40, 50, 60];
let arr = [];
// Insert elements
for (const element of inputs) {
console.log(`Inserting ${element} at start`);
arr =insertAtStart(arr, element);
console.log("Current array:", arr);
}
}
main();
The output of the above code will be:
Inserting 10 at start
Current array: [ 10 ]
Inserting 20 at start
Current array: [ 20, 10 ]
Inserting 30 at start
Current array: [ 30, 20, 10 ]
Inserting 40 at start
Current array: [ 40, 30, 20, 10 ]
Inserting 50 at start
Array is full. Cannot insert element.
Current array: [ 40, 30, 20, 10 ]
Inserting 60 at start
Array is full. Cannot insert element.
Current array: [ 40, 30, 20, 10 ]
Complexity Analysis for Insertion at Start of Array
Time Complexity:
O(n) - In the worst case, we need to shift all existing elements one position to the right, which takes linear time.
Space Complexity:
O(1) - We are not using any extra space that grows with input size; we are only using a fixed amount of space for variables.
2️⃣ Insert at a Specific Position
To insert an element at a specific position in an array, we need to shift all existing elements from that position onwards one position to the right to make space for the new element.
Steps to insert an element at a specific position
As usual we should first understand the steps involved in insertion.
Declare two global variables:
size → tracks the current number of elements
capacity → tracks the maximum size of the array
Create a function insertAtPosition(array, element, position).
Inside insertAtPosition:
Check if the array is full (size == capacity).
If full, print an error and return.
Check if the position is valid (0 <= position <= size).
If invalid, print an error and return.
Run a loop from size - 1 to position to shift elements one position to the right using:
array[i] = array[i - 1]
Now index position is free.
Insert the new element at index position.
Increment size by 1.
Inside the main function:
Create an array with a fixed capacity.
Call insertAtPosition for each insertion.
Print the array after each insertion.
Why Size and Capacity declared as Global Variables?
Capacity: Capacity is fixed for the array and does not change during insertions. So we can declare it as a global variable.
Size: Size changes with each insertion. We need to maintain it externally or else we will need to traverse the entire array to calculate size every time we want to insert an element which will increase time complexity of insertion operation.
Size should be maintained externally
Its always better to maintain size of the array externally rather than calculating it inside the function.
Code Examples to Insert Element at Specific Position in Array
Now lets see how to implement this in different programming languages.
Select your preferred programming language for
code examples:
Language
Program to insert element at specific position of array in C
InsertAtPosition.c
#include<stdio.h>
#include<stdlib.h>
// Declare global variables for size and capacity
int size =0;
int capacity =5;
// function to insert element at specific position
System.out.println("Inserting "+ element +" at position "+ position);
arr =insertAtPosition(arr, element, position);
System.out.print("Current array: ");
for (int j =0; j < size; j++) {
System.out.print(arr[j] +"");
}
System.out.println();
}
}
}
The output of the above code will be:
Inserting 10 at position 0
Current array:100000
Inserting 20 at position 1
Current array:1020000
Inserting 30 at position 1
Current array:10302000
Inserting 40 at position 0
Current array:401030200
Inserting 50 at position 2
Current array:4010503020
Inserting 60 at position 3
Array is full. Cannot insert element.
Current array:4010503020
As you can see from the output, by default Java initializes array elements to 0 because we are using int type array. So it shows 0 for uninitialized elements.
Program to insert element at specific position of array in Python
InsertAtPosition.py
# Declare global variables for size and capacity
size =0
capacity =5
definsert_at_position(arr, element, position):
global size
global capacity
# If array is full, return error that element cannot be inserted
if size == capacity:
print("Array is full. Cannot insert element.")
return arr
# Check for valid position
if position <0or position > size:
print("Invalid position. Cannot insert element.")
return arr
# Shift elements to the right
arr.append(0) # Increase size of array
for i inrange(size, position, -1):
arr[i] = arr[i -1]
# Insert element at specified position
arr[position] = element
size +=1
return arr
defmain():
# Hardcoded values to insert (instead of taking user input)
console.log(`Inserting ${element} at position ${position}`);
arr =insertAtPosition(arr, element, position);
console.log("Current array:", arr);
}
}
main();
The output of the above code will be:
Inserting 10 at position 0
Current array: [ 10 ]
Inserting 20 at position 1
Current array: [ 10, 20 ]
Inserting 30 at position 1
Current array: [ 10, 30, 20 ]
Inserting 40 at position 0
Current array: [ 40, 10, 30, 20 ]
Inserting 50 at position 2
Current array: [ 40, 10, 50, 30, 20 ]
Inserting 60 at position 3
Array is full. Cannot insert element.
Current array: [ 40, 10, 50, 30, 20 ]
Complexity Analysis for Insertion at Specific Position of Array
Time Complexity:
O(n) - In the worst case, we may need to shift all existing elements one position to the right, which takes linear time.
Space Complexity:
O(1) - We are not using any extra space that grows with input size; we are only using a fixed amount of space for variables.
3️⃣ Insert an element at the End of an Array
To insert an element at the end of an array, we simply place the new element at the index equal to the current size of the array.
Steps to insert an element at the end of an array
As usual we should first understand the steps involved in insertion.
Declare two global variables:
size → tracks the current number of elements
capacity → tracks the maximum size of the array
Create a function insertAtEnd(array, element).
Inside insertAtEnd:
Check if the array is full (size == capacity).
If full, print an error and return.
Insert the new element at index size.
Increment size by 1.
Inside the main function:
Create an array with a fixed capacity.
Call insertAtEnd for each insertion.
Print the array after each insertion.
Why Size and Capacity declared as Global Variables?
Capacity: Capacity is fixed for the array and does not change during insertions. So we can declare it as a global variable.
Size: Size changes with each insertion. We need to maintain it externally or else we will need to traverse the entire array to calculate size every time we want to insert an element which will increase time complexity of insertion operation.
Size should be maintained externally
Its always better to maintain size of the array externally rather than calculating it inside the function.
Code Examples to Insert Element at End of Array
Now lets see how to implement this in different programming languages.
Select your preferred programming language for
code examples:
Language
Program to insert element at end of array in C
InsertAtEnd.c
#include<stdio.h>
#include<stdlib.h>
// Declare global variables for size and capacity
int size =0;
int capacity =4;
// function to insert element at end
int*insertAtEnd(int*arr, intelement) {
// If array is full, return error that element cannot be inserted
if (size == capacity) {
printf("Array is full. Cannot insert element.\n");
return arr;
}
// Insert element at index size
arr[size] = element;
size++;
return arr;
}
// main function
intmain() {
// Hardcoded values to insert (instead of taking user input)
int inputs[]= {10, 20, 30, 40, 50, 60};
int inputsCount =sizeof(inputs) /sizeof(inputs[0]);
// Initial array allocation
int*arr = (int*)malloc(capacity *sizeof(int));
// Insert elements
for (int i =0; i < inputsCount; i++) {
int element = inputs[i];
printf("Inserting %d at end\n", element);
arr =insertAtEnd(arr, element);
printf("Current array: ");
for (int j =0; j < size; j++) {
printf("%d", arr[j]);
}
printf("\n");
}
free(arr);
// wait for user input before closing
printf("Press Enter to continue...");
getchar();
return0;
}
The output of the above code will be:
Inserting 10 at end
Current array: 10
Inserting 20 at end
Current array: 1020
Inserting 30 at end
Current array: 102030
Inserting 40 at end
Current array: 10203040
Inserting 50 at end
Array is full. Cannot insert element.
Current array: 10203040
Inserting 60 at end
Array is full. Cannot insert element.
Current array: 10203040
Program to insert element at end of array in C++
InsertAtEnd.cpp
#include<iostream>
usingnamespace std;
// Declare global variables for size and capacity
int size =0;
int capacity =4;
// function to insert element at end
int*insertAtEnd(int*arr, intelement) {
// If array is full, return error that element cannot be inserted
if (size == capacity) {
cout <<"Array is full. Cannot insert element."<< endl;
return arr;
}
// Insert element at index size
arr[size] = element;
size++;
return arr;
}
// main function
intmain() {
// Hardcoded values to insert (instead of taking user input)
int inputs[] = {10, 20, 30, 40, 50, 60};
int inputsCount =sizeof(inputs) /sizeof(inputs[0]);
// If array is full, return error that element cannot be inserted
if (size == capacity) {
System.out.println("Array is full. Cannot insert element.");
return arr;
}
// Insert element at index size
arr[size] = element;
size++;
return arr;
}
// main function
publicstaticvoidmain(String[] args) {
// Hardcoded values to insert (instead of taking user input)
int[] inputs = {10, 20, 30, 40, 50, 60};
// Initial array allocation
int[] arr =newint[capacity];
// Insert elements
for (int element : inputs) {
System.out.println("Inserting "+ element +" at end");
arr =insertAtEnd(arr, element);
System.out.print("Current array: ");
for (int j =0; j < size; j++) {
System.out.print(arr[j] +"");
}
System.out.println();
}
}
}
The output of the above code will be:
Inserting 10 at end
Current array:10000
Inserting 20 at end
Current array:102000
Inserting 30 at end
Current array:1020300
Inserting 40 at end
Current array:10203040
Inserting 50 at end
Array is full. Cannot insert element.
Current array:10203040
Inserting 60 at end
Array is full. Cannot insert element.
Current array:10203040
As you can see from the output, by default Java initializes array elements to 0 because we are using int type array. So it shows 0 for uninitialized elements.
Program to insert element at end of array in Python
InsertAtEnd.py
# Declare global variables for size and capacity
size =0
capacity =4
definsert_at_end(arr, element):
global size
global capacity
# If array is full, return error that element cannot be inserted
if size == capacity:
print("Array is full. Cannot insert element.")
return arr
# Insert element at index size
arr.append(element)
size +=1
return arr
defmain():
# Hardcoded values to insert (instead of taking user input)
inputs = [10, 20, 30, 40, 50, 60]
arr = []
# Insert elements
for element in inputs:
print(f"Inserting {element} at end")
arr = insert_at_end(arr, element)
print("Current array:", arr)
if__name__=="__main__":
main()
The output of the above code will be:
Inserting 10 at end
Current array: [10]
Inserting 20 at end
Current array: [10, 20]
Inserting 30 at end
Current array: [10, 20, 30]
Inserting 40 at end
Current array: [10, 20, 30, 40]
Inserting 50 at end
Array is full. Cannot insert element.
Current array: [10, 20, 30, 40]
Inserting 60 at end
Array is full. Cannot insert element.
Current array: [10, 20, 30, 40]
Program to insert element at end of array in JavaScript
InsertAtEnd.js
// Declare global variables for size and capacity
let size =0;
let capacity =4;
functioninsertAtEnd(arr, element) {
// If array is full, return error that element cannot be inserted
if (size === capacity) {
console.log("Array is full. Cannot insert element.");
return arr;
}
// Insert element at index size
arr[size] = element;
size++;
return arr;
}
functionmain() {
// Hardcoded values to insert (instead of taking user input)
const inputs = [10, 20, 30, 40, 50, 60];
let arr = [];
// Insert elements
for (const element of inputs) {
console.log(`Inserting ${element} at end`);
arr =insertAtEnd(arr, element);
console.log("Current array:", arr);
}
}
main();
The output of the above code will be:
Inserting 10 at end
Current array: [ 10 ]
Inserting 20 at end
Current array: [ 10, 20 ]
Inserting 30 at end
Current array: [ 10, 20, 30 ]
Inserting 40 at end
Current array: [ 10, 20, 30, 40 ]
Inserting 50 at end
Array is full. Cannot insert element.
Current array: [ 10, 20, 30, 40 ]
Inserting 60 at end
Array is full. Cannot insert element.
Current array: [ 10, 20, 30, 40 ]
Complexity Analysis for Insertion at End of Array
Time Complexity:
O(1) - Inserting an element at the end of the array takes constant time as no shifting of elements is required.
Space Complexity:
O(1) - We are not using any extra space that grows with input size; we are only using a fixed amount of space for variables.
Time and Space Complexity Table for Insertion in Array
Insertion Type
Time Complexity
Space Complexity
Insert at Start
O(n)
O(1)
Insert at Specific Position
O(n)
O(1)
Insert at End
O(1)
O(1)
Summary
In this tutorial, we have explored:
Inserting an element at the start of an array
Inserting an element at a specific position in an array
Inserting an element at the end of an array
The time and space complexity for each insertion method
Code examples in C, C++, Java, Python, and JavaScript for each insertion method
Why size and capacity are maintained as global variables