C++ Program to find the sum of digits of a number

Program to find the sum of digits of a number

Here we will discuss how to find the sum of digits of a number in C++ programming language.

To find the sum of digits in a number we will use loops along with two arithmetic operators, ‘/ ’ and ‘% ’.

C++ Program to find the sum of digits of a number

Algorithm:-

  • Take int number as input and store it in num
  • To extract digits we have to use modulus operator (num%10) will give us digit at unit place
  • for subsequent digits we have to update num as num=num/10, so unit digit will get removed from number
  • Initialize sum=0
  •  A do while loop is started
    • Value of sum is incremented by remainder of num divide by 10 i.e. num % 10

                                sum+=num%10; 

    • Divide num by 10 and store result in num itself   

                                num=num/10;

    • Do this until num is not equal to 0

                                while(num!=0);

  • sum is printed which is the output

C++ Code:-

    
    //C++ Program
    //Sum of digits in a number
    #include
    using namespace std;
    int main()
    {
        int num,sum=0;
        cout<<“Enter any num : “;
        //user input
        cin>>num;
        //loop to find sum of digits
        do
        {
                sum+=num%10;
                num=num/10;
        }while(num!=0);
        //output
        cout<<\nSum of digits in given integer is: “<<sum;
        return 0;
    }

 

    Output:

 

    Enter any num : 83625

 

   sum of digits in given integer is: 24