### Divide array

I have a stream of numbers that I want to divide into two separate arrays
my coding works while in the loop but not if I try to output the two arrays together
any suggestions
 ``12345678910111213141516171819202122232425262728293031323334353637`` ``````#include int main() { using namespace std; int i; int a[5]; int b[5]; int array[10]= {1,2,3,4,5,6,7,8,9,0}; for(i=0; i<5; i++){ a[i]=array[i]; cout << a[i]; // output = 12345 } for(i=5; i<10; i++){ b[i]=array[i]; cout << b[i]; // output = 678910 } for(i=0; i<5; i++){ cout<

What I want is output =
1 6
2 7
3 8
4 9
5 10
The problem is that in the second loop you are accessing b[5] to b[9]. What you want is b[0] to b[4] so you have to adjust the index by doing subtraction.
 ``1234`` ``````for(i=5; i<10; i++) { b[i] = array[i]; }``````

Careful!

 ``1234`` ``````for(i=5; i<10; i++) { b[i-5] = array[i]; }``````
Thank you both for that I will try your coding.
To avoid such errors you can use standard algorithm std::copy

For example

 ``12345678910111213141516171819202122232425262728`` ``````#include #include int main() { const size_t N = 5; int a[N]; int b[N]; int array[2 * N]= { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; std::copy( array, array + N, a ); std::for_each( a, a + N, []( int x ) { std::cout << x; } ); std::cout << std::endl; std::copy( array + N, array + 2 * N, b ); std::for_each( b, b + N, []( int x ) { std::cout << x; } ); std::cout << std::endl; for( size_t i=0; i < N; i++ ) { std::cout << a[i] << " " << b[i] << "\n"; } return 0; }``````

Last edited on
Thank you Peter87 & iHutch105 your suggestions together gave me the correct result.

I owe you both a few beers.

I will have a look at your coding vlad but I am better with nested loops.

your coding did not compile ?

This is what I got:-

line 14 error: expected primary-expression before '[' token
line 14 error: expected primary-expression before ']' token
line 14 error: expected primary-expression before 'int'
line 19 error: expected primary-expression before '[' token
line 19 error: expected primary-expression before ']' token
line 14 error: expected primary-expression before 'int'

 ``123456789101112131415161718192021222324252627282930`` `````` #include using namespace std; int main() { int i; int a[5]; int b[5]; int array[10]= {1,2,3,4,5,6,7,8,9,10}; for(i=0; i<5; i++){ a[i]=array[i]; } for(i=5; i<10; i++){ b[i-5]=array[i]; } for(i=0; i<5; i++){ cout <

output:-

1 6
2 7
3 8
4 9
5 10

Thank you
good
Topic archived. No new replies allowed.