C Program to insert an element in array
C Program to insert an element in an array at a given position.
C Program to insert an element in an array
#include <stdio.h>
void main()
{
int arr[50], size, pos, i, num;
printf("Enter number of elements: ");
scanf("%d", &size);
printf("Enter array elements-\n");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("\nEnter number to insert: ");
scanf("%d", &num);
printf("Enter position to insert element: ");
scanf("%d", &pos);
// check for invalid position
if (pos < 0 || pos > size)
printf("Invalid position");
else
{
// shifting of elements
for (i = size-1; i >= pos-1; i--)
arr[i+1] = arr[i];
arr[pos - 1] = num;
size++;
printf("Array after insertion-\n");
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
}
}
Output
Enter number of elements: 5
Enter array elements-
2
3
6
4
5
Enter number to insert: 100
Enter position to insert element: 4
Array after insertion-
2 3 6 100 4 5