It is necessary to output the elements of the array in reverse order, while passing the last index of the array to the function. What am I doing wrong? Here is my code:

#include <iostream> using namespace std; int Rev(int array[], int len) { if (len < 0) { return 0; } else { array[len]; Rev(array, len-1); cout << array[len] << "\n"; } } int main() { int arr[6] = {42, 23, 16, 15, 8, 4}; // вызов функции Rev(arr, 5); return 0; } 

At the exit, I get

 42 23 16 15 8 4 

those. in the same order in which the elements of the array were specified, and I need to output them in reverse order.

  • I corrected, there should be 5 - RedScreed

2 answers 2

Why recursion? Why not so:

 void Rev(int array[], int len) { for(int i = len; i >= 0; --i) cout << array[i] << "\n"; } int main() { int arr[6] = {42, 23, 16, 15, 8, 4}; Rev(arr, 5); } 

And you, if you want recursively - swap lines

 Rev(array, len-1); cout << array[len] << "\n"; 
  • Thank. I try to thoroughly understand the recursive functions, while with varying success. - RedScreed
  • one
    Well, look - you need to display the last element first, and then the rest recursively. You deduce the rest, and then the last one. And so on each level of recursion - as a result, the usual order is obtained. - Harry

in order to change the order you should have already answered to display after a recursive call -

as an alternative, you can use the excellent property of static variables that retain their old values ​​between calls (and at the same time learn this)

  void Rev(int array[], int len) { static int i = 0; if (i < len) { cout << array[len-i-1] << ' '; ++i; Rev(array, len); } } 
  • one
    And the next time you call for another array, won't the value stored in i interfere? - Mikhailo
  • @Mikhailo yes you are right - for the next array nothing will be output since the variable i will be set to len - ampawd