122k views
5 votes
Find an example from a previous assignment where you used a loop to solve a problem. After the loop, add a call to a recursive method that will accomplish the same function. Keep the original loop also. The program should show the same results with the loop as with the recursive method. ***A suggested program to convert from a loop to a recursive method is one of the star designs at the beginning of the semester. Test it to make sure it works the same as with the loop.

1 Answer

5 votes

Answer:

C++

Loop

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

void countDownLoop(int n) {

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

int number = n;

for (int i=n; i>-1; i--) {

if (number == 0) {

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

}

cout<<number<<endl;

number--;

}

}

else

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

}

Recursion

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

void countDownRecursion(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;

}

User Evangelist
by
5.4k points