Array Operations
Deletion from Array :
In this tutorial, we will discuss the deletion operation in arrays.
We will use an example array of size 5 to explain the process of deleting
data from a specific position at the beginning and end of the array. We
will also write the code and analyse the time complexity of the
operation.
First, we initialise an array of size 50 and ask the user for the
number of elements they want to insert. We then populate the array with
the user's input and ask them which position they want to delete data
from. For example, if they choose position 2 (index 1), we cannot leave
that space blank. Instead, we shift the elements to fill the empty space
and decrease the size of the array by 1.
We start a loop to shift the elements to the left, starting from the
index before the position chosen by the user until the second last index
of the array. We shift the element at index i+1 to index i and continue
until the end of the loop, overwriting the deleted element. If we want to
print the deleted data, we store it in a separate variable before shifting
the elements.
We provide the code for the deletion operation, where we ask the
user for the position to delete, check if it's a valid position, and then start
the loop to shift the elements.
int size = 5;
int arr[size];
int pos, i;
int item; // ask user for position to delete
printf("Enter position to delete: ");
scanf("%d", &pos); // check if valid position
if (pos <= 0 || pos > size)
Deletion from Array :
In this tutorial, we will discuss the deletion operation in arrays.
We will use an example array of size 5 to explain the process of deleting
data from a specific position at the beginning and end of the array. We
will also write the code and analyse the time complexity of the
operation.
First, we initialise an array of size 50 and ask the user for the
number of elements they want to insert. We then populate the array with
the user's input and ask them which position they want to delete data
from. For example, if they choose position 2 (index 1), we cannot leave
that space blank. Instead, we shift the elements to fill the empty space
and decrease the size of the array by 1.
We start a loop to shift the elements to the left, starting from the
index before the position chosen by the user until the second last index
of the array. We shift the element at index i+1 to index i and continue
until the end of the loop, overwriting the deleted element. If we want to
print the deleted data, we store it in a separate variable before shifting
the elements.
We provide the code for the deletion operation, where we ask the
user for the position to delete, check if it's a valid position, and then start
the loop to shift the elements.
int size = 5;
int arr[size];
int pos, i;
int item; // ask user for position to delete
printf("Enter position to delete: ");
scanf("%d", &pos); // check if valid position
if (pos <= 0 || pos > size)