54.0k views
0 votes
Implement a program that uses a recursive function to count from N (provided by the user in main, <= 100) down to 1 and instead of displaying 0 it will display the message: I’ve learned how to use recursion! All output comes from the recursive function. The recursive function validates the number range, not main. Add a row to the bottom of your test plan and explain what are the two things one must identify in order to write a recursive function.

User DrakaSAN
by
7.2k points

1 Answer

5 votes

Answer:

C++.

Step-by-step explanation:

#include <iostream>

using namespace std;

//////////////////////////////////////////////////////////////

void countDown(int N) {

if ((N > -1) && (N <= 100)) {

if (N == 0) {

cout<<"I've learned how to use recursion!";

}

else {

cout<<N<<endl;

countDown(N-1);

}

}

else

cout<<"Invalid Range."<<endl;

}

//////////////////////////////////////////////////////////////

int main() {

int N;

////////////////////////////////

cout<<"Enter number: ";

cin>>N;

countDown(N);

////////////////////////////////

return 0;

}

////////////////////////////////////////////////////////////////////////////////////////////

Any Recursive function has two main things.

First is the break condition or base case, without it, the function would never stop calling itself and go into infinite loop.

In the above example, the base case was "N == 0".

Second, and the more difficult thing, is to write a proper recurring statement. This part is basically what recursion is all about, i.e. solve problems by breaking them down into smaller problems and then combining the result.

In the above example, this was "countDown(N-1)".

User DDomen
by
6.3k points