Using a recursive function to print array backwards
Feb 13, 2019 at 1:21am Feb 13, 2019 at 1:21am UTC
Im currently attempting to write some code that converts a decimal number into binary and the use a recursive function to print the contents of an array backwards. clearly im not quite understanding recursion at the moment. because if i was to enter the number 4, the results display "0010000000000000" so i am clearly missing something obvious. can anyone help me out with this?
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 44 45 46 47 48 49
#include <iostream>
using namespace std;
const int SIZE = 16;
void convert(unsigned short int ,int []);
void printbackward(int [], int ); //prototype
int main()
{ unsigned short int number;
int binary[SIZE] = {0};
cout << "Enter a positive integer " ;cin>>number;
convert(number,binary);
cout << "The decimal number " << number<< " in binary is " ;
printbackward(binary,SIZE-1);
return 0;
}
void convert(unsigned short int n, int bin[])
{
int index = 0;
while (n != 0)
{ bin [index] = n%2;
n = n/2;
index++;
}
}
void printbackward(int binary[], int s) //function definition
{
if (s == 0)
cout << binary[s];
else
{
printbackward(binary, s-1);
cout << binary[s];
}
}
Feb 13, 2019 at 1:37am Feb 13, 2019 at 1:37am UTC
Your output is correct.
4 is "100" in binary.
You can have any number of zeros in front of any number. Your convert() function creates a number with 16 zeros (a 16-bit value).
So, "0000000000000100" printed backwards is "0010000000000000".
Good job!
Topic archived. No new replies allowed.