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 array element in given index range [L – R] in C++?
Let us first define the original array and the exclusive range for deletion of the array elements and also find the original array length −
int arr[] = { 2,4,6,8,10,12,14,16,18,20};
int L = 2, R = 6;
int length = sizeof(arr) / sizeof(arr[0]);
Now we loop in the array and if index position (i) is greater than L or R we increment the variable k which will be used to shift positions(delete) of array element once the index value (i) lies between the range L and R. Also, the new length of the given array will be k.
int k = 0;
for (int i = 0; i < length; i++) {
if (i <= L || i >= R) {
arr[k] = arr[i];
k++;
}
}
Example
Let us see the following implementation to get a better understanding of deleting array elements in given index
#include <iostream>
using namespace std;
int main() {
int arr[] = { 2,4,6,8,10,12,14,16,18,20};
int L = 2, R = 6;
int length = sizeof(arr) / sizeof(arr[0]);
int k = 0;
for (int i = 0; i < length; i++) {
if (i <= L || i >= R) {
arr[k] = arr[i];
k++;
}
}
length=k;
for (int i = 0; i < length; i++)
cout << arr[i] << " ";
return 0;
}
Output
The above code will produce the following output −
2 4 6 14 16 18 20
Advertisements