Hello, this was my problem to figure out... write a function that takes an array
and displays the elements in the array in reverse using recursion and not a loop. basiclly, i just want to know if i went about this the correct way, and if not please provide any advice ill gladly take it. thank you
#include <iostream>
#include <iomanip>
usingnamespace std;
void fillArray(int*, int&);
void recurArray(int*);
int main()
{
int numOfElements = 0;
int arr[10];
int* p_arr = arr;
fillArray(p_arr, numOfElements);
recurArray(p_arr);
cout << "\n\n";
system("PAUSE");
return 0;
}
void fillArray(int* p_arr, int& numOfElements)
{
for (int i = 0; i < 10; i++)
{
numOfElements++;
p_arr[i] = numOfElements;
}
}
void recurArray(int* p_arr)
{
if (*p_arr >= 1)
{
recurArray(p_arr + 1);
cout << *p_arr << endl;
// if you are to take away the proceeding comment and execute the line of code
// it will print the array forward from 1 - 10
//recurArray(p_arr + 1);
}
}
#include <iostream>
usingnamespace std;
void fillArray(int* p_arr, int numOfElements);
int main()
{
constint numOfElements = 10;
int arr[numOfElements];
fillArray(p_arr, numOfElements);
// ...
}
void fillArray(int* p_arr, int numOfElements)
{
for (int i = 0; i < numOfElements; ++i)
{
p_arr[i] = i;
}
}
Your idea for recursion is correct, but the test is wrong. p_arr will not be zero or negative for a very long time. Try this. Pass in both ends of the array and decrement the end each time.: