I've been working with a program that inputs an integer and prints it's binary representation. The program works fine, but there are two things I don't get.
The final loop at the bottom of convert function prints the array in reverse order but I don't understand why it needs to be written that way. The integer j is assigned whatever variable i is minus one to start that loop.
Also I want to always print out eight bit places. If I enter the integer 58 I want it to output 00111010. But my program just outputs 111010. So how can I get it to always output all eight bit places?
Code:void convertToBinary(int n) { int binaryNumber[8]; int i = 0; while(n > 0) { binaryNumber[i] = n % 2; // store the 1's and 0's in array n /= 2; i++; } cout << "The binary equivalent is "; // print the binary digits in reverse order for(int j = i - 1; j >= 0; j--) // why is this written like this cout << binaryNumber[j] << " "; }