1

i am doing one of the simple programin C, sum of digits of 5 digit number.Though i had done it using a simple function but i need to do it with recursion also.I had read many solution on net regarding this problem using recursion and had implemented one of mine.But that is giving error and i cant figure out what mesh i am doing in my algo.

#include<stdio.h>
int sum5(int x);  //function for sum of  digits of 5 digit number

int main()
{
   int x;
   int result;
   printf("Enter a 5 digit number : ");
   scanf("%d",&x);
   printf("Number entered by you is %d",x);
   result = sum5(x);
   printf("Sum of digits of 5 digit number is = %d",&result);
   return 0;
}

int sum5(int x)
{
   int r;
   int sum=0;
   if(x!=0){
      r=x%10;
      sum=sum+r;
      x=x-r;      //doing this so that 0 come in the last and on diving it by 10, one digit will be removed.
      sum5(x/10);
   }
   return sum;
}

but after its execution i am getting wrong result.It is dumping some anonymous value on the output.

1
  • 1
    this part is useless x=x-r; as what youre sending afterwards will anyway remove the right-most digit. it wont work as no one gets the return value from the recursion call. Commented May 9, 2013 at 12:14

2 Answers 2

8

Also, your sum5 function is incorrect. You have to add the value of sum5 to the sum variable of the caller function.

int sum5(int x)
    {
        int r;
        int sum = 0;
        if (x != 0) {
            r = x % 10;
            sum = r;
            //x = x - r;  - this isn't required. integer division will floor x
            sum += sum5(x / 10);
        }
        return sum;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

@0A0D: i had tried it with my code, basically with &result error i wasnt adding the result of recursion.But now its working fine
8

This is incorrect as it is printing the address of result and not its value:

printf("Sum of digits of 5 digit number is = %d",&result);

Change to:

printf("Sum of digits of 5 digit number is = %d", result);

Always check the result of scanf() to ensure a valid value was read:

/* Returns number of assignments made. */
if (scanf("%d", &x) == 1 && x > 9999 && x < 100000)
{
}

Plus the error in the implementation of sum5() as pointed out by Osiris .

1 Comment

Yes that &result was a silly mistake though.And that if(scanf("%d",&x)==1){} this found to be very useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.