Array Question

Reply

Join Date: Oct 2008
Posts: 18
Reputation: SQ89 is an unknown quantity at this point 
Solved Threads: 0
SQ89's Avatar
SQ89 SQ89 is offline Offline
Newbie Poster

Array Question

 
0
  #1
Dec 3rd, 2008
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 ?

  1. #include <iostream.h>
  2.  
  3. void print(int X[], int newsize);
  4. void main ()
  5. {
  6. int const N=6;
  7. int A[N]={1,2,3,4,5,6};
  8. int C[N/2],B[N/2];
  9.  
  10. for(int i =0;i<N;i++)
  11. {
  12.  
  13. if(i>N/2)
  14. {
  15. int k=0;
  16. C[k]=A[i];
  17. k++;
  18. }
  19. else
  20. B[i]=A[i];
  21. }
  22. print(B,N);
  23. cout<<endl;
  24. print(C,N);
  25. }
  26. void print(int X[],int size)
  27. {
  28. int newsize;
  29. newsize=size/2;
  30. for(int i=0;i<newsize;i++)
  31. cout<<X[i]<<"\t";
  32. }
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 182
Reputation: mrboolf will become famous soon enough mrboolf will become famous soon enough 
Solved Threads: 18
mrboolf mrboolf is offline Offline
Junior Poster

Re: Array Question

 
0
  #2
Dec 3rd, 2008
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:
  1. int k=0;
  2. for(int i =0;i<N;i++) {
  3. if(i>=N/2) {
  4. C[k]=A[i];
  5. k++;
  6. }
  7. else
  8. B[i]=A[i];
  9. }
Last edited by mrboolf; Dec 3rd, 2008 at 12:45 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2008
Posts: 18
Reputation: SQ89 is an unknown quantity at this point 
Solved Threads: 0
SQ89's Avatar
SQ89 SQ89 is offline Offline
Newbie Poster

Re: Array Question

 
0
  #3
Dec 3rd, 2008
Thank you
it works now
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC