Reversing an array of chars (algorithm for this?)
Sep 2, 2010 at 12:13am UTC
Ok, so I'm writing a program to convert decimal into binary. It all works with the exception that my binary shows up in reverse order and I'm having trouble with reversing the array of chars in my intToBinaryString() function.
Any tips on how to get this started?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include<iostream>
#include<cstring>
using namespace std;
void intToBinaryString(long int , char []);
#define ARRAY_SIZE 10001
int main()
{
long int number;
char binary[ARRAY_SIZE];
int count = 0;
cout << "Enter a non-negative integer to convert to binary: " ;
cin >> number;
if (number >= 0)
{
cout << "The binary representation for " << number << " is: " ;
intToBinaryString(number, binary);
}
else
cout << "Enter a non-negative number" << endl;
cout << endl << endl;
system ("pause" );
return 0;
}
void intToBinaryString(long int num, char bin[]) //NOTE:check pg 817 for c-string info
{
int remainder, n=0;
char tempArray[ARRAY_SIZE];
do
{
remainder = num%2;
num = num/2;
itoa(remainder, tempArray, 10);
cout << tempArray;
}while (num > 0);
}
Topic archived. No new replies allowed.