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);

}``````

## All 8 Replies

Formula is correct. It must be something wrong with your function. Post your whole code.

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

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?

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. :)

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

<<BE uniQue

>> 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.

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

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

cout<<"Sum="<<sum;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.