Ask Question
1 January, 07:59

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).

+5
Answers (1)
  1. 1 January, 08:04
    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?
Get 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 & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers