C program to insert an element in an array at a specified position – In this article, we will discuss the only method mentioned here to insert an element in an array at a specified position.
Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has also been added with which you can execute it yourself.
The only means used here to do so is using the standard method.
As you can see in the photo uploaded, firstly, the size of the array is entered.
In this case, the size of the array entered is 5.
Later, the elements of the array are entered.
Here, the elements that are added are as follows:
1, 2, 3, 4 and 5
Once it is done, the place of the change is to be selected. In the photo, the spot that is chosen is 2 which is equal to a[2], the third position.
So, the third element will be changed with a new one which will be inserted.
The new element is given, which in this case is 0.
So, the new order after insertion would look like 1, 2, 0, 4, 5.
Thus, the process to do the same in C programming is as follows:
Using Standard Method
- Read the size of the array and store it into the variable n.
2) Read the entered elements and store the element into the array as scanf(“%d”,&a[i]) using for loop for(i=0;i<n;i++).
3) To insert the element at a particular index in an array
a) Read the entered index number which should be less than the array size and store the value into the variable index.
b) Read the new element which we want to insert and store into the variable new1.
c) print the array elements using the print() function before inserting the new element. Using for loop it prints the array elements.
d) Insert the new element as a[index]=new1.
e) Print the array elements using print() function after insertion of the new element. Then we can observe the new element at which position it was inserted into the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
#include <stdio.h> #include <conio.h> print(int a[],int n) { int i; for(i=0; i<n; i++) { printf("%d ",a[i]); } } int main() { int a[1000],i,n,index,new1; printf("Enter size of the array : "); scanf("%d", &n); printf("Enter elements in array : "); for(i=0; i<n; i++) { scanf("%d",&a[i]); } printf("Enter index should be less than %d:",n); scanf("%d",&index); if(index<n) { printf("Enter new element : "); scanf("%d",&new1); printf("before insertion :"); print(a,n); a[index]=new1; printf("\nafter insertion :"); print(a,n); } return 0; } |
1 2 3 4 5 6 7 8 9 10 |
Enter size of the array: 5 Enter elements in array: 1 2 3 4 5 Enter index should be less than 5:2 Enter new element : 0 before insertion :1 2 3 4 5 after insertion :1 2 0 4 5 |