2 Arrays (1 even, 1 odd numbers)

How could I create 2 arrays; one that holds only even numbers and one that only holds odds? They will both hold N number of elements in which N is inputted by the user before.
declare the even and odd arrays
receive input, check input
if odd -> assign to odd array, keep an index count
ditto for even
seems to be a theme this week. You can't. N must be known at compile time for *arrays*.

that looks like

int odd[] = {1,3,5,7,9};

you can do it with a pointer or vector, which can be sized at run-time. Vectors are the best approach for most applications.

vector<int> odd;
for(i = 1; i < valuethatisntnabove; i+=2) //you need to compute the loop counter, which is not N.
odd.push_back(i);

I have this so far
1
2
3
4
5
6
7
8
9
int main() {
    int N = NULL;
    cout << "How big would you like each array to be?" << endl;
    cin >> N;
    int *px = new int[N];
    int *py = new int[N];
    return 0;
}


I can't assign them when initialized because I don't know how many elements will be in it.
ok, the pointer solution works.

I don't understand what you said, but now you need a loop to assign the values.
There are cryptic ugly ways to do the loop without the extra variables, this is explicit code to show what is being done clearly.

int e = 2; //0 is not even, according to theory
int o = 1;
int dx;

for(dx = 0; dx < N; dx++)
{
px[dx] = o;
py[dx] = e;
e+=2;
o+=2;
}

you probably want a loop to print your arrays in here somewhere.

and you need to return the memory you got:
delete[] px;
delete[]py;
return 0;
Last edited on
Topic archived. No new replies allowed.