C Program to Insert an Element in an Array
Last Updated :
12 Jul, 2025
In this article, we will learn how to insert an element into an array in C.
C arrays have a fixed size, so we cannot dynamically increase their memory. However, we can insert an element if the array already have enough memory space to accommodate the new elements
Insert Element at Specific Position
To insert an element at a specific position, shift all elements to the right of the specified position one step to the right. This will create an empty space at the specified position. Then, insert the new element at the desired position.
C
#include <stdio.h>
void insert(int arr[], int *n, int pos, int val) {
// Shift elements to the right
for (int i = *n; i > pos; i--)
arr[i] = arr[i - 1];
// Insert val at the specified position
arr[pos] = val;
// Increase the current size
(*n)++;
}
int main() {
int arr[7] = {10, 20, 30, 40, 50};
int n = 5;
int pos = 3;
int val = 25;
// Insert the value at the specified position
insert(arr, &n, pos, val);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Explanation: In the given program, the function insert() shifts all elements starting from the insertion index 3 one step to the right. The new value 25 is then inserted at the desired position, and the size of the array is incremented.
Time Complexity: O(n) (for Shifting) + O(1) (for incrementing size) = O(n)
Auxiliary Space: O(1)
If you want to explore array manipulation and other data structures, the C Programming Course Online with Data Structures provides hands-on examples and exercises.
Insert an Element at the End of an Array
If you are inserting an element at the end, there's no need for shifting elements. You can directly add the element at the next available position and increase the size.
C
#include <stdio.h>
void insertLast(int arr[], int *n, int val) {
// Insert val at last
arr[*n] = val;
// Increase the current size
(*n)++;
}
int main() {
int arr[7] = {10, 20, 30, 40, 50};
int n = 5;
int val = 25;
// Insert the value at the end
insertLast(arr, &n, val);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Time Complexity: O(1) (for decrementing size)
Auxiliary Space: O(1)
Note: Apart from insertion at the end, all cases will be handled same as insertion at specific position. Also, make sure array have enough space to avoid segmentation faults.
Similar Reads
Interview Preparation
Practice @Geeksforgeeks
Data Structures
Algorithms
Programming Languages
Web Technologies
Computer Science Subjects
Data Science & ML
Tutorial Library
GATE CS