Press "Enter" to skip to content

Find the Sum of Individual Digits of a Number : C++

This is a common question in C++ practical examinations. Here the program accept an integer number and calculate the individual digits and display the sum on the screen.

For example if you give the number 12345, then sum of individual digits is 15 (1 + 2 + 3 + 4 + 5 = 15).


#include <iostream>
using namespace std;

int main()
    int num,lastDigit,sum=0,balNum;
    cout <<"Enter a number : ";
    balNum = num;
     lastDigit = balNum % 10;
     balNum = balNum /10;
     sum = sum + lastDigit;
    cout<<"Sum of individual digits of "<<num<<" is = "<<sum;
    return 0;

Code Explanation:

Variable ‘num’ accepts an input number of integer datatype.

balNum = num;
Here our original number ‘num’ is copied into variable ‘balNum’, because at last of program, we need our original number.

lastDigit = balNum % 10;
Here last digit of the number is assigned into the variable lastDigit using modulus operator (%).

For example: If the number is 12345, then 12345 % 10 is the remainder of the division operation 12345 / 10, that is 5. At while loop we repeat this process to get each individual digits.

balNum = balNum /10;
If we got the last digit, then we don’t need the last number. So we can avoid this number by division operation. That is 12345 / 10 is 1234 (Integer datatype does not support exponential part).

sum = sum + lastDigit;
The variable ‘sum‘ is added into same variable after adding last digit of the number.

‘while loop‘ continues these steps until the value of the balNum is 0.

Sum of individual digits of a given number in c++

Sample Output:

Sum of individual digits of a given number output

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *