• Home
  • how to delete an element from beginning and at end of array?

how to delete an element from beginning and at end of array?

To delete an element from the beginning of an array, you can use the following steps:

  1. Declare a new array of the same type as the original array, with a length that is one less than the original array.
  2. Use a loop to copy all elements of the original array, except the first element, to the new array.
  3. Set the original array to the new array.

Here is an example in Java:

int[] arr = {1, 2, 3, 4, 5};
int[] newArr = new int[arr.length - 1];

for (int i = 0; i < newArr.length; i++) {
newArr[i] = arr[i + 1];
}

arr = newArr;

To delete an element from the end of an array, you can use the following steps:

  1. Declare a new array of the same type as the original array, with a length that is one less than the original array.
  2. Use a loop to copy all elements of the original array, except the last element, to the new array.
  3. Set the original array to the new array.

Here is an example in Java:

int[] arr = {1, 2, 3, 4, 5};
int[] newArr = new int[arr.length - 1];

for (int i = 0; i < newArr.length; i++) {
newArr[i] = arr[i];
}

arr = newArr;