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

Given an octal number, we have to convert it to decimal number using the class and object approach.
Submitted by Shubh Pachori, on August 08, 2022

Example:

Input:
Enter Octal Number: 43

Output:
Decimal Number: 35

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

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

// create a class
class OctalToDecimal {
  // private data member
 private:
  int octal;

  // public functions
 public:
  // getOctal() function to get Octal Number
  void getOctal() {
    cout << "Enter Octal Number:";
    cin >> octal;
  }

  // OToD() function to convert octal to decimal
  int OToD() {
    // initialising variables to perform operations
    int decimal = 0, index = 0, remain;

    // while loop to convert octal to decimal
    while (octal) {
      remain = octal % 10;
      octal = octal / 10;
      decimal = decimal + remain * pow(8, index);
      index++;
    }

    // returning decimal number
    return decimal;
  }
};

int main() {
  // create a object
  OctalToDecimal O;

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

  // calling getOctal() function to insert the Octal Number
  O.getOctal();

  // calling OToB() function to convert it
  d = O.OToD();

  cout << "Decimal Number:" << d;

  return 0;
}

Output:

Enter Octal Number:122
Decimal Number:82

Explanation:

In the above code, we have created a class OctalToDeimal, one int type data member octal to store the octal number, and public member functions getOctal() and OToD() to store and convert the given octal number to decimal number.

In the main() function, we are creating an object O of class OctalToBinary, reading the octal number given by the user using getOctal() function, and finally calling the OToD() member function to convert the given octal number. The OToD() function contains the logic to convert the given octal number to a decimal number and printing the result.

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




Comments and Discussions!

Load comments ↻





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