Answer to Question #188444 in C++ for Shaikh Shahid Raaz

Question #188444

Write a program which has a class named 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 octal 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, octal class’s display function displays octal equivalent whereas decimal class’s display function displays the decimal equivalent




please dont use bitset stream ,use user define method for conversion


1
Expert's answer
2021-05-04T01:53:47-0400
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
class binary
{
public:
    char s[30];
    binary()
    {
        cout<<"\nEnter a binary number ";
        cin>>s;
    }
    int isBinary(char s[])
    {
        int f=0;
        for(int i=0;i<strlen(s);i++)
            {
                if(s[i]!='0' && s[i]!='1')
                {
                    f=1;
                    break;
                }
            }
        if(f==0)
        {
            return 0;
        }
        else
        {
            return 1;
        }
    }
    void Display_binary()
    {
        if(isBinary(s)!=0)
        {
            cout<<"\nThis is not a binary number ";
        }
        else
        {
            cout<<"\nBinary Number is "<<s;
        }
    }
};
class decimal : public binary
{
 public:
     int a[30],i,sum=0;
     decimal()
     {
         for(int i=0;i<strlen(s);i++)
         {
             a[i]=s[i]-48;
         }
         for(int i=0;i<strlen(s);i++)
         {
             sum=pow(2,(strlen(s)-1-i))*a[i]+sum;
         }
     }
     void display()
     {
         cout<<"\nDecimal Number is "<<sum;
     }


};
class Octal : public binary
{
 public:
     int a[30],i,sum=0,f=1,oct;
     Octal()
     {
         for(int i=0;i<strlen(s);i++)
         {
             a[i]=s[i]-48;
         }
         for(int i=0;i<strlen(s);i++)
         {
             sum=pow(2,(strlen(s)-1-i))*a[i]+sum;
         }
         while (sum != 0)
         {
             oct += (sum % 8) * f;
             sum /= 8;
             f *= 10;
        }
     }
     void display()
     {
         cout<<"\nOctal Number is "<<oct;
     }


};
int main()
{
    decimal d1;
    d1.display();
    Octal o1;
    o1.display();
}




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