0

this bit of code, prints the binary backwards, and I got no clue why I know it's a bit inefficient but I don't get why its backwards you can skip to case 1, the rest isn't a that important unless you want some extra details on it. anyways, if you have any ideas, it would be deeply appreciated

#include <iostream>
#include <cmath>

#include <iostream>

using namespace std;
int main()
{
    cout<<"Hello World";
    int num = 8;
    int numalt;
while (num >= 1){numalt = num % 2;num=num / 2;if (numalt <= 1){cout<<numalt;};}
    return 0;
}
  • What you do is to convert a number to binary representation. You have to read it backwards! see https://stackoverflow.com/questions/7349689/how-to-print-using-cout-a-number-in-binary-form – MiniMik Aug 05 '21 at 07:39
  • 1
    What I do in these situations is get a piece of paper and a pen and go through every statement of the program one at a time, and make a note on the paper which variables contain what data every step of the way. – Galik Aug 05 '21 at 07:44
  • You could store the binary digits into a container (e.g. `std::vector`) and `std::reverse()` them after you're done. (Though, once the digits are in the container, you just could output them from back to front.) A convoluted solution would be to do the conversion in a recursive function where the output is done while returning from recursive descent... – Scheff's Cat Aug 05 '21 at 07:55

1 Answers1

0

May have a look at this... you have to revert the result...

#include <iostream>
#include <vector>


//using namespace std;
int main()
{
  std::vector<int> v{};

  std::cout << "Hello World" << std::endl;

  int num = 8;
  int numalt;

  while (num >= 1)
  {
    numalt = num % 2;
    num = num / 2;
    if (numalt <= 1)
    {
      v.insert(v.begin(), numalt);
      //cout<<numalt;
    }
  }
  
  for (std::vector<int>::const_iterator i = v.begin(); i != v.end(); ++i)
    std::cout << *i;

  std::cout << std::endl;
  return 0;
}
MiniMik
  • 268
  • 1
  • 10