Maisha
Maisha

Reputation: 45

how can i count digits of a number using recursion?

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

Answers (3)

youssef oraby
youssef oraby

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

Stephan Lechner
Stephan Lechner

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

nayab
nayab

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

Related Questions