Advertisement

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 an item: 6

A new list is: 1 2 3 4 5

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

#include<iostream>
using namespace std;

int main() {

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

    cout << "Enter size of an array:";
    cin>>n;

    cout << "Enter array elements:";
    for (i = 0; i < n; i++) {
        cin >> arr[i];
    }
    cout << "Enter 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 << "New 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:10 20 30 40 50
Enter element for delete:30
New array list is:10 20 40 50