C++ Program to obtain the sum of digits of given number [DEVCPP/GCC]

STEPS

In order to calculate the sum of digits of a given number,

1. Obtain the last digit of given number using modulus (% ) operator.
                                    123 % 10 = 3

2. Add the obtained digit in a variable (sum) which is initialized by 0.
                                       0 + 3 = 3

3. Divide the number by 10 in order to remove the last digit from given number.
                                      123/10 = 12

4. Repeat the above steps 1-3 until number is not zero.                              

PROGRAM

//Program to obtain the sum of digits of given number

#include <iostream>

using namespace std;

int main()
{
        int num,sum=0,last;

        cout<<"ENTER NUMBER: ";
        cin>>num;

        while(num>0)
        {
                last = num % 10;          // Obtain Last Digit Of Number
                sum = sum + last;        // Add Obtained Digit to Number
                num = num /10;          // Remove Last Digit From Number
        }

        cout<<"\nSUM OF DIGITS IS "<<sum;
        return 0;
}

OUTPUT

C++ Program to obtain the sum of digits of given number

Share this

Related Posts

1 comments :

comments
June 6, 2017 at 10:58 PM delete

Thank You SujitKumar for your kind words!

Reply
avatar

FIND US ON FACEBOOK!