C

How To Insert An Element At a Specific Position in Array

In this tutorial, we are going to see how to insert an element at a specific position in an array in C programming. Note: This does not mean that we want to increase the size of the array.

For example, let’s consider the following array arr[10] with four elements:

arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40

And suppose you want to insert the value 5 at the first position of the array. i.e. arr[0] = 5, so we need to move the elements by one cell so that after the insertion:

arr[0] = 5
arr[1] = 10
arr[2] = 20
arr[3] = 30
arr[4] = 40

 

 

How To Insert An Element At a Specific Position in Array
#include <stdio.h>

int main()
{
   int position, i, nbr, val;
   int arr[100];
 
   printf(" Enter the number of elements in the array: ");
   scanf("%d", &nbr);
 
   printf(" Enter the %d elements: ", nbr);
 
   for (i = 0; i < nbr; i++)
      scanf("%d", &arr[i]);
 
   printf(" Enter the position where you want to insert the element: ");
   scanf("%d", &position);
 
   printf(" Enter value to be inserted: ");
   scanf("%d", &val);
 
   for (i = nbr - 1; i >= position - 1; i--)
      arr[i+1] = arr[i];
 
   arr[position-1] = val;
 
   printf(" After inserting: ");
 
   for (i = 0; i <= nbr; i++)
      printf("%4d", arr[i]);
 
   return 0;
}

Output:

 Enter the number of elements in the array: 4
 Enter the 4 elements: 1 2 3 4
 Enter the position where you want to insert the element: 1
 Enter value to be inserted: 9
 After inserting:    9   1   2   3   4

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *