Lizzy
Lizzy

Reputation: 21

Recursions and functions c++

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;
}

Upvotes: 1

Views: 75

Answers (4)

JinhoC
JinhoC

Reputation: 1

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)
}

Upvotes: 0

Kostas
Kostas

Reputation: 4176

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.

Upvotes: 2

A.A.
A.A.

Reputation: 1047

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);
}

Upvotes: 1

Eduard6421
Eduard6421

Reputation: 315

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 :)

Upvotes: 3

Related Questions