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.
#include <iostream>
usingnamespace 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 "<<number<<" is " << count;
return 0;
}
long digits (long number){
int count;
if (number > 0){
count+=1;
digits(number/10);
}
else {
return count;
}
}
}
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
#include <iostream>
usingnamespace 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 "<<number<<" is " << coun;
return 0;
}
int count = 0;
int digits(int number){
if (number > 0){
count++;
digits(number/10);
}
return count;
}