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 Sumdigits(num/10));
}
int main(){
int num;
printf("Enter Number: ");
scanf("%d",&num);
printf("%d",Sumdigits(num));
}
CodePudding user response:
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);
}
CodePudding user response:
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 );
}