Write a C++ program using the concept of OOP to check whether a number is strong or not


Write a C++ program using the concept of OOP to check whether a number is strong or not.

Algorithm:

  1. Define a class Number with a private member variable num and a public member function isStrong().
  2. In the constructor of the class, prompt the user to enter a number and store it in the num variable.
  3. In the isStrong() function, initialize a variable temp to the value of num and a variable sum to 0.
  4. Use a while loop to iterate until temp is greater than 0. In each iteration:
    1. Get the last digit of temp and store it in a variable lastDigit.
    2. Initialize a variable fact to 1.
    3. Use another loop to iterate from 1 to lastDigit and multiply the value of fact with the current iteration value.
    4. Add the value of fact to sum.
    5. Divide temp by 10.
  5. Compare the sum with the original number and return true if they are equal, else return false.
  6. In the main() function, create an object of the Number class.
  7. Use the object's isStrong() function to check if the number is strong number or not, and print the result.
  8. 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