st4evr - 1 year ago 87

C++ Question

Beginner in C++ here and learning arrays. The program below is supposed to separate positive and negative numbers in an array. However, it is returning random numbers in both the splitPos and splitNeg functions.

Could someone ever so kindly advice and show me what is incorrect in the functions and what can be done to omit these random digits so that only positive and negative digits are returned respectively by the program for each function/loop? I am obviously not seeing and/or understanding what is incorrect.

Thank you so very much for your help and time in advance!!!

`#include <iostream>`

using namespace std;

//function prototypes

int splitNeg(int[], int[], int);

int splitPos(int[], int[], int);

void displayArr(int[], int);

int main()

{

const int SIZE = 20;

int usedPos, usedNeg;

int origArr[SIZE] = { 4, -7, 12, 6, 8, -3, 30, 7, -20, -13, 17, 6, 31, -4, 3, 19, 15, -9, 12, -18 };

int posArray[SIZE];

int negArray[SIZE];

usedPos = splitPos(origArr, posArray, SIZE);

usedNeg = splitNeg(origArr, negArray, SIZE);

cout << "Positive Values: " << endl;

displayArr(posArray, usedPos);

cout << endl;

cout << "Negative Values: " << endl;

displayArr(negArray, usedNeg);

return 0;

}

int splitPos(int origArr[], int posArray[], int SIZE)

{

int j = 0;

for (int i = 0; i < SIZE; i++ && j++)

{

if (origArr[i] >= 0)

posArray[j] = origArr[i];

}

return j;

}

int splitNeg(int origArr[], int negArray[], int SIZE)

{

int k = 0;

for (int i = 0; i < SIZE; i++ && k++)

{

if (origArr[i] < 0)

negArray[k] = origArr[i];

}

return k;

}

void displayArr(int newArray[], int used)

{

for (int i = 0; i < used; i++)

cout << newArray[i] << endl;

return;

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

If you change your for-loops a bit:

```
int splitPos(int origArr[], int posArray[], int SIZE)
{
int j = 0;
for (int i = 0; i < SIZE; i++)
{
if (origArr[i] >= 0)
posArray[j++] = origArr[i];
}
return j;
}
int splitNeg(int origArr[], int negArray[], int SIZE)
{
int k = 0;
for (int i = 0; i < SIZE; i++)
{
if (origArr[i] < 0)
negArray[k++] = origArr[i];
}
return k;
}
```

you will get the result you desire.

The counter variables of your target arrays only get increased if you find a value that matches the criterion of being less (or greater) than 0.

I honestly do not understand what you tried to achieve with a ... hmmm.. "combined" increase like `i++ && j++`

, this goes into short circuit evaluation.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**