1. Let's assume that there is an array, p, with five elements, as follows:
Figure 1.1
Now, suppose you want to enter a value, say 99, at the third position. We will write a C program that will give the following output:
Figure 1.2
Here are the steps to follow to insert an element in an array:
- Define a macro called max and initialize it to a value of 100:
#define max 100
- Define an array p of size max elements:
int p[max]
- Enter the length of the array when prompted. The length you enter will be assigned to a variable n:
printf("Enter length of array:");
scanf("%d",&n);
- A for loop will be executed prompting you to enter the elements of the array:
for(i=0;i<=n-1;i++ )
scanf("%d",&p[i]);
- Specify the position in the array where the new value has to be inserted:
printf("\nEnter position where to insert:");
scanf("%d",&k);
- Because the arrays in C are zero-based, the position you enter is decremented by 1:
k--;
- To create space for the new element at the specified index location, all the elements are shifted one position down:
for(j=n-1;j>=k;j--)
p[j+1]=p[j];
- Enter the new value which will be inserted at the vacated index location:
printf("\nEnter the value to insert:");
scanf("%d",&p[k]);
Here is the insertintoarray.c program for inserting an element in between an array:
#include<stdio.h>
#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]);
}
Now, let's go behind the scenes to understand the code better.