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:
- Define a class Number with a private member variable num and a public member function getSingleDigitSum().
- In the constructor of the class, prompt the user to enter a number and store it in the num variable.
- In the getSingleDigitSum() function, initialize a variable sum to 0 and a variable temp to the value of num.
- 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.
- Check if sum is greater than 9. If it is, call getSingleDigitSum() recursively passing sum as the argument.
- If sum is less than or equal to 9, return sum as the single digit sum.
- In the main() function, create an object of the Number class.
- Use the object's getSingleDigitSum() function to get the single digit sum of the digits in the number and print it.
- 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