0

I'm trying to make a function that adds the digits of a number together and finds the sum of them.
For example, for the number 9211, I want to add 9 + 2 + 1 + 1 and output the sum.
Here's my function, I can't figure out where I am going wrong.
Could someone point out why the result isn't coming out correctly?

#include <iostream>
using namespace std;

int SumFunction (int x)
{
   int result = 0;
   result = ((x % 10) + ((x / 10) % 10) + ((x / 100) % 10) + ((x / 1000) % 10) + ((x / 10000) % 10));
   return (result);

}
7
Contributors
8
Replies
9
Views
7 Years
Discussion Span
Last Post by kri_prasad2000
0

EDIT: The program worked fine all along. I was just using incorrect input! Sorry, you can delete this thread.

Edited by Towely: n/a

0

Runs fine for me using 1235 and 3459 as input. They're sum buddies and are reported as such. What input is not working for you?

0

Oh... the problem was with my input! The program worked fine all along!
I'm so dumb. Sorry for the inconvenience.... You guys can delete this thread. :)

0

dude,
try type casting explicity over the division and mod operation.
The formulae seems to be right. Post ur complete code.

<<BE uniQue

0

>> result = ((x % 10) + ((x / 10) % 10) + ((x / 100) % 10) + ((x / 1000) % 10) + ((x / 10000) % 10));

You know your formula won't handle number above 99999, try
doing this with for loops or recursions.

0

To make the program obust you need to use looping concept .
This will provide user the freedom of entering any number

0

int x=5674876;
int sum=0;
do
{
sum += (x%10);
x /= 10;
}while(x>0);

cout<<"Sum="<<sum;

Edited by kri_prasad2000: n/a

This article has been dead for over six months. Start a new discussion instead.
Be sure to adhere to our posting rules.