Lmgerbasi
Lmgerbasi

Reputation: 13

Keep getting the same answer when writing a recursive function

Note: I'm fairly new to C programming so I don't know everything just yet.

So I'm working on this assignment for my programming class where I have to write a recursive function count_digits( ) that counts all the digits in a string. I wrote the program and got it to compile but when I type in a number, it always gives me the same answer.

This is what my code is:

#include <stdio.h>
int count_digits(int num)
{
    static int count=0;
    if(num>0)
    {
        count++;
        count_digits(num/10);
    }
    else
    {
        return count;
    }
}

int main()
{
    int number;
    int count=0;

    printf("Enter any number:");
    scanf("%d",&number);

    count=count_digits(number);
    printf("\nTotal digits in [%d] are: %d\n",number,count);

    return 0;
}

Upvotes: 0

Views: 44

Answers (2)

irqmask
irqmask

Reputation: 26

there are a few things to consider: What happens if you call your function count_digit() more than one time in the program? What if you enter 0, 10, 100 as number?

Perhaps you should rethink using a static variable here. Also for debugging, insert some printfs (or use the debugger) in count_digit() to check how your function behaves.

Upvotes: 1

3CxEZiVlQ
3CxEZiVlQ

Reputation: 39086

Your non void function returns nothing if num is greater than zero. The compiler should warn you about not returning value. The fix:

return count_digits(num/10);

Upvotes: 3

Related Questions