Answer to Question #186381 in C++ for RAHUL SINGH

Question #186381

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 Armstrong is derived from

class called Number. Another class called Palindrome is derived from class Number. Use

appropriate constructors and redefine the function called operation to display if the number is

Armstrong number as well as Palindrome in case it falls in this category. You may make use of

other data members and member functions if needed


1
Expert's answer
2021-05-01T17:01:39-0400
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
class Number{
    protected:
        int x;
    public:
        Number(){}
        virtual void operation(){}
};
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