Yu Xiong
Yu Xiong

Reputation: 343

finding even numbers in the array issue (C++)

My code is to extract odd number and even number in an 1D array.

#include <iostream>
using namespace std;

int main() {
    int a[6] = {1,6,3,8,5,10};
    int odd[]={};
    int even[]={};

    for (int i=0; i < 6; i++) {
        cin >> a[i];
    }

    for (int i=0; i < 6; i++) {
        if (a[i] % 2 == 1) {
            odd[i] = a[i];
            cout << odd[i] << endl;
        }
    }

    cout << " " << endl;

    for (int i=0; i < 6; i++) {
        if (a[i] % 2 == 0) {
            even[i] = a[i];
            cout << even[i] << endl;
        }
    }

    return 0;
}

the output is:

1
3
5

2
1
6

It shows that it successfully extract odd numbers but the same method applied to the even number. It comes with an issue while the even number is 4.

Could anyone help me find the cause here? Thanks.

Upvotes: 1

Views: 9772

Answers (3)

user3285991
user3285991

Reputation:

First, although not causing a problem, you initialize an array with data and then overwrite it. The code

int a[6] = {1,6,3,8,5,10};

can be replaced with

int a[6];

Also, as stated in the comments,

int odd[]={};

isn't valid. You should either allocate a buffer as big as the main buffer (6 ints) or use a vector (although I personally prefer c-style arrays for small sizes, because they avoid heap allocations and extra complexity). With the full-size buffer technique, you need a value like -1 (assuming you intend to only input positive numbers) to store after the list of values in the arrays to tell your output code to stop reading, or store the sizes somewhere. This is to prevent reading values that haven't been set.

I don't understand your problem when 4 is in the input. Your code looks fine except for your arrays.

Upvotes: 1

Victor Istomin
Victor Istomin

Reputation: 1156

You've got an Undefined Behavior, so result may be any, even random, even formatted hard drive.

int odd[] = {} is the same as int odd[/*count of elements inside {}*/] = {/*nothing*/}, so it's int odd[0];

Result is not defined when you're accessing elements besides the end of array. You probably have to think about correct odd/even arrays size, or use another auto-sizeable data structure.

Upvotes: 1

Pavel P&#225;ja Halbich
Pavel P&#225;ja Halbich

Reputation: 1583

You can use std::vector< int > odd; and then call only odd.push_back(elem) whem elem is odd.

Upvotes: 0

Related Questions