C++ Program to Delete an Element from an Array

In this tutorial, we will learn and write code on deleting an element from an array in C++. To understand the coding, you should have knowledge of the following topics in C++ programming:


Delete Element from Array in C++

The program takes user input for the size of an array and for the elements of an array. Then the program will ask the user to enter a number from the array to be deleted.

Lastly, after the deletion of an element, the new array is displayed.

C++ Program to Delete an Element from an Array

//C++ Program to Delete an Element in an array
#include <iostream>
using namespace std;

int main()
{
  int arr[30], size, i, delElem, count = 0;

  cout << "Enter the size of an array (Max size: 30): ";
  cin >> size;

  cout << "Enter array elements:\n";
  for (i = 0; i < size; i++)
    cin >> arr[i];

  cout << "\nEnter element to be delete: ";
  cin >> delElem;

  for (i = 0; i < size; i++)
  {
    if (arr[i] == delElem)
    {
      for (int j = i; j < (size - 1); j++)
      {
        arr[j] = arr[j + 1];
      }

      count++;
      break;
    }
  }

  if (count == 0)
  {
    cout << "\nElement not found..!!\n";
  }
  else
  {
    cout << "\nElement deleted successfully..!!\n";

    //Display new array
    cout << "New Array after Deletion:\n";
    for (i = 0; i < (size - 1); i++)
      cout << arr[i] << " ";
  }


  return 0;
}

Output:

delete array element c++