O
O
OccamaRazor2017-09-11 18:14:48
C++ / C#
OccamaRazor, 2017-09-11 18:14:48

How to reverse the order of a number in an array?

Is it possible to change the order of numbers in an array using recursion without using libraries, built-in functions using only pointers?

#include <iostream>

using namespace std;
void copy(int old_array[], int new_array[], int len);
int reverse(int *pB, int len, int i);

int main() {
  const int len = 5;
  int A[len] = { 1,2,3,4,5 };
  int B[len];
  int *pA = A;
  int *pB = B;
  copy(pA, pB, len);
  reverse(pB, len, 0);
}

void copy(int A[], int B[], int len) {
  for (int i = 0; i < len; ++i) 
    *B++ = *A++;
}

int reverse(int *pB, int len, int i)
{
  int x = pB[i];
  if (i < len - 1) reverse(pB, len, i + 1);
  cout << x << endl;
  return 0;
}

After performing reverse, the array B remains as before 1,2,3,4,5 as well as A 1,2,3,4,5

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
devalone, 2017-09-11
@OccamaRazor

For example like this:

#include <iostream>

void printArray(const int * array, size_t len)
{
  std::cout << "[ ";
  for(size_t i = 0; i < len; ++i)
    std::cout << array[i] << (i == len - 1 ? "" : ", ");
  std::cout << " ]" << std::endl;
}
void _reverseArray(int * first, int *last)
{
  int tmp = *first;
  *first = *last;
  *last = tmp;
  if(first < last)
    _reverseArray(first + 1, last - 1);
}
void reverseArray(int * ptr, size_t len)
{
  _reverseArray(ptr, ptr + len - 1);
}
int main() {
  int array[] = { 1, 2, 3, 4, 5, 6 };
  size_t len = sizeof(array) / sizeof(int);
  printArray(array, len);
  reverseArray(array, len);
  printArray(array, len);
  return 0;
}

G
GavriKos, 2017-09-11
@GavriKos

So, in reverse, the array B is not modified.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question