Write a C++ program using the concept of OOP to find the sum of digits of a number until the sum is reduced to a single digit


Write a C++ program using the concept of OOP to find the sum of digits of a number until the sum is reduced to a single digit.


Algorithm:

  1. Define a class Number with a private member variable num and a public member function getSingleDigitSum().
  2. In the constructor of the class, prompt the user to enter a number and store it in the num variable.
  3. In the getSingleDigitSum() function, initialize a variable sum to 0 and a variable temp to the value of num.
  4. Use a while loop to iterate until temp is greater than 0. In each iteration, add the last digit of temp to sum and divide temp by 10.
  5. Check if sum is greater than 9. If it is, call getSingleDigitSum() recursively passing sum as the argument.
  6. If sum is less than or equal to 9, return sum as the single digit sum.
  7. In the main() function, create an object of the Number class.
  8. Use the object's getSingleDigitSum() function to get the single digit sum of the digits in the number and print it.
  9. Exit the program.


Coding:

#include <iostream>
using namespace std;
 
class Number {
    private:
        int num;
    public:
        Number() {
            cout << "Enter a number: ";
            cin >> num;
        }
        int getSingleDigitSum() {
            int sum = 0;
            int temp = num;
            while (temp > 0) {
                sum += temp % 10;
                temp /= 10;
            }
            if (sum > 9) {
                return getSingleDigitSum();
            } else {
                return sum;
            }
        }
};
 
int main() {
    Number n;
    cout << "Single digit sum of the digits: " << n.getSingleDigitSum() << endl;
    return 0;
}
 


#OOP
#HappyProgramming
#HappyCoding

No comments:

Post a Comment