×

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 decimal number to octal number using class

Submitted by Shubh Pachori, on August 08, 2022

Problem statement

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

Example:

Input:
Enter Decimal Number: 22

Output:
Octal Number: 26

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

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

// create a class
class DecimalToOctal {

    // private data member
private:
    int decimal;

    // public functions
public:
    // getDecimal() function to get Decimal Number
    void getDecimal()
    {
        cout << "Enter Decimal Number:";
        cin >> decimal;
    }

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

        // while loop for conversion
        while (decimal) {
            octal = octal + (decimal % 8) * index;
            decimal = decimal / 8;
            index = index * 10;
        }

        // returning octal number
        return octal;
    }
};

int main()
{
    // create a object
    DecimalToOctal D;

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

    // calling getDecimal() function to insert the Decimal Number
    D.getDecimal();

    // calling DToO() function to convert it
    o = D.DToO();

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

    return 0;
}

Output

Enter Decimal Number:6655
Octal Number:14777

Explanation

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

In the main() function, we are creating an object D of class DecimalToOctal, reading the decimal number given by the user using getDecimal() function, and finally calling the DToO() member function to convert the given decimal to octal. The DToO() function contains the logic to convert the given decimal number to an octal 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.