The next step is to ask the user to Insert an Element which He/She 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.
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.
Insert an Element at Specific Position in Array in C Program
#include <stdio.h>
int main()
{
/* C Program to Insert an Element at Specific Position in Array */
int i, arr[50], pos, len;
int newitem;
printf("Enter the Size of the Array:\n");
scanf("%d", &len);
printf("Enter %d elements for the array:\n", len);
for (i = 0; i < len; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter the new element in an Array:\n");
scanf("%d", &newitem);
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;
}
0 Comments: