Skip to main content
Decimal to Binary in C++ (Using Loop & Array)
Decimal to Binary in C++ (Using Loop & Array)
#include <iostream>
using namespace std;
int main() {
int decimalNum;
int binaryNum[32]; // To store binary digits
int index = 0; // Counter for binary array
cout << "Enter a decimal number: ";
cin >> decimalNum;
int tempNum = decimalNum;
if (decimalNum == 0) {
cout << "Binary: 0";
return 0;
}
// Process of dividing by 2 and storing remainder
while (decimalNum > 0) {
binaryNum[index] = decimalNum % 2;
decimalNum = decimalNum / 2;
index++;
}
cout << "Binary of " << tempNum << " is: ";
// Printing binary in reverse order
for (int i = index - 1; i >= 0; i--) {
cout << binaryNum[i];
}
cout << endl;
return 0;
}
Comments
Post a Comment
welcome user , hope you good