Recursion problem

This is a discussion on Recursion problem within the C Programming forums, part of the General Programming Boards category; Hey guys I have a question about this function (needs to calculate the number of digits of any integer). My ...

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    5

    Recursion problem

    Hey guys I have a question about this function (needs to calculate the number of digits of any integer). My problem is- How do I return 1 in case of the number that is given is 0 since 0 is a 1 digit number?

    Code:
    int numberOfDigits(int num);
    
    int main()
    {
    	int number=1068;
    	printf ("%d\n",numberOfDigits(number));
            return 0;
    }
    
    int numberOfDigits(int num)
    {
    	if (num==0)
    	{
    		return 0;
    	}
    	return 1 + numberOfDigits(num/10);
    }
    Thanks.

  2. #2
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,424
    start your recursion one step futher
    Code:
    int numberOfDigits(int num)
    {
    	if (num> -10 && num <10)
    	{
    		return 1;
    	}
    	return 1 + numberOfDigits(num/10);
    }
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    5
    That totally works, thanks for the quick reply.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Template Recursion Pickle
    By SevenThunders in forum C++ Programming
    Replies: 20
    Last Post: 02-05-2009, 08:45 PM
  2. Problem of understanding recursion
    By ixing in forum C Programming
    Replies: 2
    Last Post: 05-02-2004, 03:52 PM
  3. half ADT (nested struct) problem...
    By CyC|OpS in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 08:37 AM
  4. recursion problem
    By ender in forum C++ Programming
    Replies: 1
    Last Post: 11-11-2001, 01:25 PM
  5. recursion problem
    By dustinc in forum C++ Programming
    Replies: 1
    Last Post: 10-29-2001, 03:29 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21