how to write an algorithm that converts deceimal to binary, using mod , div and an array to display the answer

Here's a simple function that uses pow and outputs a char array(string). Basically it checks if the value is greater than or equal to 2 raised to the power of the loop counter. If so set the character at the opposite end of the char array to 1 and decrement the value by 2 raised to the power of the loop counter. This is set for 8 bits but that can easily be changed.

string ToBinary(int input)
{
    char output[9] = "00000000";
    for(int i= 7; i >= 0; i--)
    {
        if(input >= pow(2.0,i))
        {
            output[7-i] = '1';
            input -= pow(2.0,i);
        }

    }
    return output;
}
// converting.cpp : main project file.

#include "stdafx.h"


 #include <iostream>

    using namespace Std;

    int main()

        int array[x] =0;
        int  Deci=0;
         cout<<"enter number";
        cin>>Deci;
        while (Deci!=0)
        {
            array[x] =Deci\2;
            Deci=Deci/2;
        }
            cout<<"results:"<< array[x];
        system("pause");
        return 0;
    }

its not doing not working, and the program its telling that cout is undeclared

You've got to pay more attention to Intellisense when you're writing your code.

No opening brace for main
A capital 'S' to spell 'std'
'x' is undeclared
array[x] =Deci\2; uses a reverse slash instead of a a modulus sign, array[x] =Deci%2;

Edited 3 Years Ago by tinstaafl

This article has been dead for over six months. Start a new discussion instead.