copy one array into another
Mar 11, 2011 at 3:14pm UTC
Hi,
an array like this;
int numbers[10] = {31,28,31,2,31,10,31,31,9,31,3,31};
and I would like to pair the elements of the array like the following (I mean, I would like to sum each two element);
0+1, 1+2, 2+3,....,7+8, 8+9 and would like to copy the new values into another array which will be int numbers[9].
I found something like that;
1 2 3 4 5 6 7
void reverseWord(char word [], char reverse [], int howMany)
{
for (int i = 0; i < howMany; i++)
reverse[ howMany - i ] = word[ i ];
return ;
}
but how can I sum the two elements accordingly.. ? If I write with if conditions, it looks long and not efficient. Is there any other easier way ?
Mar 11, 2011 at 3:21pm UTC
0+1, 1+2, 2+3,....,7+8, 8+9 and would like to copy the new values into another array which will be int numbers[9].
Do you mean: 31+28, 28+31, 31+2,...3+31, and copy those new values to a different array?
If yes then a simple for loop should suffice.
Last edited on Mar 11, 2011 at 3:23pm UTC
Mar 11, 2011 at 3:26pm UTC
that's right. 31+28, 28+31, 31+2,...3+31, and copy those new values to a different array.
Mar 11, 2011 at 3:30pm UTC
In pseudoish-code:
1 2
for (int i = 0; i < size_of_array-1; i++)// size_of_array-1 so that i+1 is not out of bounds.
new_array[i] = sum of array[i] and array[i+1];
Try that out.
Last edited on Mar 11, 2011 at 3:31pm UTC
Mar 11, 2011 at 3:32pm UTC
C++ STL algorithms will do that for you:
1 2 3 4 5 6
#include <algorithm>
#include <functional>
...
int numbers[12] = {31,28,31,2,31,10,31,31,9,31,3,31};
int result[11];
std::transform(numbers, numbers + 11, numbers + 1, result, std::plus<int >());
This just passes "numbers" as two ranges offset by 1, sums them, and stores the result in "result".
Mar 11, 2011 at 3:45pm UTC
This is also good to know. thanks to both of you,, below one works.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
using namespace std;
int main () {
int array[6] = {2, 6, 6, 5, 3, 7};
int newArray[5] = {0, 0, 0, 0, 0};
for (int i = 0; i < 5; i++) {// minus one so that i+1 is not out of bounds.
newArray[i] = array[i] + array[i+1];
cout << newArray[i] << endl;
}
}
Topic archived. No new replies allowed.