1

I have made a function and I am trying to make it recursive. Does anyone have any tips on how I can make this function recursive? I know recursive means to use the function in the function itself.

int countEven(int n){
    int evens = 0;
    if(n <= 0) return 0; //base case
    while(n > 0){
        int digit = n%10; //get the last digit
        if(digit%2 == 0){
            evens = evens + 1;
        }
        n = n/10;
    }
    cout << evens;
}
Alaleh
  • 1,008
  • 15
  • 27
Lizzy
  • 21
  • 2

4 Answers4

3
int rec(int n)
{ 
  int sum = 0;
  if(n<=0)
    return 0;
  else if ((n%10)%2==0)
    sum = rec(n/10)+1;
  else
    sum = rec(n/10);

  return sum;
}

Maybe something like this :)

Richard
  • 56,349
  • 34
  • 180
  • 251
Eduard6421
  • 295
  • 1
  • 11
  • Thank you so much! Can I just ask why you add +1 in the else if statement? – Lizzy May 01 '18 at 17:13
  • @Lizzy Because that particular case is even and needs to be counted. – user4581301 May 01 '18 at 17:15
  • Sure! The value 1 is added everytime and even element is found. Example : 124 ; 1) n = 124; 124%10%2==0; I add 1 because i found an even number; 2) n = 12; 12%10%2 == 0 ; I add 1 because i found another even number; 3) n = 1: 1%10%2 == 1; I do not add anymore as the number is odd. – Eduard6421 May 01 '18 at 17:15
  • @Eduard6421 thank you so much for the explanation. I understand now! :) – Lizzy May 01 '18 at 17:19
2

For counting the even digits of an integer base 10 you can simplify the function to the following

int countEven(int n)
{
    if (n != 0) return !(n % 2) + countEven(n/10);
    else        return 0;
}

This expands as follows. Assume n = 258:

            countEven(258) = 
1 +         countEven(25)  = 
1 + 0 +     countEven(2)   = 
1 + 0 + 1 + countEven(0)   = 2

Note that the statement !(n % 2) returns 1 if n is even and 0 if it's odd.

For shorter you can do the following:

int ce(int n) { return n ? !(n&1) + ce(n/10) : 0; }

using the ternary operator.

Kostas
  • 4,061
  • 1
  • 14
  • 32
1

seems like you're trying to count the even digits in a number

int countEven(int n){
    if(n == 0) 
        return 0; //base case
    if (n<10)
        return !(n%2);
    return !(n%2)+countEven(n/10);
}
Alaleh
  • 1,008
  • 15
  • 27
0

looks like a similar question i received from QC.

to make it recursive, you must have the function calling onto itself. Ask how you can make the the input simpler and have some sort of base so that the function doesn't break.

int countEven(int number) {
    if (x <= 0) return 0;
    if (x % 2 == 0) {
       return countEven(number / 10) + 1; 
    }
    return countEven(number / 10)
}
JinhoC
  • 1