0

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}.

4
  • 1
    In what part of your code are you stuck? Commented Oct 21, 2019 at 3:25
  • I really don't have any idea on how to start Commented Oct 21, 2019 at 3:26
  • try this code as a starting point Commented Oct 21, 2019 at 3:32
  • Consider changing the arr2[5]={1,3,5,7,8} to arr2[5]={1,3,5,7,9} Commented Oct 21, 2019 at 3:41

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank youuuuuuuuuuuuu!!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.