MaxX
MaxX

Reputation: 33

Recursive positive digits sum program

I'm facing an issue, the program almost works correctly except it gives +1 in output result. For example num input is 123 = 1+2+3=6, instead it gives 7 as output.

I can simply fix this problem by adding -1 in the printf statement, but I want to know why this is happening.

#include<stdio.h>
int Sumdigits(int num);

int Sumdigits(int num){
    if(num<1){
        return 1;
    }
    else return (num%10+Sumdigits(num/10));
}

int main(){
    int num;
    printf("Enter Number: ");
    scanf("%d",&num);
    printf("%d",Sumdigits(num));
}

Upvotes: 2

Views: 56

Answers (3)

Luis Colorado
Luis Colorado

Reputation: 12668

if (num < 1) is only handled when the digit is zero, but then you return 1, instead, so adding one to the result. This happens always, as this is the cut'n go back case that is executed always at the deepest recursion level.

It should read:

    if (num < 1)
        return 0;

(if you check, the only possibility for a valid number is to be zero, as it is an integer going down from a large number until you have no more digits, when you exhaust the number, it is actually zero, so it can be more readably written:

    if (num == 0)
        return 0;

meaning if we are at the end, then just add zero.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

You are adding 1 in this if statement

if(num<1){
    return 1;

The function should be declared and defined like

unsigned int Sumdigits( unsigned int num )
{
    return num == 0 ? 0 : num % 10 + Sumdigits( num / 10 );
}

If the user is allowed to deal with negative integer values then the function can be defined the following way

unsigned int Sumdigits( int num )
{
    unsigned int digit = num < 0 ? -( num % 10 ) : num % 10;

    return num == 0 ? 0 : digit + Sumdigits( num / 10 );
}

Upvotes: 1

Andreas Wenzel
Andreas Wenzel

Reputation: 24726

The problem is that Sumdigits( 0 ) will return 1 instead of 0, which does not make sense. To fix this, change

if(num<1){
    return 1;
}

to:

if(num<1){
    return 0;
}

It is also worth noting that your code will not work with negative numbers. Therefore, you may want to change the function Sumdigits to the following:

int Sumdigits( int num )
{
    if( num == 0 )
        return 0;

    if ( num < 0 )
        num = -num;

    return num % 10 + Sumdigits(num/10);
}

Upvotes: 1

Related Questions