Write a C++ program using the concept of OOP to check whether a number is strong or not.
Algorithm:
- Define a class Number with a private member variable num and a public member function isStrong().
- In the constructor of the class, prompt the user to enter a number and store it in the num variable.
- In the isStrong() function, initialize a variable temp to the value of num and a variable sum to 0.
- Use a while loop to iterate until temp is greater than 0. In each iteration:
- Get the last digit of temp and store it in a variable lastDigit.
- Initialize a variable fact to 1.
- Use another loop to iterate from 1 to lastDigit and multiply the value of fact with the current iteration value.
- Add the value of fact to sum.
- Divide temp by 10.
- Compare the sum with the original number and return true if they are equal, else return false.
- In the main() function, create an object of the Number class.
- Use the object's isStrong() function to check if the number is strong number or not, and print the result.
- Exit the program.
Coding:
#include <iostream> using namespace std; class Number { private: int num; public: Number() { cout << "Enter a number: "; cin >> num; } bool isStrong() { int temp = num; int sum = 0; while (temp > 0) { int fact = 1; int lastDigit = temp % 10; for (int i = 1; i <= lastDigit; i++) { fact *= i; } sum += fact; temp /= 10; } return sum == num; } }; int main() { Number n; if (n.isStrong()) { cout << "The number is a strong number." << endl; } else { cout << "The number is not a strong number." << endl; } return 0; }
#OOP
#HappyProgramming
#HappyCoding
No comments:
Post a Comment