Recursion.

The goal of the program that I have to create is to have the user enter a number. From there, a function will countdown from that number to 0 and then return0;

The only hint that my instructor gave us was to lookup "recursion" on the internet. I am sorta confused about that.

Also, we ARE NOT allowed to use loops.

Here's the base code, I need to edit only the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

void countDown(int x)
{

}

int main()

{

	int num;
	cout << "Enter a positive number: ";
	cin >> num;
	countDown(num);
}


Any ideas?
Any ideas?

Yup... look up recursion.
Recursion is executing a function from inside the same function. For example:

1
2
3
4
5
6
7
int factorial(int num){
	num*=num-1;
	--num;
	if(num!=1){
		factorial(num);}
	return num;}


The above code would find the factorial of "num" by calling "factorial" inside itself until the number is 1.
Last edited on
Okay, that made sense. I'm able to make my function. This might seem like a stupid question, but I can't stop my program from putting a 0 (the assignment asks to not display the zero and to just show the return 0; screen)

I tried putting in the return 0; function, but my program had an error that said void can't return anything.

Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

void countDown(int x)
{
	cout << x << " ";
	if (x > 0)
	{
		countDown(x - 1);
	}
	
}


int main()

{

	int num;
	cout << "Enter a positive number: ";
	cin >> num;
	countDown(num);
}
You just need to change "x > 0" to "x > 1" (line 8). Otherwise, when x==1, it'll recurse with x-1, which is 0.

Also, void functions aren't supposed to return anything - if you need to exit a void function, you just type "return;".
Last edited on
Gotcha! Thanks so much for the help guys :)

Last edited on
Topic archived. No new replies allowed.