Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

c++ programming. Array shifter using pointers USING G++ compiler PLEASE! Write a

ID: 3822497 • Letter: C

Question

c++ programming. Array shifter using pointers

USING G++ compiler PLEASE!

Write a function that accepts an int array and the array’s size as arguments. The function should create a new array, using dynamic memory allocation, that is of the same size as the argument array. The argument array’s size is user defined in the main() function.

Now, using pointers to both the arrays, first copy the elements at odd positions (1 st , 3 rd , 5 th ), and next copy the elements at even positions (2 nd , 4 th , 6 th ) from the argument array to the dynamically allocated array. Finally, in the same function, print the contents of the argument array and the newly created array.

Explanation / Answer

#include <iostream>

using namespace std;

void copyAlternate(int *arr, int n)
{
int *copyArr = new int[n];
  
int j = 0;
for(int i = 1; i < n; i+=2)
{
*(copyArr + j) = *(arr+i);
j++;
}
  
for(int i = 0; i < n; i+=2)
{
*(copyArr + j) = *(arr+i);
j++;
}
  
cout << "Argument array: ";
for(int i = 0; i < n; i++)
{
cout << *(arr+i) << " ";
}
cout << endl;
  
cout << "Copied array: ";
for(int i = 0; i < n; i++)
{
cout << *(copyArr+i) << " ";
}
cout << endl;
}

int main()
{
cout << "Enter size of array: ";
int n;
cin >> n;
int arr[n];
for(int i = 0; i< n; i++)
{
arr[i] = i;
}
copyAlternate(arr, n);

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote