sum function

Write a function that accepts an integer value (non-negative) and returns the sum of the digits of the number
exmple: 1023= 1+0+2+3=6

i dont have idea how i doing this function

#include <iostream>
#include <math.h>
using namespace std;

int sum_digit(int x)
{
int ans;
??????
}
int main()
{
int a;
cout<<"enter number x\n";
cin>>a;

cout<<sum_digit(a) <<endl;


system("pause");

}
Last edited on
get remainder by dividing the number by 10 in a loop and make sure that dont divide the same number again and again i.e remove the remainder part by dividing the number by 10 in each iteration. and store sum of the remainder in a variable.
do this with while or for?
for(int i=10 ; ?? ;i--)
int ans=1
i=x/i;
}
ans=i;
return i;

i
i think i dont understand
take remainder in each iteration and save it in variable say remsum.
now remsum=number%10
% is used to get remainder.
after that you have to remove that remainder from your orignal number because you have save it where you want to.
for this you have to divide it by 10. last digit will be removed because dividing the number by will give you a float and int dont save digits after decimal.
as you will use the loop that means you have to add remainder in the previous sum(i.e previous remainder.
for this you need to write
remsum+=number%10.
and make sure that you assign remsum=0 where you initialize it else it will start from a garbage value.
Topic archived. No new replies allowed.