Array Operations
Insertion Operation
In the insertion operation, we are adding one or more elements to the array.
Based on the requirement, a new element can be added at the beginning, end,
or any given index of array. This is done using input statements of the
programming languages.
Algorithm
Following is an algorithm to insert elements into a Linear Array until we reach
the end of the array –
1. Start
2. Create an Array of a desired datatype and size.
3. Initialize a variable 'i' as 0.
4. Enter the element at ith index of the array.
5. Increment i by 1.
6. Repeat Steps 4 & 5 until the end of the array.
7. Stop
Example
Here, we see a practical implementation of insertion operation, where we add
data at the end of the array −
#include <stdio.h>
int main()
{
int LA[3] = {}, i;
printf("Array Before Insertion:\n");
for(i = 0; i < 3; i++)
printf("LA[%d] = %d \n", i, LA[i]);
printf("The array elements after insertion :\n"); // prints array values
for(i = 0; i < 3; i++)
LA[i] = i + 2;
printf("LA[%d] = %d \n", i, LA[i]);
}
return 0;
}
Output is :
Array Before Insertion:
LA[0] = 0
LA[1] = 0
LA[2] = 0
Array After Insertion:
LA[0] = 2
LA[1] = 3
LA[2] = 4
Array - Deletion Operation
In this array operation, we delete an element from the particular index of an
array. This deletion operation takes place as we assign the value in the
consequent index to the current index.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer such
that K<=N. Following is the algorithm to delete an element available at the
Kth position of LA.
1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N-1
4. Set LA[J] = LA[J + 1]
5. Set J = J+1
6. Set N = N-1
7. Stop
Example
#include <stdio.h>
void main(){
int LA[] = {1,3,5};
int n = 3;
int i;
printf("The original array elements are :\n");
for(i = 0; i<n; i++)
printf("LA[%d] = %d \n", i, LA[i]);
for(i = 1; i<n; i++)
LA[i] = LA[i+1];
n = n - 1;
printf("The array elements after deletion :\n");
for(i = 0; i<n; i++)
printf("LA[%d] = %d \n", i, LA[i]);