-1

does this count as a recursive function...if no, then what is the reason. Which changes would classify it as such...thanks

public class Recursion {

public static void recursionFunc(int beginning_value){
    if (beginning_value != 0){
        System.out.println(beginning_value);
        recursionFunc(beginning_value - 1);

    }
}
public static void main(String[] args){
    recursionFunc(10);
}
}
gparyani
  • 1,958
  • 3
  • 26
  • 39
dido
  • 3,347
  • 11
  • 34
  • 42
  • 3
    If it's calling itself, it is recursive. Just try not to recur forever. – Sotirios Delimanolis Aug 23 '13 at 18:43
  • 1
    Why wouldn't it be? Isn't this a standard example of recursion? – Jeroen Vannevel Aug 23 '13 at 18:43
  • 3
    Also, the definition of recursion applies to all languages - not just Java. – sdasdadas Aug 23 '13 at 18:43
  • 10
    See: http://stackoverflow.com/questions/18409742/what-classifies-as-a-recursive-function-in-java – Kon Aug 23 '13 at 18:44
  • 4
    @Kon That should be an answer. – Sotirios Delimanolis Aug 23 '13 at 18:46
  • 2
    @Kon Let's see what happens if I try to flag this question as a duplicate of itself...(it doesn't work) – gparyani Aug 23 '13 at 18:46
  • @SotiriosDelimanolis `Exception in thread "main" java.lang.StackOverflowError` It's an `Error`, so it was internal, but it seems to be caused by my code... – gparyani Aug 23 '13 at 18:50
  • The only requirement for a function to be recursive is that it either calls itself directly or indirectly. Your code does that so it is recursive. Java does not tail call optimize (TCO) so even for medium deep recursions you might need to [increase stack size](http://stackoverflow.com/questions/3700459/how-to-increase-to-java-stack-size) or rewrite to a loop construct not to get Stack Overflow. – Sylwester Aug 24 '13 at 00:02

2 Answers2

4

A function that calls itself, directly or indirectly, is called recursive. Your function calls itself, so it is definitely recursive.

Here is an example of recursive functions that calls themselves indirectly:

static void funcA(int x) {
    if (x <= 0) return;
    if (x % 2 == 0) {
        funcB(x-1);
    } else {
        funcC(x-1);
    }
}
static void funcB(int x) {
    funcA(x-1);
}
static void funcC(int x) {
    funcA(x-2);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Your method is a recursive method. A method is considered to be recursive when it calls itself again. All recursion methods should some sort of exit built into it, otherwise the method will yield an Stackoverflow error.

Here is a recursive method that does not have a exit built into it:

static void callAgain() {
callAgain();
}

Here's more details on recursive methods: http://danzig.jct.ac.il/java_class/recursion.html

Luke Taylor
  • 9,481
  • 13
  • 41
  • 73