Insert an element in an array with C.
/*
Example
Input
Input array elements: 10, 20, 30, 40, 50
Input element to insert: 25
Input position where to insert: 3
Output
Elements of array are: 10, 20, 25, 30, 40, 50
*/
#include <stdio.h>
int main()
{
int arr[100];
int i, n, num, pos;
/* Input n of the array */
printf("Enter n of the array : ");
scanf("%d", &n);
/* Input elements in array */
printf("Enter elements in array : ");
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
/* Input new element and position to insert */
printf("Enter element to insert : ");
scanf("%d", &num);
printf("Enter the element position : ");
scanf("%d", &pos);
/* If position of element is not valid */
if (pos > n + 1 || pos <= 0)
{
printf("Invalid position! Please enter position between 1 to %d", n);
}
else
{
/* Make room for new array element by shifting to right */
for (i = n-1; i >= pos-1; i--)
{
arr[i+1] = arr[i];
}
/* Insert new element at given position and increment n */
arr[pos - 1] = num;
/* Print array after insert operation */
printf("Array elements after insertion : ");
for (i = 0; i < n+1; i++)
{
printf("%d ", arr[i]);
}
}
return 0;
}
Output
Enter n of the array : 4
Enter elements in array : 1 2 3 4
Enter element to insert : 6
Enter the element position : 2
Array elements after insertion : 1 6 2 3 4
0 Comments