0

Convert decimal to binary of the user's input. Only to use for loop and modulus

#include<iostream> #include<conio.h> using namespace std; int main() { int DecimalNumber; int BinaryNumber; cout << "Enter Your Decimal Number Here :"; cin >> DecimalNumber; cout << endl << DecimalNumber << ": In Binary Is : "; for (int loop = DecimalNumber;loop >= 1;loop /= 2) { BinaryNumber = loop % 2; cout << BinaryNumber; } _getch(); return 0; } This code prints the answer but is inverted

28th Mar 2021, 8:23 AM
Khawaja Haris Ahmad
Khawaja Haris Ahmad - avatar
11 Respuestas
+ 1
Find largest power of 2 < DecimalNumber and divide by 2 in loop each step. Also in loop print 1 if remaining number is bigger and sutract from number, else print 0. To find largest power of 2 you can use another loop starting at 2 and doubling each step
28th Mar 2021, 11:10 AM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
You can store your whole output in string variable, so it will be easy to reverse and print
28th Mar 2021, 9:14 AM
Michal Doruch
0
Michał Doruch sorry I wasn't clear, question asks us to only use "for" loops and modulus operator. Even I don't think it would be possible but thats why I posted it here
28th Mar 2021, 9:21 AM
Khawaja Haris Ahmad
Khawaja Haris Ahmad - avatar
0
Coder Kitten exactly thats why I'm here. It can be conducted easily using a pointer or array. I just want to know if it is even possible without them
28th Mar 2021, 9:45 AM
Khawaja Haris Ahmad
Khawaja Haris Ahmad - avatar
0
Ty
28th Mar 2021, 9:47 AM
Khawaja Haris Ahmad
Khawaja Haris Ahmad - avatar