C++ Program to delete an element in an array


In this program, You will learn how to delete an element in an array in C++.


List is: 1 2 3 4 5 6

Delete item: 6

New list is: 1 2 3 4 5


Example: How to delete an element in an array in C++

Run it Now
#include<iostream>
using namespace std;

int main() {

    int arr[10], i, n, num, p = 0;

    cout << "Enter Size of an Array :";
    cin>>n;

    cout << "\nEnter Array Elements :";
    for (i = 0; i < n; i++) {
        cin >> arr[i];
    }
    cout << "\nEnter Element for Delete :";
    cin>>num;

    for (i = 0; i < n; i++) {
        if (arr[i] == num) {
            arr[i] = arr[i + 1];
            p = 1;
        } else if (p > 0) {
            arr[i] = arr[i + 1];
        }
    }
    cout << "\nNew Array List is :";
    for (i = 0; i < n - p; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Output:

Enter Size of an Array :5
Enter Array Elements :1 2 3 4 5
Enter Element for Delete :3
New Array List is :1 2 4 5