Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing odd numbers from an array

I am trying to remove odd numbers from an array, but I'm not allowed to create a new array to store the new values.

So, if I have arr[1,2,3,4,5,6,7,8,9] then I need it to be arr[2,4,6,8] so that arr[0] will be 2 and not 1.

I can't seem to be able to drop the even numbers without creating a new array to store the values and then feed it back into the original array with the new values.

I have tried to make arr[i] = 0 if its an odd number but then I wasn't able to drop the 0 and replace it with the next even number.

So far, I have this:

void removeOdd(int arr[], int& arrSize){
    int i, j = 0;
    int temp;
    int newArrSize;
    for(i = 0, newArrSize = arrSize; i < arrSize; i++){
        if(arr[i] % 2 != 0){
            arr[i] = 0;
        }
    }
    arrSize = newArrSize;
}
like image 584
Knarz Avatar asked Sep 05 '26 05:09

Knarz


1 Answers

// Moves all even numbers into the beginning of the array in their original order
int removeOdd(int arr[], int arrSize) {
    int curr = 0; // keep track of current position to insert next even number into
    for (int i = 0; i < arrSize; ++i) {
        if (arr[i] % 2 == 0) {
            arr[curr++] = arr[i];
        }
    }
    return curr;
}

int main() {
    int arr[10] = { 0,1,2,3,4,5,6,7,8,9 };
    int newSize = removeOdd(arr, 10);
    for (int i = 0; i < newSize; ++i) {
        std::cout << arr[i] << " ";
    }
}

0 2 4 6 8

You might want to use std::vector:

void removeOdd(std::vector<int>& arr) {
    int curr = 0;
    for (int i = 0; i < (int)arr.size(); ++i) {
        if (arr[i] % 2 == 0) {
            arr[curr++] = arr[i];
        }
    }
    arr.resize(curr);
}

int main() {
    std::vector<int> arr = { 0,1,2,3,4,5,6,7,8,9 };
    removeOdd(arr);
    for (int number : arr) {
        std::cout << number << " ";
    }
}
like image 126
Yola Avatar answered Sep 07 '26 20:09

Yola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!