Home »
C++ Programs
C++ program to convert decimal number to binary using class
Submitted by Shubh Pachori, on September 09, 2022
Problem statement
Given a decimal number, we have to convert it into binary using the class and object approach.
Example:
Input:
Enter Decimal Number : 15
Output:
Binary is 1111
C++ code to convert decimal number to binary using the class and object approach
#include <iostream>
using namespace std;
// creating a class
class DecimaltoBinary {
// private data members
private:
int decimal;
// public member function
public:
// getDecimal() function to insert
// decimal number
void getDecimal() {
cout << "Enter Decimal Number : ";
cin >> decimal;
}
// dtob() function to convert decimal to binary
void dtob() {
// initializing a array to store binary
// digit and a index
int b[10], index;
// for loop to convert decimal to binary
for (index = 0; decimal > 0; index++) {
// storing remainder of decimal value
b[index] = decimal % 2;
// updating the divided decimal value
decimal = decimal / 2;
}
// print base line
cout << "Binary is ";
// for loop to printing the binary
// value stored in array
for (index = index - 1; index >= 0; index--) {
cout << b[index];
}
}
};
int main() {
// declaring object
DecimaltoBinary D;
// calling getDecimal() function to
// insert decimal number
D.getDecimal();
// calling dtob() function to convert
// it to binary
D.dtob();
return 0;
}
Output
RUN 1:
Enter Decimal Number : 108
Binary is 1101100
RUN 2:
Enter Decimal Number : 255
Binary is 11111111
Explanation
In the above code, we have created a class DecimalToBinary, one int type data member decimal to store the decimal number, and public member functions getDecimal() and DToB() to store and convert the given decimal number to the binary digit.
In the main() function, we are creating an object D of class DecimalToBinary, reading the decimal number given by the user using getDecimal() function, and finally calling the DToB() member function to convert the given decimal number. The DToB() function contains the logic to convert the given decimal number and printing the result.
C++ Class and Object Programs (Set 2) »