1.

Solve : Counting even digits in C++?

Answer»

So I have this project where I'm supposed to count the number of even digits a user inputs using recursive functions, however I don't know what's wrong with my code right now. The function keeps returning 3 digits when you input 2 even digits, and returning 7 when you input 3 even digits. A perfect user is assumed, so there is no need for strings and ARRAYS.


Current code:
Code: [Select]#include <iostream>


using namespace std;

int count = 0;
int number;
int digit;

int evens(int number);

int main(){
cout << "Input number: ";
cin >> number;
cout << evens(number);
return 0;
}


int evens(int number){
digit = number%10; //get last digit
if (number == 0){ //check if end of number and return count
return count;
}
if (digit%2 == 0){ //check if DIVISIBLE by 2
count = count ++; //add to count
evens(number/10); //cut off last digit and repeat
}

evens(number/10);

}how about:

Code: [Select]int evens(int number){

if (number == 0)
return 0; //check if end of number and return count
digit = number%10; //get last digit

if (digit%2 == 0){ //check if divisible by 2
return(1+evens(number/10));
else
return evens(number/10);

}


OVERLOOKING the fact that recursion is a "technique" best avoided (especially for something where an obvious iterative solution is possible) using a Module level variable to determine the results from a recursive function is a bit silly.

Basically, what should happen is-

chop of ones digit.

If even, return 1 added to the even digit count of the number without the ones digit.

otherwise, just return the even digit count of the number w/o the ones digit. (without adding one)

Since this is merely a education exercise, I see no harm in the large number of unnecessary temporary variables.


Also: I MIGHT add that the original cause of your problem was that for even numbers you recursed twice:

as the last line of the function, you have:
Code: [Select]evens(number/10);

which will be executed regardless, even if you had already run it when the if test was true. you might be able to get your version working by placing that particular portion in an else clause. However try running it twice in one program and you'll see a good reason not to use module level variables...

Thanks a lot, I would have use iterations but we had to use recursive functions. I need to go study that chapter again, STILL some things I'm fuzzy on, like EXACTLY how recursive functions (ie this function), would run step by step. :x
Thanks for your help!



Discussion

No Comment Found