// University of Iowa // 22C-30 Homework 3 // Problem 3 // by: Justin C. Miller // Prof: Sriram // Description: recursive function // to computer binary // equivalent of a given // positive integer n #include // for cout, cin #include // for EXIT_SUCCESS #include // for string using namespace std; // so there's no std::cin string binaryEquivalent(int) ; int main(int argc, char * argv[]){ for(int i = 0 ; i < 32 ; i++) cout << i << " in binary is " << binaryEquivalent(i) << endl ; return EXIT_SUCCESS ; }//end of main function // PRE- given a positive integer n // POST- returns binary equivalent of // of n in string format string binaryEquivalent(int n){ if(n < 0){ cerr << "Binary Equivalent only" << " works w/ positive integers"<< endl ; exit(EXIT_FAILURE) ; }else if(n == 0){ return "0" ; // required only for n = 0 }else if(n == 1){ return "1" ; // base case }else if(n % 2 == 0){ return binaryEquivalent(n/2) + "0" ; // even }else{ return binaryEquivalent(n/2) + "1" ; // odd }//else }//end of binaryEquivalent function