Home »
C++ Programs
C++ program to find the sum of all digits of a number using class
Submitted by Shubh Pachori, on August 22, 2022
Problem statement
Given a number, we have to find the sum of all digits of a number using the class and object approach.
Example:
Input:
Enter Number: 12345
Output:
Sum of all digits of the number is 15
C++ code to find the sum of all digits of a number using the class and object approach
#include <iostream>
using namespace std;
// create a class
class Sum {
// private data member
private:
int number;
// public functions
public:
// getNumber() function to get the number
void getNumber() {
cout << "Enter Number:";
cin >> number;
}
// add() function to find the Sum of
// all digits of the number
int add() {
int sum = 0, remain;
while (number) {
// the last digit of number is stored
// in remain by % operator
remain = number % 10;
// remain is added in the sum
sum = sum + remain;
// number is divided by 10 to
// discard the last digit
number = number / 10;
}
// returning the sum
return sum;
}
};
int main() {
// create an object
Sum S;
// int type variable to store the
// sum of all digits in it
int sum;
// function is called by the object to
// store the number
S.getNumber();
// add() function to add all digits
// of the number
sum = S.add();
cout << "Sum of all digits of the number is " << sum;
return 0;
}
Output
Enter Number:9876
Sum of all digits of the number is 30
Explanation
In the above code, we have created a class named Sum, an int type data member number to store the number, and public member functions getNumber() and add() to store and find out the sum of all digits of the given number.
In the main() function, we are creating an object S of class Sum, reading an integer number by the user using getNumber() function, and finally calling the add() member function to find out the sum of all digits of a given integer number. The add() function contains the logic to find out the sum of all digits of the given number and printing the result.
C++ Class and Object Programs (Set 2) »