DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Array Question (http://www.daniweb.com/forums/thread160584.html)

SQ89 Dec 3rd, 2008 12:27 pm
Array Question
 
I have an Array A[N]={1,2,3,4,5,6};
and I want to split it to 2 arrays of size N/2
such that B = 1, 2, 3 and C = 4, 5, 6
here is my program but there is something wrong with array C
Can you help me with it ?

#include <iostream.h>

void print(int X[], int newsize);
void main ()
{
        int const N=6;
        int A[N]={1,2,3,4,5,6};
        int C[N/2],B[N/2];

        for(int i =0;i<N;i++)
        {
               
                if(i>N/2)
                {
                        int k=0;
                        C[k]=A[i];
                k++;
                }
        else
                B[i]=A[i];
        }
        print(B,N);
        cout<<endl;
        print(C,N);
}
void print(int X[],int size)
{
        int newsize;
        newsize=size/2;
        for(int i=0;i<newsize;i++)
                cout<<X[i]<<"\t";
}

mrboolf Dec 3rd, 2008 12:43 pm
Re: Array Question
 
Some general considerations first:

1 - main must return an int, so it's
int main()
and not
void main()
. I think your compiler should have issued a warning at least. Here's an explanation of why.
2 - you use deprecated
<iostream.h>
instead of
<iostream>
. To this also your compiler should have issued a warning. Take a look at this before changing it.

Coming to the "real" errors:
1 - instead of
if(i>N/2)
it should be
if(i>=N/2)
and
2 - You initialize k to 0 every time you enter the if block, basically rewriting only the first position of the C array. Take k declaration out of the loop, like this:
        int k=0;
        for(int i =0;i<N;i++) {
                if(i>=N/2) {
                        C[k]=A[i];
                        k++;
                }
                else
                        B[i]=A[i];
        }

SQ89 Dec 3rd, 2008 1:03 pm
Re: Array Question
 
Thank you :D
it works now :)


All times are GMT -4. The time now is 1:45 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC