PDA

View Full Version : quick recursion question...



Anon
04-05-2008, 02:26 PM
void main()
{

//Recursion 2: Print Binary
cout << "The binary equivalent of 13 is: " << printBinary(13) << endl;

}





int printBinary(int n)
{
if (n > 0)
{
if ((n % 2) == 0)
{
printBinary(n /= 2);
cout << "0";
}
else
{
printBinary(n /= 2);
cout << "1";
}
}
return 5;
}


So im writing a simple recursive method to output the binary equivalent of a base 10 number. What I have works, however im lost on how I should return the number. What I have now is just a test with the return being 5 just as a placeholder. Any ideas on how to return the binary instead of just cout?

Nore
04-05-2008, 02:41 PM
whywork/margorp

ryph
04-05-2008, 02:49 PM
moved here
i code in C, so just switch the printf's over to couts and whatnot


#include <stdio.h>
#include <string.h>

char * printBinary(int n){
char binary[10];

if (n > 0){
if ((n &#37; 2) == 0){
strcpy(binary, "0");
strcat(binary, printBinary(n /= 2));
}else{
strcpy(binary, "1");
strcat(binary, printBinary(n /= 2));
}
}
return binary;
}

int main(){
char binary[10], binary2[10];
int a;

strcpy(binary, printBinary(13));

//flip the binary to proper order
for (a=0; a<strlen(binary); a++)
binary2[a]=binary[strlen(binary)-(a+1)];
binary2[a]='\0';

printf("The binary equivalent of 13 is : %s\n", binary2);
return 0;
}


edit: fixed to loop the binary around to proper order

Anon
04-05-2008, 03:05 PM
ya i know it was the wrong place to put it, i just wanted an answer asap so i posted it where there was more people.

Anon
04-05-2008, 03:49 PM
thanx