Thread: Recursion problem

  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
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    start your recursion one step futher
    Code:
    int numberOfDigits(int num)
    {
    	if (num> -10 && num <10)
    	{
    		return 1;
    	}
    	return 1 + numberOfDigits(num/10);
    }
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  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, 09: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, 02:25 PM
  5. recursion problem
    By dustinc in forum C++ Programming
    Replies: 1
    Last Post: 10-29-2001, 04:29 AM