Insert element in to C array

Previous
Next

How can we insert an element into array?

  • To insert the element into specific location, we must shift all other elements by 1 location towards right side.
  • We use loop for shifting multiple elements.
  • We need to shift elements from specified index to last index.
#include<stdio.h>
int main()
{
	int arr[20], n, i, ele, loc ;
	printf("Enter size : ");
	scanf("%d", &n);
	
	printf("Enter elements : \n");
	for(i=0 ; i<n ; i++)
		scanf("%d", &arr[i]);
		
	printf("Enter element to insert : ");
	scanf("%d", &ele);
	
	printf("Enter location to insert : ");
	scanf("%d", &loc);
	
	for(i=n-1 ; i>=loc ; i--)
		arr[i+1] = arr[i];
	
	arr[loc] = ele;
	
	printf("Array elements now : \n");
	for(i=0 ; i<=n ; i++)
		printf("%d \n", arr[i]);
	return 0;
}
Output:

Enter size : 6
Enter elements :
10
20
30
40
50
60
Enter element to insert : 100
Enter location to insert : 2
Array elements now :
10
20
100
30
40
50
60
Previous
Next

Add Comment

Courses Enquiry Form