3

I had an exam today and there was a question which I don't really remember the exact code.

But what I do remember that inside the method exampleMethod(int num) there was a line calling the method itself inside the method.

I want to know can a method be called inside it self? because it was a multiple choice question and they wanted from us to find the output.

I hope my question is clear.

Thanks SOF :)

1
  • 3
    Why don't you write a small program to try it out yourself? Experimenting is the best way to learn. Commented Jun 12, 2011 at 15:52

2 Answers 2

15

Sure it can. When you do that it's called recursion. Be careful that you have an exit condition or you will get a stack overflow.

for example

int iAmRecursive(int num) { if (num > 10) // break out at some condition; i.e. don't recurse return num; // return so the recursion doesn't continue iAmRecursive(num + 1); // I didn't break out, so continue to recurse. } 

EDIT -- here is the same example but with a different break-out, to compliment @Ted's comment

int iAmRecursive(int num) { if (num <= 10) // only continue under certain condition iAmRecursive(num + 1); // When I get here, I implicitly break out by not recursing. } 

however I prefer to always be as explicit as possible, so I would explicitly break out as in the first example, if possible.

Sign up to request clarification or add additional context in comments.

7 Comments

Hmm... There was no exit condition inside the code. I'm trying so hard to remember the question :S
+1 for using "stack overflow" (as well as for a correct answer).
@ted, yeah, i couldn't resist ;)
@Mohammad - an "exit condition" is any test in the body of the method that would prevent the recursive call if the condition were met. For instance: int factorial(n) { return n < 2 ? 1 : n * factorial(n-1); }
Oh boy! I got this question wrong! how come I've never read it in my book
|
2

A nice example of recursion is a method to compute a factorial.

public static long factorial(int i) { if (i == 1) return 1; return factorial(i - 1) * i; } 

Then invoke it simply like this:

long f = factorial(10); // equals 10! = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 (* 1) 

2 Comments

"faculty"? Most people know this as "factorial".
Oops. Sorry, I'm dutch. It "faculty" sounds good to me. Thanks for noticing it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.