Delete array element in given index range [L – R] in C++?

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 16-Jan-2021 06:53:01
Advertisements