recursion advice

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <iomanip>

using namespace 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);
	}
}


Why does fillArray have a hard coded 10 in that loop? It should use the parameter.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

void fillArray(int* p_arr, int numOfElements);

int main()
{
	const int 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.:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

void recurArray(int* begin, int* end);

int main()
{
	const int numOfElements = 10;
	int arr[numOfElements];
	// ... initialise array

	recurArray(arr, arr + numOfElements);
}

void recurArray(int* begin, int* end)
{
	if (begin < end)
	{
		recurArray(begin, --end);
		cout << *end << endl;
	}
}
Last edited on
Topic archived. No new replies allowed.