➤ Insert an Element at Specific Position in Array in C Language.
1. In this problem First, we have to take an array and declare the size of
an array and, as usual, Insert the elements in an array.
Till now our array is storing the elements only, this is a simple Array program in C.
2. The next step is to ask the user to Insert an Element which user's wants
to store in a Specific Position of an array. Ask for the the position where
an element wants to store. So basically here we have asked the user to
New Element and a Specific Position of an Array.
3. Here we have to increase the length of an Array by 1 and shift the Array element by 1.
There will be no issue with the size of the array cause we already increase
the size of the array by 1. We only have to traverse to the Specific Position
and store the new Item and shift the existing Elements.
- ➤ Program to Insert an Element at Specific Position in Array in C Language.
- #include <stdio.h>
- int main()
- {
- int i, arr[50], pos, len;
- int newitem;
- //user's initialize size of array
- printf("Enter the Size of the Array:\n");
- scanf("%d", &len);
- //Enter all the initialize elements
- printf("Enter %d elements for the array:\n", len);
- for (i = 0; i < len; i++)
- {
- scanf("%d", &arr[i]);
- }
- //Enter the new elements to be insert
- printf("Enter the new element in an Array:\n");
- scanf("%d", &newitem);
- // Enter the specific position where elements to be insert in array
- printf("Enter the Specific Position in Array:\n");
- scanf("%d", &pos);
- len++;
- pos--;
- i = len - 1;
- while (i >= pos)
- {
- arr[i] = arr[i - 1];
- i--;
- }
- arr[pos] = newitem;
- printf("Array after inserting new element\n");
- for (i = 0; i < len; i++)
- {
- printf(" %d", arr[i]);
- }
- return 0;
- }
- ➤ OUTPUT :
- Enter the Size of the Array:
- 4
- Enter 4 elements for the array:
- 23
- 45
- 67
- 78
- Enter the new element in an Array:
- 89
- Enter the Specific Position in Array:
- 3
- Array after inserting new element
- 23 45 89 67 78