Question

In: Computer Science

How to rewrite the bin() function below using recursion instead of a for loop in C?...

How to rewrite the bin() function below using recursion instead of a for loop in C?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>

char* bin(int x, int i);

int main(int argc, char **argv) {
char* binstr = bin(10, 0);
printf("%s\n", binstr);
free(binstr);

return 0;
}

char* bin(int x, int i){
int bits = log10((double) x)/log10(2)+1;
char* ret = malloc((bits+1)*sizeof(char));


for(int i = 0; i < bits; i++){
ret[bits-i-1] = (x & 1) ? '1' : '0';
x >>= 1;
}

ret[bits] = '\0';
return ret;
}

Solutions

Expert Solution

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

#include <stdint.h>

char * bin(int x, int i);

int main(int argc, char ** argv) {
  char * binstr = bin(10, 0);
  printf("%s\n", binstr);
  free(binstr);

  return 0;
}

char * bin(int x, int i) {
    // since size of int is 32 bit
    // maximum no of bits in x for any positive value
    // is 31 and one bit for null character
    char* ret = malloc((32) * sizeof(char));
    int j = 0;
    bin_internal(x, ret, &j);
    ret[j] = '\0';
    return ret;
}

// this is the recursive function
// here every time we divide the number by 2
// and compute its result via recursion call for x / 2.
void bin_internal(int x, char* ret, int* j){
    if(x == 0)
        return;
    bin_internal(x >> 1, ret, j);
    ret[*j] = (x & 1)? '1': '0';
    (*j) ++;
}

OUTPUT:-

if you have any doubt, feel free to ask in the comments.


Related Solutions

Can you rewrite this MATLAB code using a for loop instead of a while loop? %formatting...
Can you rewrite this MATLAB code using a for loop instead of a while loop? %formatting clc, clear, format compact; %define variables k=1; b=-2; x=-1; y=-2; %while loop initialization for k <= 3 disp([num2str(k), ' ',num2str(b),' ',num2str(x),' ',num2str(y),]); y = x^2 -3; if y< b b = y; end x = x+1; k = k+1; end
C programming Rewrite the following function using no loops, and only tail call recursion double question5...
C programming Rewrite the following function using no loops, and only tail call recursion double question5 (int in) { int i; int result; for (result = rand(), i = 0; i < in; i += 3) { result /= i; result += rand(); } return result; }
Rewrite your program for finding Pascal's Triangle to use iteration (loops) instead of recursion. Include in...
Rewrite your program for finding Pascal's Triangle to use iteration (loops) instead of recursion. Include in both algorithms code to keep track of the total time used to run the algorithms in milliseconds. Run these algorithms for n = 10, n = 20, and n = 30. Print out both the original output and the time to run for both algorithms. Please make sure you comment your code thoroughly. The code should be nicely formatted and should use proper variables.
REWRITE FOLLOWING CODES USING DO...WHILE LOOP. BY USING C LANGUAGE #include <stdio.h> int main(void) {     ...
REWRITE FOLLOWING CODES USING DO...WHILE LOOP. BY USING C LANGUAGE #include <stdio.h> int main(void) {      int count =2; // COUNT TAKEN 2 AS TO PRINT 2 TIMES           while(count--){                printf("\--------------------------------------------\ \n"); printf("\          BBBBB               A                   \ \n"); printf("\          B    B             A A                  \ \n"); printf("\          BBBB              A   A                 \ \n"); printf("\          B    B           AAAAAAA                \ \n"); printf("\          BBBBB           A       A               \ \n"); printf("\---------------------------------------------\ \n");             }                                 return 0; }
#Python program using loop instead of numpy or pandas. Write a function to enter n student...
#Python program using loop instead of numpy or pandas. Write a function to enter n student scores from 0 to 100 to represent student score, Count how many A (100 - 90), B(89-80), C(79-70), D(69-60), F(<60) We will use numpy array OR pandas later for this problem, for now use loop Invoke the function with 10 student scores, show the result as follow: Test Enter 10 scores Enter a student score: 99 Enter a student score: 88 Enter a student...
C++ only Write a function decimalToBinaryRecursive that converts a decimal value to binary using recursion. This...
C++ only Write a function decimalToBinaryRecursive that converts a decimal value to binary using recursion. This function takes a single parameter, a non-negative integer, and returns a string corresponding to the binary representation of the given value. Your function should be named decimalToBinaryRecursive Your function should take a single argument An integer to be converted to binary Your function should not print anything Your function should use recursion instead of a loop. Note that if you try to use a...
REWRITE THE FOLLOWING CODES USING FOR LOOP. PLS USE C LANGUAGE FORMAT #include <stdio.h> int main(void)...
REWRITE THE FOLLOWING CODES USING FOR LOOP. PLS USE C LANGUAGE FORMAT #include <stdio.h> int main(void) {      int count ; scanf("%d",&count);           while(count--){                printf("\--------------------------------------------\ \n"); printf("\          BBBBB               A                   \ \n"); printf("\          B    B             A A                  \ \n"); printf("\          BBBB              A   A                 \ \n"); printf("\          B    B           AAAAAAA                \ \n"); printf("\          BBBBB           A       A               \ \n"); printf("\---------------------------------------------\ \n");             }                            return 0; }
4. Rewrite the following pseudocode segment using a loop structure in the specified languages: k =...
4. Rewrite the following pseudocode segment using a loop structure in the specified languages: k = (j + 13) / 27 loop:       if k > 10 then goto out       k = k + 1       i = 3 * k - 1       goto loop out: . . . a. C++ b. Python c. Ruby Assume all variables are integer type. Discuss the relative merits of the use of these languages for this particular code.
-> > Use recursion to write a C++ function for determining if a strings has more...
-> > Use recursion to write a C++ function for determining if a strings has more vowels than consonants. Please include the pseudo code so that I can understand better with simple English as much as possible.
In python I want to create a function that takes in a linked list. Using recursion...
In python I want to create a function that takes in a linked list. Using recursion only, I want to check if the linked list is sorted. How do i do this?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT