this code finds the binary of a decimal integer N; it divides the number by 2 and takes the floor of the result and divides it also by 2,
the code gets the remainder of those divisions 0 or 1 and builds up the binary.
The problem with this code is that it won't run until the last division example (take 128 the last division is 1/2 and remainder is 1, the program stops at N/2 > 0 as specified in the while loop and 1/2 = 0 since 1 is of type int).
How do I resolve this issue or how do I modify the condition in the while loop?
#include <iostream> using namespace std; void ConvertToBinary(int N); int main() { int N = 1; while (1) { cout << "enter N: "; cin >> N; cout << endl; ConvertToBinary(N); cout << endl; } system("pause"); return 0; } void ConvertToBinary(int N) { int A[1000]; int i=0; cout << "The binary of " << N << "= "; while (N / 2 > 0) { if (N % 2 == 0) { A[i] = 0; } else if (N % 2 != 0) { A[i] = 1; } N = N / 2; i++; } for (int j= i-1 ; j>=0 ; j--) { cout<<A[j]; } cout << endl; }
while (N)should do it, I think.