Answer to Question #187604 in C++ for RAHUL KUMAR

Question #187604

Write a program which has an abstract class called Number having an integer data member. The class contains a pure virtual function called operation. A class called odd is derived from class called Number. Another class called Even is derived from class Number. Yet another class called prime is derived from Number. Use appropriate constructors and redefine the function called operation to display if the number is odd, even or prime. You may make use of other data members and member functions if needed. 


1
Expert's answer
2021-05-03T23:44:18-0400
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
//Define Number class
class Number{
    //variable define
    protected:
        int x;
    public:
        //define constructor
        Number(){}
        //define virtual function
        virtual void operation(){}
};
// define child class
class Palindrome: public Number{
    public:
        Palindrome(int y){
            this->x = y;
        }
        bool is_palindrome(){
            string s = to_string(x);
            for(int i = 0, j = s.length() - 1; i < s.length() / 2; i++, j--){
                if(s[i] != s[j]) return false;
            }
            return true;
        }
        void operation(){
            if(is_palindrome()){
                cout<<x<<" is a palindrome\n";
            }
            else cout<<x<<" is not a palindrome\n";
        }
};
class Armstrong: public Number{
    public:
        Armstrong(int y){
            x = y;
        }
        bool is_armstrong(){
            string s = to_string(x);
            int sum = 0;
            for(int i = 0; i < s.length(); i++){
                sum += (int)(pow(s[i] - '0', 3));
            }
            if(sum == x) return true;
            else return false;
        }
        void operation(){
            if(is_armstrong()) cout<<x<<" is an armstrong number\n";
            else cout<<x<<" is not an armstrong number\n";
        }
};
int main(){
    Number *no;
    int x;
    cout<<"Input integer: ";
    cin>>x;
    no = new Armstrong(x);
    no->operation();
    no = new Palindrome(x);
    no->operation();

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS