Splitting an array in 2

closed account (jEb91hU5)
Hello,

I'm having a bit of trouble starting the code for a project. The problem states that you are to take an array with 20 numbers, written in another file, and split it into two arrays--one with the even numbers and one with the odd numbers. I would appreciate some help on how to begin this. I've written out some code, but it hasn't worked, so I scrapped it. I understand how to split an array evenly, but I'm just having trouble splitting it to even and odd integers.

Thanks!
Last edited on
What does "split" mean? Does it mean you create two new arrays, one full of odd numbers and one full of even, or does it mean you're to use the exact same memory for the created arrays?
Last edited on
closed account (jEb91hU5)
"Split" means make two new arrays.
Create two new arrays.
Looks at every number in the original array.
If the number is even, copy it into the first new array.
If the number is odd, copy it into the second new array.
closed account (jEb91hU5)
Here is the code that I'm trying to fix now. But the output isn't putting out the correct values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>

using namespace std;

//function prototypes
int splitOdd(int[], int[], int);
int splitEven(int[], int[], int);
void displayArr(int[], int);

int main()
{
	const int SIZE = 20;
	int usedEven, usedOdd;
	int origArr[SIZE] = { 4, 7, 12, 6, 8, 3, 30, 7, 20, 13, 17, 6, 31, 4, 3, 19, 15, 9, 12, 18 };
	int evenArray[SIZE];
	int oddArray[SIZE];


	usedEven = splitEven(origArr, evenArray, SIZE);
	usedOdd = splitOdd(origArr, oddArray, SIZE);


	cout << "Even Values: " << endl;
	displayArr(evenArray, usedEven);
	cout << endl;
	cout << "Odd Values: " << endl;
	displayArr(oddArray, usedOdd);

	system("pause");
	return 0;
}

int splitEven(int origArr[], int evenArray[], int SIZE)
{
	int j = 0;
	for (int i = 0; i < SIZE; i++ && j++)
	{
		if (origArr[i] % 2 == 0)
			evenArray[j] = origArr[i];

	}

	return j;

}

int splitOdd(int origArr[], int oddArray[], int SIZE)
{
	int k = 0;
	for (int i = 0; i < SIZE; i++ && k++)
	{
		if (origArr[i] % 2 == 1)
			oddArray[k] = origArr[i];

	}

	return k;
}

void displayArr(int newArray[], int used)
{
	for (int i = 0; i < used; i++)
		cout << newArray[i] << endl;
	return;

}
Inside your splitEven and splitOdd functions. Shouldn't you increase j and k ONLY when you've actually added something to the new array?
closed account (jEb91hU5)
Yes. Do you do that by putting the "j++" and "k++" within the "if statements?"
You tell me. Right now, you're incrementing j and k with every loop.

You need to increment it only if a copy operation happened.
Topic archived. No new replies allowed.