If you’re new to C programming and arrays, one of the most common beginner tasks is inserting an element into an array. It might sound simple but it’s a great way to learn about memory handling, shifting elements, and working with loops.
Let’s break this down in a chill and beginner-friendly way and then write a working C program to insert an element in an array.
Table of Contents
What Does “Insert an Element in an Array” Mean?
So imagine you have an array like this:
arr = [10, 20, 30, 40]
Now you want to add the number 25 at position 2 (indexing starts from 0), so it becomes:
arr = [10, 20, 25, 30, 40]
For that to happen, we have to shift the elements from the position we want to insert—rightward—to make space.
Step-by-Step Plan
- Ask the user how many elements they want in the array.
- Store the elements.
- Ask where they want to insert the new number and what number it is.
- Shift elements to the right from that position.
- Insert the number.
- Print the new array.
Sounds good? Let’s code it out.
C Program to Insert an Element in an Array
#include <stdio.h>
int main() {
int arr[100], n, i, pos, value;
printf("Enter number of elements in the array: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the position where you want to insert (0 to %d): ", n);
scanf("%d", &pos);
if(pos < 0 || pos > n) {
printf("Invalid position!\n");
return 1;
}
printf("Enter the value to insert: ");
scanf("%d", &value);
for(i = n; i > pos; i--) {
arr[i] = arr[i - 1]; // shifting elements to the right
}
arr[pos] = value;
n++; // updating size of array
printf("Array after insertion:\n");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Sample Output
Enter number of elements in the array: 4
Enter 4 elements:
10 20 30 40
Enter the position where you want to insert (0 to 4): 2
Enter the value to insert: 25
Array after insertion:
10 20 25 30 40
What to Keep in Mind
- The array size should not be exceeded (in this example, it’s fixed at 100).
- Validating the position is important.
- C doesn’t resize arrays automatically, so we have to handle that ourselves.
Final Thoughts
Inserting an element in an array helps you get comfortable with loops and memory movement in C. Once you get this down, you’re one step closer to tackling linked lists, dynamic arrays, and other advanced data structures.
Let me know if you want to do deletion next!







