1

I have the following program

public static int doSomething(int num){
    if(Math.abs(num) > 9){
        return (1 + doSomething( num / 10));
    }
    else{
        return 1;
    }
}
public static void main(String[] args){
    System.out.println(doSomething(333));
}

This is how I understand it. If the number is 333. 333 / 10 gives me 33. Since 33 > 9 it runs the recursive loop again giving me 3. After 3 it enters the else condition.

I don't understand why it prints 3 as answer.

I am new to java so still trying to understand the basics.

I don't believe the question is a duplicate. My question is much simpler being a beginner to java. Also the question I believe is using javascript not java.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
Jeff Benister
  • 468
  • 3
  • 12
  • It would help me to know why I was downvoted. – Jeff Benister Aug 06 '15 at 17:37
  • Not your downvoter, but what do you expect? – Fred Larson Aug 06 '15 at 17:38
  • 1
    _gives me `33 + 1 = 34`_ Where does the 33 come from? It gives you `1 + doSomething(33)`. – Sotirios Delimanolis Aug 06 '15 at 17:39
  • @SotiriosDelimanolis. Still new to java specially recursion. Thank you for pointing out the mistake – Jeff Benister Aug 06 '15 at 17:41
  • 1
    @JeffBenister language doesn't really matter for recursion. Also the duplicate closure is simply that people having the same problem and finding it get redirected to the question with the canonical/best answers that were established already instead of having the same answers with differing quality duplicated over multiple questions, it has no disadvantages for you. Even though I find [Understanding recursion](http://stackoverflow.com/q/717725) to have the best explanations of recursion in my opinion. – AliciaBytes Aug 06 '15 at 18:03

2 Answers2

5

Look, what will return doSomething() if Math.abs(num) < 9? 1? yes you are right. Ok lets start.

doSomething(333) => 1 + doSomething(33) // 33 not less than 9
                 => 1 + (1 + doSomething(3)) // now 3 is less than 9
                 => 1 + (1 + {1})
                 => 3
mazhar islam
  • 5,561
  • 3
  • 20
  • 41
2

The recursion is not on 1 + 33, but on 33 only, so it's:

doSomething(333)
= 1 + doSomething(33)
= 1 + 1 + doSomething(3)
= 1 + 1 + 1
= 3
Jan
  • 2,060
  • 2
  • 29
  • 34