Ask Question
14 October, 22:58

Write a program that takes as input a positive integer, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:

As long as x is greater than 0

Output x % 2 (remainder is either 0 or 1)

x = x / 2

Note: The above algorithm outputs the 0's and 1's in reverse order.

If the input is 6, the output is 011. (6 in binary is 110; the algorithm outputs the bits in reverse).

+4
Answers (1)
  1. 15 October, 01:32
    0
    I implemented this program in C+ + programming language using Dev C++.

    You can get the running code with an explanation in the explanation section. This program is tested for all input as asked in the question. However, this program can convert any integer into binary and then print the binary digits into reverse order.

    Explanation:

    #include

    using namespace std;

    int main ()

    {

    int x, j, i; / / to declare the variable

    int a[10];

    cout<<"Enter value for x: "; //allow user to enter the value;

    cin>>x;

    if (x<0) / /check if user enter negative value

    {

    cout<<"You entered negative value./n";

    cout<<"Enter value for x: "; //allow user to enter the value;

    cin>>x;

    }

    for (i=0; x>0; i++) / / loop until x become zero

    {

    a[i]=x%2; //store remainder into array a[]

    cout<
    x=x/2; / / divide the value that is entered by user by 2

    j=j+1; / * count the number of binary bit i. e how many zero and one in an array (j is used to count the number of element in array a[]*/

    }

    cout<<"/n "; //newline

    for (int i=1; i<=j; i++) / /print array in reverse order

    {

    cout<
    }

    return 0;

    }
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Write a program that takes as input a positive integer, and outputs a string of 1's and 0's representing the integer in binary. For an ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers