Question

When are some (relatively) basic (think first year college level CS student) instances when one would...

When are some (relatively) basic (think first year college level CS student) instances when one would use recursion instead of just a loop?

0 0
Add a comment Improve this question Transcribed image text
Answer #1

The solutions to some problems are more naturally expressed using recursion.

For example, assume that you have a tree data structure with two kinds of nodes: leaves, which store an integer value; and branches, which have a left and right subtree in their fields. Assume that the leaves are ordered, so that the lowest value is in the leftmost leaf.

Suppose the task is to print out the values of the tree in order. A recursive algorithm for doing this is quite natural:

class Node { abstract void traverse(); }
class Leaf extends Node {
int val;
void traverse() { print(val); }
}
class Branch extends Node {
Node left, right;
void traverse() { left.traverse(); right.traverse(); }
}

Writing equivalent code without recursion would be much more difficult. Try it!

More generally, recursion works well for algorithms on recursive data structures like trees, or for problems that can naturally be broken into sub-problems. Check out, for instance, divide and conquer algorithms.

If you really want to see recursion in its most natural environment, then you should look at a functional programming language like Haskell. In such a language, there is no looping construct, so everything is expressed using recursion (or higher-order functions, but that's another story, one worth knowing about too).

Note also that functional programming languages perform optimized tail recursion. This means that they do not lay down a stack frame unless they do not need to --- essentially, recursion can be converted to a loop. From a practical perspective, you can write code in a natural fashion, but get the performance of iterative code. For the record, it seems that C++ compilers also optimize tail calls, so there is no additional overhead of using recursion in C++.

Add a comment
Answer #2

I have taught C++ to undergraduates for about two years and covered recursion. From my experience, your question and feelings are very common. At an extreme, some students see recursion as difficult to understand while others want to use it for pretty much everything.

I think Dave sums it up well: use it where it is appropriate. That is, use it when it feels natural. When you face a problem where it fits nicely, you will most likely recognize it: it will seem like you cannot even come up with a iterative solution. Also, clarity is an important aspect of programming. Other people (and you also!) should be able to read and understand the code you produce. I think it is safe to say iterative loops are easier to understand at first sight than recursion.

I don't know how well you know programming or computer science in general, but I strongly feel that it does not make sense to talk about virtual functions, inheritance or about any advanced concepts here. I have often started with the classic example of computing Fibonacci numbers. It fits here nicely, since Fibonacci numbers are defined recursively. This is easy to understand and does not require anyfancy features of the language. After the students have gained some basic understanding of recursion, we have taken another look at some simple functions we have built earlier. Here's an example:

Does a string contain a character x?

This is how we did it before: iterate the string, and see if any index contains x.

bool find(const std::string& s, char x)
{
   for(int i = 0; i < s.size(); ++i)
   {
      if(s[i] == x)
         return true;
   }

   return false;
}

The question is then, can we do it recursively? Sure we can, here's one way:

bool find(const std::string& s, int idx, char x)
{
   if(idx == s.size())
      return false;

   return s[idx] == x || find(s, ++idx);
}

The next natural question is then, should we do it like this? Probably not. Why? It's harder to understand and it's harder to come up with. Hence it is more prone to error, too.

Add a comment
Know the answer?
Add Answer to:
When are some (relatively) basic (think first year college level CS student) instances when one would...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Case 1. A first-year college student is talking to a counselor in the Center for Student Services. She has been talking...

    Case 1. A first-year college student is talking to a counselor in the Center for Student Services. She has been talking about some of the difficulties of adjusting to college life. She comes from a small town and is attending a large state university. She speaks openly and seems to be in good spirits; she even smiles at times: “My new friends seem so much worldlier and confident than me. Most of them have traveled out of the country, have...

  • 1. Mark is a 22-year-old college student and is the primary caregiver for his 15-year-old brother....

    1. Mark is a 22-year-old college student and is the primary caregiver for his 15-year-old brother. Mark’s younger brother was just diagnosed with a mental illness. If you were in Mark’s place, what effect would the mental illness have on you? Think of a time when a family member was suffering from an illness or when stress was occurring in your family. What were your needs during this time? What kind of nursing support would have been helpful? 1

  • Jack is a 48-year-old consultant who earns $480; 000 per year. Hector is a 19-year-old college...

    Jack is a 48-year-old consultant who earns $480; 000 per year. Hector is a 19-year-old college student who has just nished a summer job that paid him $5; 000. Both are planning on putting some of their earnings into IRA accounts. Who should be more likely to use a Roth IRA instead of a traditional IRA? Explain.

  • Focused Throat Exam Lily is a 20-year-old student at the local community college. When some of...

    Focused Throat Exam Lily is a 20-year-old student at the local community college. When some of her friends and classmates told her about an outbreak of flu-like symptoms sweeping her campus during the past 2 weeks, Lily figured she shouldn't take her 3-day sore throat lightly. Your clinic has treated a few cases similar to Lily's. All the patients reported decreased appetite, headaches, and pain with swallowing. As Lily recounts these symptoms to you, you notice that she has a...

  • Focused Throat Exam Lily is a 20-year-old student at the local community college. When some of...

    Focused Throat Exam Lily is a 20-year-old student at the local community college. When some of her friends and classmates told her about an outbreak of flu-like symptoms sweeping her campus during the past 2 weeks, Lily figured she shouldn't take her 3-day sore throat lightly. Your clinic has treated a few cases similar to Lily's. All the patients reported decreased appetite, headaches, and pain with swallowing. As Lily recounts these symptoms to you, you notice that she has a...

  • 1. Sally is first year student at a local community college. She is a 19 year-old...

    1. Sally is first year student at a local community college. She is a 19 year-old woman, stands 5 foot 4 inches tall and weighs about 128 pounds. Sally is in reasonable health. Sally enjoys going out with her friends to the local pizza place. She eats whatever they order even if she is not very hungry. Which of the following is most likely determining Sally's food choices and food acceptance when she is out with her friends? a cost...

  • III. We achieve the first level of happiness when we are able to provide the basic...

    III. We achieve the first level of happiness when we are able to provide the basic necessities of life to our families. People who don't have to worry about where the next meal is coming from and have a shelter over their heads are blessed indeed. The next level of needs naturally are higher and man starts aspiring for a worthy job, good health, property and myriad other luxuries. People being human need to be rewarded and encouraged for their...

  • Claire is a healthy 19 year-old college freshman enjoying her first few weeks of being on...

    Claire is a healthy 19 year-old college freshman enjoying her first few weeks of being on a college campus. She’s made lots of new friends, has been participating in many of the on-campus outdoor social activities, and is getting used to a hectic class schedule. For the last couple of days, she’s been feeling more tired than usual, and she’s had a sore throat. Her sore throat has been worsening, and she also has a low-grade fever and a headache...

  • You had your first child recently. You would like to set aside some funds so that...

    You had your first child recently. You would like to set aside some funds so that your child will be able to attend the University of Texas as an undergraduate without taking on any student loans. Total costs of attendance for undergraduate students currently amount to $28,000 per year and are expected to continue to grow at a 2.5% growth rate per year. Assume that the four-year college expenses for the first year of college need to be paid exactly...

  • Case 2. A 20-year-old Asian American male college student who has volunteered to work with struggling...

    Case 2. A 20-year-old Asian American male college student who has volunteered to work with struggling high school students finds that he is learning more than he imagined he would. He tells his college advisor what it’s like: “These kids deal with problems I have never had to face. Some days we’ll start by working on some bit of homework but before we’re done they’re talking about being afraid of the gangs on the way to and from school. This...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT