
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete an element from array using two traversals and one traversal in C++?
Two Traversals
Let us first define the original array and the element to be searched and deleted from the array −
int ele = 5; int arr = [1,2,3,4];
Now we loop in the array to find the given element −
for (i=0; iIf the given element position is found then we shift the elements to left which are in right to the found element −
if (i < length) { length--; for (int j=i; jExample
Let us see the following implementation to see the deletion of element in the array in two traversals −
#includeusing namespace std; int main() { int arr[] = {11, 15, 6, 8, 9, 10}; int length = sizeof(arr)/sizeof(arr[0]); int ele = 6; int i; for (i=0; i Output
The above code will produce the following output −
The array after deletion is 11 15 8 9 10One Traversal
Let us first define the original array and the element to be searched and deleted from the array −
int ele = 15; int arr = [11,15,6,8,9,10];Now we declare two variables Boolean found which specifies if the element is found or not and int pos which will store the element position if found −
bool found=false; int pos=-1;Next, we search the array and if an element is found we store its position and shift elements while our loop is traversing in a single go.
for (int i=0; iExample
Let us see the following implementation to see the deletion of element in the array in one traversal only −
#includeusing namespace std; int main() { int arr[] = {11, 15, 6, 8, 9, 10}; int length = sizeof(arr)/sizeof(arr[0]); int ele = 6 ; bool found=false; int pos=-1; for (int i=0; i Output
The above code will produce the following output −
The array after deletion is 11 15 8 9 10