Can’t print last digit of a number while displaying all digits of a number using recursion?



I was trying to print digits of a number using recursion. The function I defined returns all the digits but I fail to print the last digit. Can any one point out what’s wrong in the code? Is there any other logic which is better than this with recursion?

 public static int printIndividualDigits(int num){
        if((num/10) != 0){
           System.out.print(printIndividualDigits(num/10)+ ",");
        }
         if(num != 0){
           return num%10;
        }else{
             return 0;
         }
    }

Answer

That’s because you return the last character, but you print all the others.

In your recursive calls, you don’t append the reminder to some globally available variable (which would be preferable way in your example), hence you don’t build the answer to be printed; rather you just print the remainders, per each recursive call, and then (important) return either num%10 or 0.

So, your first stack frame (which is initial method call, first entrance into the recursive method) returns, instead of printing.

For instance, if you will take number 3435, your last recursive call ends up to be:

System.out.print(printIndividualDigits(34/10)+ ",");

which enters printIndividualDigits with argument 3 passed into “num” parameter, and then method prints 3%10 => 3.

Now, when your recursive calls pop off the stack frame – that is your recursion goes back to the first recursive frame (that is a first recursive call), variable num is 3435, *there is no more recursive calls, and code execution passes System.out#print method call, to the if checks, after which, it returns either 0, or the latest reminder, instead of printing it.

So, in the first stack frame, your return 3435%10, which is 5, gets just returned and not printed.



Source: stackoverflow