Write a C++ program using the concept of OOP to find the summation of digits of a number.
Algorithm:
- Define a class Number with a private member variable num and a public member function getSumOfDigits().
- In the constructor of the class, prompt the user to enter a number and store it in the num variable.
- In the getSumOfDigits() 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 not equal to 0. In each iteration, add the last digit of temp to sum and divide temp by 10.
- Return the value of sum as the summation of digits.
- In the main() function, create an object of the Number class.
- Use the object's getSumOfDigits() function to get the summation of 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 getSumOfDigits() {
int sum = 0;
int temp = num;
while (temp != 0) {
sum += temp % 10;
temp /= 10;
}
return sum;
}
};
int main() {
Number n;
cout << "Sum of digits: " << n.getSumOfDigits() << endl;
return 0;
}
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment