This code is a simple implementation in C++ that converts a decimal number to binary.
#include <iostream>
using namespace std;
int main() {
int binaryArray[10], num, i;
cout << "Please enter a number: ";
cin >> num;
for (i = 0; num > 0; i++) {
binaryArray[i] = num % 2;
num = num / 2;
}
cout << "Binary value of number " << num << " is ";
for (i = i - 1; i >= 0; i--) {
cout << binaryArray[i];
}
}
Please enter a number: 23
Binary value of number 0 is 10111
main()
function starts with the declaration of an integer array called binaryArray
and two integer variables, num
and i
.cin
statement. The input number is stored in the num
variable.num
becomes 0. The loop starts with i = 0
.num % 2
is stored in binaryArray[i]
. This value represents the binary digit.num
is then divided by 2 using the num = num / 2
statement.num
becomes 0, and the binary digits are stored in the binaryArray
array.i = i - 1
and continues until i >= 0
.binaryArray[i]
is printed using the cout
statement.main()
function ends with a return 0 statement.