This tutorial will help you insert an element in between an array in c. C is a computer programming language that is primarily used for writing efficient programs for different operating systems. There is a need to use the C language in various fields such as communication, video processing, audio processing, and many more. C programs run efficiently on low-end devices like Android smartphones and tablets.
C Program for Inserting Element in between an Array
Here in this program, we will see how to insert an element in-between an array. We can define the length of the array and also specify the location where you want the new value to be inserted. The program will display the array after the value has been inserted.
- Define a macro called max and initialize it to a value of 100
- Define an array p of size max elements
- Enter the length of the array when prompted. The length you enter will be
assigned to a variable n: - A for loop will be executed prompting you to enter the elements of the array
- Specify the position in the array where the new value has to be inserted
- The arrays in C are zero-based, and the position you enter is decremented by.
1: - Create space for the new element at the specified index location, all the7.
elements are shifted one position down - Enter the new value which will be inserted at the vacated index location
#include
#define max 100
void main()
{
int p[max], n,i,k,j;
printf("Enter length of array:");
scanf("%d",&n);
printf("Enter %d elements of array\n",n);
for(i=0;i<=n-1;i++ )
scanf("%d",&p[i]);
printf("\nThe array is:\n");
for(i = 0;i<=n-1;i++) printf("%d\n",p[i]); printf("\nEnter position where to insert:"); scanf("%d",&k); k--;/*The position is always one value higher than the subscript, so it is decremented by one*/ for(j=n-1;j>=k;j--)
p[j+1]=p[j];
/* Shifting all the elements of the array one position down from
the location of insertion */
printf("\nEnter the value to insert:");
scanf("%d",&p[k]);
printf("\nArray after insertion of element: \n");
for(i=0;i<=n;i++)
printf("%d\n",p[i]);
}