How to Delete an Array Element

Beginner

Introduction

In this tutorial, we will learn how to perform the deletion of an array element at a specific position in C++.

Create a new C++ file

Let's start by creating a new C++ file named main.cpp in the ~/project directory.

cd ~/project
touch main.cpp

Write the code

Copy and paste the following code into the main.cpp file:

#include <iostream>
using namespace std;

int main()
{
    int n;
    cout << "Enter the size of the array: ";
    cin >> n;

    int arr[n], i, pos;

    cout << "Enter the " << n << " elements of the array: " << endl;
    for(i = 0; i < n; i++)
    {
        cin >> arr[i];
    }

    //Printing the original array before deletion
    cout << "\nThe " << n << " elements of the array, before deletion are: " << endl;
    for(i = 0; i < n; i++)
    {
        cout << arr[i] << " ";
    }

    cout << "\nEnter the position, between 1 and " << n << " , of the element to be deleted: ";
    cin >> pos;

    //Performing the deletion logic
    --pos;
    for(i = pos; i <= 9; i++)
    {
        arr[i] = arr[i + 1];
    }

    cout << "\nThe " << n - 1 << " elements of the array, after deletion are: " << endl;
    for(i = 0; i < n - 1; i++)
    {
        cout << arr[i] << " ";
    }

    return 0;
}

Compile and run the code

Run the following command in the terminal to compile and execute the code:

g++ main.cpp -o main && ./main

Summary

In this tutorial, we learned how to delete an array element at a specific position in C++. By following the steps outlined above, you should now have a better understanding of how arrays work in C++, and you should be able to apply this knowledge to your own programs.

Other Tutorials you may like