DaidalosCheung / C

0 stars 0 forks source link

recursion_decimal_binary.c #1

Open DaidalosCheung opened 4 years ago

DaidalosCheung commented 4 years ago
#include <stdio.h>

long dec_bi( long );

int main(void) {
  long dec;
  _Bool bi;

  printf("\nEnter an integer: ");

  while( scanf("%ld", &dec) ==1 ) {
    dec_bi( dec );
    printf("\nEnter an integer: ");
  }

  return 0;
}

long dec_bi( long num ) {

  int c;
  c = num % 2;

  if ( num >= 2)  // if (num > 2) then th result will lost the first digit, cause the deepest recursion determine the largest digit. 
    dec_bi( num/2 );

  // If this line before "if" will cause binary reverse, in the if will cause the lost of first digit
  putchar( c == 0 ? '0' : '1' );

  // It is "long" datatype, the floating point will be omit, so do not need the following code
  /* num = num - c; */
  /* dec_bi( num/2 ); */ 

  return 0;    
}
DaidalosCheung commented 4 years ago
#include <stdio.h>

int dec_bi (int dec) {
  int num;
  num = dec % 2;

  if (dec > 2) {
    dec_bi( dec / 2 );
    printf("In the recursion.\n"); //1. When does not work
    putchar( num > 0 ? '1':'0' );  //2. Why omit the first digit
  }

  printf("After recursion\n");
  putchar( num > 0 ? '1':'0' );

  return 0;
}

int main (void) {
  int dec;

  printf("Enter an decimal integer: ");
  scanf("%d", &dec);

  dec_bi( dec );

  return 0;
}

/* For decimal number 6: */
/* 1. After the final recursion finish (6 -> 3 -> 1) and dec reach to 1; */
/* 2. In the final round, dec reach to 1, and (dec = 1) cannot go into if statment, so it will jump to Line13, which print after recursion and then putchar */