sum function

Nov 23, 2013 at 7:22pm
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 Nov 23, 2013 at 7:23pm
Nov 23, 2013 at 7:51pm
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.
Nov 23, 2013 at 7:57pm
do this with while or for?
for(int i=10 ; ?? ;i--)
int ans=1
i=x/i;
}
ans=i;
return i;

i
Nov 23, 2013 at 7:58pm
i think i dont understand
Nov 23, 2013 at 8:16pm
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.