For example, I have an array: int arr1[10] = {1,2,3,4,5,6,7,8,9,10}. I want to transfer all values in the odd position to another array: int arr2[5] = {1,3,5,7,8}.
-
1In what part of your code are you stuck?ignacio– ignacio2019-10-21 03:25:21 +00:00Commented Oct 21, 2019 at 3:25
-
I really don't have any idea on how to startuser12102737– user121027372019-10-21 03:26:15 +00:00Commented Oct 21, 2019 at 3:26
-
try this code as a starting pointignacio– ignacio2019-10-21 03:32:22 +00:00Commented Oct 21, 2019 at 3:32
-
Consider changing the arr2[5]={1,3,5,7,8} to arr2[5]={1,3,5,7,9}Jennis Vaishnav– Jennis Vaishnav2019-10-21 03:41:34 +00:00Commented Oct 21, 2019 at 3:41
Add a comment
|
2 Answers
Here is quick fix for you. Check following code.
int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int newArray[5] = {0, 0, 0, 0, 0};
int j = 0;
for (int i = 0; i < 10; i+=2) {
newArray[j] = array[i];
cout << newArray[i] << endl;
j++;
}
Hope this solution works.
1 Comment
user12102737
Thank youuuuuuuuuuuuu!!
First, you'll have to allocate the appropriate amount of memory to the second array. Then, a simple for loop should do the job.
// This loops over all odd positions in arr1.
for (int i = 1; i < 10; i += 2)
{
arr2[i/2] = arr1[i];
}
But I believe you want to handle this for arbitrary size. Try to come up with the correct allocations to the new array. If you're stuck, let me know.
But try to include what you've already tried.