0
Help with code
I wrote a program that displays the binary code of the entered number, but when it is output, it must be read in reverse order. How can this be fixed. Here is the code #include <iostream> using namespace std; int main () { int a; cin >> a; while (a! = 0) { if (a == 0) { break; } if (a> 0 && a% 2 == 0) { cout << "0"; a / = 2; } if (a> 0 && a% 2 == 1) { cout << "1"; a / = 2; } } return 0; } https://code.sololearn.com/cNPhSqayv4rD/?ref=app
4 odpowiedzi
+ 3
Hope this helps..!!!
https://code.sololearn.com/c4W0ydsI5sXz/?ref=app
+ 5
Instead of printing remainder of division right away , store it in an array.
We convert decimal to binary by repeatedly dividing decimal number by 2 as long as number is greater than 0 .
So create an array store remainder each time in array and displlay array in reverse order.
Algorithm
Get dec_no.
Initialize i=-1
Int array[32];
While(dec!=0)
{
i=i+1;
array[i]=dec_no%2;
dec_no=dec_no/2;
}
Dispaly array in reverse by starting from index i to index 0
you can use bitwise operators for more efficient program.
0
you can write and send code, I'm just a beginner programmer and it’s hard to understand some