How to insert and delete elements in an array using C
Array is one of the important data structures widely used in programming. This blog post includes the insertion and deletion of elements in array.
Insertion:
An array
is declared and inputs are read from the user. To insert an element, the
position and data are the inputs.
Using loop, we insert the element and displayed the output
after insertion.
C Program:
#include <stdio.h>
int main() {
int a[10];
int n,i,j,k;
printf("Enter
the number of elements:");
scanf("%d",&n);
printf("Enter
the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter
the position to insert an element:");
scanf("%d",&j);
printf("Enter
the element");
scanf("%d",&k);
// Shift the
elements to the next position
for (int i = n; i
>= j; i--) {
a[i] = a[i -
1];
}
a[j- 1] = k; //
add the value
n++; // let the
size increases
printf("Array
after insertion: ");
for (int i = 0; i
< n; i++) {
printf("%d ", a[i]);
}
}
Output:
Enter the number of elements:5
Enter the elements:34 45 56 67 78
Enter the position to insert an element:2
Enter the element90
Array after insertion: 34 90 45 56 67 78
Deletion:
This
program reads the input from the user. It gets the array elements and size,
position to delete and the element to delete.
Finally, it shifts the data to left side and displays the
output.
C Program:
#include <stdio.h>
int main() {
int a[10];
int n,i,j=0,k;
printf("Enter
the number of elements:");
scanf("%d",&n);
printf("Enter
the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter
the position to insert an element:");
scanf("%d",&j);
printf("Enter
the element");
scanf("%d",&k);
// Shift the
elements to the left side of the array
for (int i = j -
1; i < n - 1; i++) {
a[i] = a[i +
1];
}
n--; // it
decreases the size
printf("Array
after deletion: ");
for (int i = 0; i
< n; i++) {
printf("%d ", a[i]);
}
return 0;
}
Output:
Enter the number of elements:5
Enter the elements:23 34 45 56 67
Enter the position to insert an element:3
Enter the element45
Array after deletion: 23 34 56 67
That’s all. Both of the operation in array is successful.
Hope, you found this blog useful to you. Keep Coding!!!
Comments
Post a Comment