splitting an array into negative and positive

here i want to split an array into an array of positive and negative numbers,however i dun want my output to show the zeroes at the end,please help!

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
#include <iostream>
using namespace std;
#define SIZE 10
int main()
{
    int num[SIZE]={4,-2,-8,1,7,9,-23,-6,56,23};
    int pos[SIZE]={0},neg[SIZE]={0};
    int j=0,k=0;
    for(int i=0;i<SIZE;i++)
    {
        if(num[i]<0)
        {
            neg[j]=num[i];
            ++j;
        }
        else
        {
            pos[k]=num[i];
            ++k;
        }
    }
    cout<<"originally numbers in the array are\n";
    for(int i=0;i<SIZE;i++)
        cout<<num[i]<<"\t";
    cout<<"\nPositive number array is\n";
    for(int i=0;i<SIZE;i++)
        cout<<pos[i]<<"\t";
    cout<<"\nnegative number array is\n";
    for(int i=0;i<SIZE;i++)
        cout<<neg[i]<<"\t";
}
Since you're keeping track of how many positive and negative numbers there are, this is really easy.

line 26: Change i<SIZE to i<k
line 29: Change i<SIZE to i<j
here i want to split an array into an array of positive and negative numbers,however i dun want my output to show the zeroes at the end,please help!

Then you should probably make use of j and k when you're printing out those arrays.

An alternative:
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
// http://ideone.com/JuwFBe
#include <iostream>
#include <algorithm>
#include <iterator>

template <typename iter_type>
void print(iter_type beg, iter_type end)
{
    std::cout << *beg;

    while (++beg != end)
        std::cout << ' ' << *beg;

    std::cout << '\n';
}


int main()
{
    int num[] = { 4, -2, -8, 1, 7, 9, -23, -6, 56, 23 };

    std::cout << "before partition\n\t";
    print(std::begin(num), std::end(num));

    // http://en.cppreference.com/w/cpp/algorithm/partition
    auto p = std::partition(std::begin(num), std::end(num), [](int n) {return n < 0; });

    std::cout << "\nafter partition\n\t";
    print(std::begin(num), std::end(num));

    std::cout << "\nnegative numbers (" << p - std::begin(num) << ")\n\t";
    print(std::begin(num), p);

    std::cout << "\npositive numbers (" << std::end(num) - p << ")\n\t";
    print(p, std::end(num));

}
Topic archived. No new replies allowed.