0

I want to separate each digit of a number by a recursive function. I am trying the following function:

private static void print( int n ){
    print( n/10, n%10 );
}

private static int print( int n, int ld ){
    if( n < 10 ) return n;
    int digit = n % 10;
    int first = print( n/10, ld );
    System.out.println( digit );
    return first;
}

But it does not work. Can anyone help me how can I change the above function to achieve my outcome ?

input : 12345 output: 1 2 3 4 5

I want to do this by a recursive function

1
  • please extend your question with a clear example of input and expected output! Commented Dec 11, 2019 at 9:53

2 Answers 2

1

This will print digits in correct order.

    private static void print( int n ){

        int t = (int)Math.floor(n / 10);

        if (t > 0) {
            print(t);
            System.out.println( n % (t * 10) ); 
        }
        else 
            System.out.println( n );
    }
Sign up to request clarification or add additional context in comments.

Comments

0

There is no need for creating two functions From the first function result, you are not using where you have made a call for print(arg, arg)

just add terminate condition when the result gets 0

private static void print( int n ){
        if (n == 0)  return;

        int digit = n%10;
        System.out.println(digit);

        print( n/10  );
    }

2 Comments

I do not want to print each digit of number in reverse
Then what is your expected result? you haven't mentioned that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.