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

Question #187302

Write a program which has a class called binary which has a character array to store a binary




string. The class decimal derives from class binary and contains an integer data member. Another




class called hexadecimal also derives from binary. Each class should contain constructors and




appropriate data members to input and display the elements. The display function of binary class




displays the binary equivalent, hexadecimal class’s display function displays hexadecimal




equivalent whereas decimal class’s display function displays the decimal equivalent.




1
Expert's answer
2021-04-30T09:23:55-0400
#include <iostream>
using namespace std;
#include <math.h>


class Binary{
    public:
        char bin[10]="1011";
        Binary(){
            cout<<"\nThe binary equivalent is: "<<bin;
        }
        
};


class Decimal: public Binary{
    private:
        int num;
    
    public:
        Decimal(){
            int n=atoi(bin);
            int dec_value = 0;
            int base = 1;
         
            int temp = n;
            while (temp) {
                int last_digit = temp % 10;
                temp = temp / 10;
         
                dec_value += last_digit * base;
         
                base = base * 2;
            } 
            cout<<"\n"<<"The decimal equivalent is: "<<dec_value;
        }
    
};


class Hexadecimal: public Binary{
    private:
        int hex;
    
    public:
        Hexadecimal(){
            int hex[1000];
            int i = 1, j = 0, rem, dec = 0, binaryNumber;
            binaryNumber=atoi(bin);
            while (binaryNumber > 0) 
              {
               rem = binaryNumber % 2;
               dec = dec + rem * i;
               i = i * 2;
               binaryNumber = binaryNumber / 10;
              }
               i = 0;
              while (dec != 0) 
              {
               hex[i] = dec % 16;
               dec = dec / 16;
               i++;
              }
              cout<<" \nThe hexadecimal equivalent: ";
              for (j = i - 1; j >= 0; j--)
              {
               if (hex[j] > 9) 
               {
                cout<<(char)(hex[j] + 55)<<"\n";
               } 
               else
               {
                cout<<hex[j]<<"\n";
               }
              }
            
        }
    
};
int main(){
    Decimal d;
    Hexadecimal h;
    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