Reputation: 45
yes i know other ways to count digits and returning to main function from the recursion function, but i'd like to print it in the void function. im having difficulty with it. could somebody help?
#include <iostream>
using namespace std;
void recursive_function(int num)
{
int sum=0;
while(num!=0){
recursive_function(num/10);
sum++;
}
cout<<sum<<endl;
}
int main()
{
recursive_function(345289467);
return 0;
}
Upvotes: 1
Views: 545
Reputation: 11
#include <iostream>
using namespace std;
int rec_fun(int x,int c){
if(x==0 ){
if(c==x)
c=1;
return c;
}
return rec_fun(x/10,++c);
}
int main() {
cout<<rec_fun(1566,0);
return 0;
}
Upvotes: 1
Reputation: 35154
If you do not want to use the return-stack to count your digits, you will need to pass the current count throughout the call stack as function parameter:
void recursive_function(int num, int count=1)
{
if (num>=10) {
recursive_function(num/10, count+1);
} else {
cout<<count<<endl;
}
}
Upvotes: 3
Reputation: 2380
your recursive function should return integer.
#include <iostream>
using namespace std;
int recursive_function(int num)
{
if(num>9){
return 1+recursive_function(num/10);
}else
return 1;
}
int main()
{
cout << recursive_function(123456789);
return 0;
}
Upvotes: 1