# reducing digits problem

• 08-17-2009
effa
reducing digits problem
hey.i'm new with C++ and trying to start with simple coding. here's the problem. there's no error in my code but keeps getting a failed result and couldnt figure out why.here's some code i made.
it suppose to give me
reduceDigits(173) == 2 where 1x7x3=21 and 2x1 =2 (giving the least output)

Code:

```unsigned int reduceDigits (unsigned int number) {         int digit = 0;         int product = 1;         if (number != 0){                        digit = number % 10;                 product *= digit;                 number = number / 10;                }         else{                 if (product > 9){                         reduceDigits (product);                 }                 else{                         cout << product;                 }         }         return number; }```
could anyone point out where i made mistake in this code?
thanks heaps.
• 08-17-2009
bithub
First of all, you need to use [code] tags when posting code.

1. reduceDigits is called with a value of 173
2. if(number != 0) is true
3. digit is set to 3.
4. product is set to 3
5. number is set to 17.
6. number (17) is returned.

That is obviously the incorrect answer. You need to write out an algorithm on paper which can give you the correct answer. Do this before you write a single line of code. Once you have the algorithm down, then you can start worrying about coding issues.
• 08-17-2009
tabstop
"else" is where you've gone wrong (the first one, not the second one). Why would you only want to do all that if number==0?
• 08-17-2009
effa
isn't the return number should keep on looping in the if statement.it's like updating the old value for number.in this case instead of taking 173 it will take 17 as the new parameter.is it?
• 08-17-2009
effa
the number is suppose to be 17,1,0..which means the testing for the product only can be done until all the single number in the parameter is been multiply.well,that was i thought it should do.
• 08-17-2009
bithub
Quote:

Originally Posted by effa
isn't the return number should keep on looping in the if statement.it's like updating the old value for number.in this case instead of taking 173 it will take 17 as the new parameter.is it?

What loop? You don't have a loop anywhere in your code. You have recursion that will never get called due to the else that tabstop pointed out. Follow the code like I pointed out in my original post, and you will see what I mean.