C++ Program to Find Sum of Digits of A Number Using Classes
Have you ever wondered that how to find sum of digits in C++ using classes?
It is a quite easy job. I will tell you step-by step that how you can manage to find sum of digits of an integer in C++.
Digit sum means adding all the digits of a particular number.
For example, if we take a number 532 then its sum of digits will be:
Program Logic & Structure:
If we think about the logic behind summation of digits of a number then we can conclude that:
- Take a number from user as input.
- Grab each digit from that number.
- Add all the digits grabbed from number.
- Display the sum on screen.
One question arises that how we will extract the digits from given number?
The answer to this question is very simple. Dividing a number by 10 gives us the last digit of that number as remainder. We will continue a loop to grab each digit of the number and sum them up.
Recommended reading: C++ Program For Addition of Two Numbers Using Classes
using namespace std;
cout<<"ENTER NUMBER: ";
sum = sum + rem;
num = num / 10;
cout<<"SUM OF DIGITS: "<<sum;
This program is based on the concepts of Object Oriented Programming (OOP). As data members, classes, member functions are used in this program to accomplish the task.
First of all, we defined a new class named SUMdigits and included two data members i.e. variables named num & sum.
We also defined a constructor which initializes the values of both variables to zero.
Next, we declared a function to get input from user. We asked the user to enter a number and stored it in num variable.
After that, we defined a function named digits_Sum i.e. main part of this class. This function extracts all the digits from number and sum them.
Here, we declared rem variable to store the remainder of division.
We initialized a loop which continues until num is greater than 0. It means that loop will stop if there is no more digit in given number.
Recommended reading: C++ Project For Address Book Management
I have told you before that dividing a number by 10 gives us the last digit of that number as remainder. It means that one digit is extracted from number and we stored that digit in rem variable.
Next, we added this number to sum variable which is the result of this program.
At the end, we used output() function to show the sum of digits on screen.
In main function, we simple declared an object and used all three functions of SUMdigits class.
If you want to learn about finding sum of digits of number without classes then you can Read Here.
If you have any question then you can ask me in comments. I would like to answer them.
You can also Click Here To Download Exercise Files.