How to remove the last element from an array in C++

In this article, we are going to learn how to remove the last element from an array in C++. To delete the last element from an array we first get the array size and the array elements from the user.

Arrays themselves have unchangeable length. The usual method for extending or shrinking an array is,

  1. Copy to a new array with a for-loop or recursive statement, excluding the last element.
  2. Delete the old array.
  3. Reference new array.

Remove the last element from an array in C++

Let’s take the help of an example.

Input: [1,2,3,4,5]

Output: [1,2,3,4]

Code Implementation:

#include <iostream>
using namespace std;
int main()
{
  int arr[50], size, i, count=0;
  cout<<"Enter array size : ";
  cin>>size;
  cout<<"Enter array elements : ";
  for(i=0; i<size; i++)
  {
    cin>>arr[i];
  }
  
  for(i=0; i<size; i++)
  {
    if(arr[i]==arr[size-1])
    {
      for(int j=i; j<(size-1); j++)
      {
        arr[j]=arr[j+1];
      }
      count++;
      break;
    }
  }
  if(count==0)
  {
    cout<<"Element not found..!!";
  }
  else
  {
    cout<<"Element deleted successfully..!!\n";
    cout<<"Now the new array is :\n";
    for(i=0; i<(size-1); i++)
    {
      cout<<arr[i]<<" ";
    }
  }
  return 0;
}

 

Working:

We create a new array with a size of less than one of the main array size. Now we start a for loop from the start to less than (size-1). After going to the last element, we copy each element of the main array to the new array created.

I hope, you have understood how our program works to remove the last element from an array in C++ language.

Mention below your comments, if you find any mistake in the article or to share more information related to the topic of this article.

You may also learn,

C++ program to delete the middle element of a stack

Leave a Reply

Your email address will not be published.