Recursion- counting numbers- homework

hi guys!
its supposed to do this:
4. Recursion. Write a recursive function called digits that will return the number of digits in its parameter of type long. Your function should work for arguments that are negative or zero as well as positive.

but only returns 0!
i have no clue why its doing this.

 ``1234567891011121314151617181920212223242526272829303132`` `````` #include using namespace std; long digits (long); int main(){ long number, count; cout << "Enter an integer number (negative or zero is ok): "; cin >> number; count = digits (number); cout << "The number of digits in number "< 0){ count+=1; digits(number/10); } else { return count; } } }``````
You need to think about the logic.
What will happen when number is -10 or 0 ?
What value will be returned ?
Maybe do this first with pen and paper.
the problem is each time digits gets called it sets count to a garbage value in most cases it seems to be 0,but you should always initialise variables,the logic is correct apart from entering 0 or a minus number then the if statement will never execute and the function will just return so changed it to enter a number greater than 0

what you want to do is put count outside the digits function so it won't be re-initialised each time the function is called

this should work

 ``12345678910111213141516171819202122232425262728293031`` `````` #include using namespace std; int digits (int); int main(){ int number, coun; // changed count to coun probably better to pick a more suitable name but just named it that for demonstration cout << "Enter an integer number (negative or zero is ok): "; cin >> number; coun = digits(number); cout << "The number of digits in number "< 0){ count++; digits(number/10); } return count; } ``````

but to be honest you have the right idea
Last edited on
Topic archived. No new replies allowed.