01/03/2023

Insert an Element at Specific Position in Array in C Program

Write a C Program to Insert an element at a particular index in an array or we can say that a C program to Insert an Element at a Specific Position of an array. This is a very simple program, Below I am explaining every step to solve this problem. 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.

Insert an Element at Specific Position in Array in C Program

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;
 }

The Output of Insert an Element at a Specific Position


The Output of Insert an Element at a Specific Position

Similar to Insert an Element at a Specific Position of an Array


Previous Post
Next Post

post written by:

Hi, I’m Ghanendra Yadav, SEO Expert, Professional Blogger, Programmer, and UI Developer. Get a Solution of More Than 500+ Programming Problems, and Practice All Programs in C, C++, and Java Languages. Get a Competitive Website Solution also Ie. Hackerrank Solutions and Geeksforgeeks Solutions. If You Are Interested to Learn a C Programming Language and You Don't Have Experience in Any Programming, You Should Start with a C Programming Language, Read: List of Format Specifiers in C.
Follow Me

0 Comments: