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

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to delete elements from the given range. Let's see the steps to solve the problem.

  • Initialize the array and range to delete the elements from.

  • Initialize a new index variable.

  • Iterate over the array.

    • If the current index is not in the given range, then update the element in the array with a new index variable

    • Increment the new index.

  • Return the new index.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int deleteElementsInRange(int arr[], int n, int l, int r) {
   int i, newIndex = 0;
   for (i = 0; i < n; i++) {
      // adding updating element if it is not in the given range
      if (i <= l || i >= r) {
         arr[newIndex] = arr[i];
         newIndex++;
      }
   }
   // returing the updated index
   return newIndex;
}
int main() {
   int n = 9, l = 1, r = 6;
   int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
   int updatedArrayLength = deleteElementsInRange(arr, n, l, r);
   for (int i = 0; i < updatedArrayLength; i++) {
      cout << arr[i] << " ";
   }
   cout << endl;
   return 0;
}

Output

If you execute the above program, then you will get the following result.

1 2 7 8 9

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 27-Jan-2021 12:00:35
Advertisements