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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | //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: