Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider this recursive function: public static void print(int n) { if (n >= 10)

ID: 3752911 • Letter: C

Question

Consider this recursive function:

public static void print(int n)

{

if (n >= 10)                  

print( n / 10);

printDigit( n % 10);

}

The above function flows as such....

print(6371);

    print(637)

         print(63)

              print(6) // I understand till this point**

              printDigit(6%10); // From here on out,dont understand how the program even gets to the call printDigit();

         printDigit(63%10);

    printDigit(637%10);

printDigit(6371%10);

so to the screen, it prints: 6371, 637, 63, 6 ,6, 3, 7, 1

My question is.... how exactly does it print that flow. I understand that print(n/10) reduces the problem every time till it reaches the base case but once the base case is reached (n not greater than or equal to 10) how is it that the call to printDigit(n%10) continues to loop. I know that the implementation of printDIgit() is not written but it is irrelavent in this situation.

Explanation / Answer

if you see the function void print() has

2 statements

S1: if(n>=10) print(n%10)

s2: printDigit(n%10)

in order to complete the function print() we need to execute these 2 statements

printf(6371) S1 executed S2 pending here n=6371

print(637) S1 executed S2 pending here n=637

print(63) S1 executed S2 pending here n=63

print(6) S1 executed S2 executed ad prints 6, now we fully completed this function call but we have some pending function call so it will than

printDigit(63%10)

printDigit(637%10)

etc

In the recursion it will maintain the stack for the function calls