In this cycle
for (i = 0; i < n; i++){ if ( arr[i] >= a && arr[i] <= b ){ arr[i] = arr[i+1]; arr[i] = 0; }
out-of-bounds occurs when i equals n-1 in a sentence
arr[i] = arr[i+1];
and besides, the body of the loop does not make sense, since first the assignment for the element with index i value arr[i+1] , and then this value is overwritten with zero.
arr[i] = arr[i+1]; arr[i] = 0;
Below is a demo program showing how you can "remove" elements from an array that lie in the [a, b] segment, use loops
#include <iostream> int main() { int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; const size_t N = sizeof( arr ) / sizeof( *arr ); for ( size_t i = 0; i < N; i++ ) std::cout << arr[i] << ' '; std::cout << std::endl; int a = 3, b = 6; size_t k = 0; for ( size_t i = 0; i < N; i++ ) { if ( not ( a <= arr[i] && arr[i] <= b ) ) { if ( i != k ) arr[k] = arr[i]; ++k; } } for ( size_t i = k; i < N; i++ ) arr[i] = 0; for ( size_t i = 0; i < N; i++ ) std::cout << arr[i] << ' '; std::cout << std::endl; return 0; }
Output of the program to the console
0 1 2 3 4 5 6 7 8 9 0 1 2 7 8 9 0 0 0 0
The same can be done using standard algorithms. For example,
#include <iostream> #include <algorithm> int main() { int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; const size_t N = sizeof( arr ) / sizeof( *arr ); for ( size_t i = 0; i < N; i++ ) std::cout << arr[i] << ' '; std::cout << std::endl; int a = 3, b = 6; size_t k = 0; std::fill( std::remove_if( arr, arr + N, [&]( int x ) { return a <= x && x <= b; } ), arr + N, 0 ); for ( size_t i = 0; i < N; i++ ) std::cout << arr[i] << ' '; std::cout << std::endl; return 0; }
The output of this program is similar to the one shown above.
0 1 2 3 4 5 6 7 8 9 0 1 2 7 8 9 0 0 0 0