java - Recursive function with local variable not executing if statement -


public int count7(int n)  {     int count = 0;     if (n%10 == 7) count= 1;     if(n%10 != 7) count= 0;      if (n < 10 && n==7) return 1;     if (n < 10 && n!=7) return 0;     else return count7(n/10) + count; } 

i have above function recursively adds occurrences of 7 in given number. each time divides number 10 reduce 1 number , checks if last digit equals 7.

when run count7(7), returns 1. have question regarding why never hits first if statement (if n%10 == 7) count = 1;

if program written as:

public int count7(int n)  {     int count = 0;     if (n%10 == 7) count= 0;     if(n%10 != 7) count= 0;      if (n < 10 && n==7) return 1;     if (n < 10 && n!=7) return 0;     else return count7(n/10) + count; } 

the call count7(7) still work. question recursive calls placed on stack, why last call not assign count 1 , instead assign 0?

eg:

count7(717)

count7(7) + count <-------this hits base case since n < 10 count(71) + count count(717) + count 

count assigned 1 whenever n % 10 == 7. base case returns 1. please explain 1 case thing not able understand properly.

you have 3 return statements in play

if (n < 10 && n==7) return 1; if (n < 10 && n!=7) return 0; else return count7(n/10) + count; 

only third 1 (the recursive case) uses count variable @ all. when count7(7), triggers base case immediately, returning 1 without ever caring count equal to, because first return statement used instead of third, imagine you're expecting.


Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -