Can someone show me how to write a recursive function that count how many time the number 7 occur in an integer. Thanks
Can someone show me how to write a recursive function that count how many time the number 7 occur in an integer. Thanks
Yes I can. But instead of giving you the answer. I am going to help and guide you through this long and tough journey to find the number of magical sevens in a given integer.
So to start, do you have any ideas? Does not have to be in code, just basic ideas?
I tried to get the last digit my using %, and then remove it with /
but i think my if statement is wrong, as well as setting up that base case.
int count7(int n)
{
if(n % 10 != 7) return 0;
if(n == 7 || n % 10 == 7) return 1 + count7(n/10);
}
Your attempt is close. You need to change line 3. Also line 4 can be reduced to simply if(n % 10 == 7) return 1 + count7(n/10)
Line 3 is going to be your base case. When should you stop in ALL cases? For example in you base case if n = 71, then (71 % 10 != 7) == true, hence your function stops and returns 0.
Base cases is a case where the input n is the minimal number possible for the recursion to work. So what range of value passed in should the function automatically just stop?
it seems like my code stop working whenever the next number is not 7...
I am thinking that the if statement should stop when I get to the last number and it is not equal to 7
but I am failing to make it work.
i tried if(n/10 == 0 && n != 7) return 0;
Not quite, you need to check if n < 7, if so then stop and return 0 else you should check each digit for a seven.
i tried that also, but it failed even more
int count7(int n)
{
if(n < 7) return 0;
if (n % 10 == 7) return 1 + count7(n/10);
}
Yes, your not quite done yet. Your line 4 is not quite yet correct. Here is what you have to do:
check if the last digit is a 7, if so then return 1 + count(n/10) if not then return 0 + count(n/10)