×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object Programs

C++ program to convert binary number to octal number using class

Submitted by Shubh Pachori, on August 08, 2022

Problem statement

Given a binary number, we have to convert it to octal number using the class and object approach.

Example:

Input:
Enter Binary: 10101

Output:
Octal Number: 25

C++ code to convert binary number to octal number using class and object approach

#include <iostream>
#include <cmath>
using namespace std;

// create a class
class BinaryToOctal {
  // private data member
 private:
  long binary;

  // public functions
 public:
  // getBinary() function to get binary digit
  void getBinary() {
    cout << "Enter Binary:";

    cin >> binary;
  }

  // BToO() function to convert binary to octal
  int BToO() {
    // declaring int type variables for operations
    int octal = 0, decimal = 0, index = 0;

    // while to convert binary to decimal
    while (binary != 0)

    {
      decimal = decimal + (binary % 10) * pow(2, index);

      index++;

      binary = binary / 10;
    }

    index = 1;

    // while loop to convert decimal to octal
    while (decimal != 0)

    {
      octal = octal + (decimal % 8) * index;

      decimal = decimal / 8;

      index = index * 10;
    }

    // returning the converted value
    return octal;
  }
};

int main() {
  // create a object
  BinaryToOctal B;

  // initialize a int type variable to store the value
  int o;

  // calling getBinary() function to insert the binary digit
  B.getBinary();

  // calling BToO() function to convert it
  o = B.BToO();

  cout << "Octal Number:" << o;

  return 0;
}

Output

Enter Binary: 11001
Octal Number: 31

Explanation

In the above code, we have created a class BinaryToOctal, one long type data member binary to store the binary digit, and public member functions getBinary() and BToO() to store and convert the given binary digit to octal number.

In the main() function, we are creating an object B of class BinaryToOctal, reading the binary digit given by the user using getBinary() function, and finally calling the BToO() member function to convert the given binary digit. The BToO() function contains the logic to convert the given binary digit and printing the result.

C++ Class and Object Programs (Set 2) »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.