-1

I have this function:

int calc (int day, int month , int year)
{
    int cal;
    cal=day+month+year;
    cout<<cal;
}

Let say that the result of cal is 2008. What I want to do is to count each number separately.

Example:

2008=2+0+0+8=10

But I don't know how to do that. Any ideas?

Thanks

Edit:

Another Example:

day=20
Month=03
Year=1993

20+03+1993=2016

And 2+0+1+6=9
Community
  • 1
  • 1

1 Answers1

1

This is the way you take the sum of digits of any number.

The modulos divide (%) operator is used to extract the last digit. and a running sum is kept to keep the sum of digits. The divide operation at the end removes the last number from the digit so that in the next round of loop the second last number can be extracted by %.

Keep in mind that the number(num) is of integer type. Hence when you divide the number by 10, it keeps the integer part and discards any decimal part. Thus, 2008/10=200 and not 200.8. Also to clarify the % operator, 2008%10=8 as 8 is the remainder of dividing 2008 by 10.

num=2008;    //put any number here
sum=0;
while(num>=0)
{
       digit=num%10;
       sum+=digit;
       num=num/10;
}
cout<<sum;
DotPi
  • 3,977
  • 6
  • 33
  • 53