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

Question #186604

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-05-03T05:24:34-0400
#include <iostream>
using namespace std;
#include <math.h>

class Binary{
    public:
        char binNum[5]="1010";
        Binary(){
            cout<<"\nThe binary equivalent is: "<<binNum;
        }


};




class Decimal: public Binary{
    private:
        int decNum;


    public:
        Decimal(){
            int n=atoi(binNum);
            decNum = 0;
            int base = 1;


            int temp = n;
            while (temp) {
                int last_digit = temp % 10;
                temp = temp / 10;


                decNum += last_digit * base;


                base = base * 2;
            }
            cout<<"\n"<<"The decimal equivalent is: "<<decNum;
        }


};




class Hexadecimal: public Binary{
    private:
        int hex;


    public:
        Hexadecimal(){
            int hex[1000];
            int i = 1, j = 0, rem, dec = 0, binaryNumber;
            binaryNumber=atoi(binNum);
            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 dec1;
    Hexadecimal hex1;
    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