C Program to insert an element in an array


In this program, You will learn how to insert an element in an array in c.


List is: 1 2 3 4 5 6

Insert item: 44

Insert location: 7

New list is: 1 2 3 4 5 6 44


Example: How to insert an element in an array in c

Run it Now
#include<stdio.h>

int main() {

   int arr[10], n, i, num, loc;

   printf("Enter Size of an Array :");
   scanf("%d", &n);

   printf("\nEnter Array Elements :");
   for (i = 0; i < n; i++) {
       scanf("%d", &arr[i]);
   }

   printf("\nEnter Element for Insert :");
   scanf("%d", &num);
   printf("\nEnter location :");
   scanf("%d", &loc);

   for (i = n; i >= loc; i--) {
       arr[i] = arr[i - 1];
   }
   n++;
   arr[loc - 1] = num;

   printf("\nAfter Insert Array List is :");
   for (i = 0; i < n; i++) {
       printf("%d ", arr[i]);
   }

   return 0;
}

Output:

Enter Size of an Array :5
Enter Array Elements :10 20 30 40 50
Enter Element for Insert :15
Enter location :2
After Insert Array List is :10 15 20 30 40 50