6
\$\begingroup\$

Input:

    Enter a decimal number: 101

Output:

    The binary number is : 1100101

I have solved this way->

#include <stdio.h>
int main(void){

int input=get_input();
long long complete_integer=binary_conversion(input);
reverse_digits(complete_integer);
}
int get_input() {
int number = 0;
printf("Enter a decimal number: ");
scanf("%d",&number);
return number;
}
int binary_conversion(int number) {
long long complete_integer = 0;
int base=2;

while (number != 0) {
//Take the last digit from the integer and push the digit back of complete integer
complete_integer = complete_integer * 10 + number%base;
number /= base;
}
printf("Completed integer number : %d\n",complete_integer);
return complete_integer;
}

int reverse_digits(long long complete_integer) {
    int binary = complete_integer;
    int last_digit = 0;

    while(binary != 0) {

        last_digit = last_digit * 10 + binary % 10;
        binary /= 10;
    }
    printf("The binary number is: %d",last_digit);
}

I am here for: What about my comments and indentations? Will I face any problem for some conditions? Would you propose a better simplification by using my program?

\$\endgroup\$
  • \$\begingroup\$ You can check it now. \$\endgroup\$ – Ashiful Islam Prince Oct 4 at 14:22
  • \$\begingroup\$ You should indent your code, it makes it much more readable and emphasizes its structure. Unindented code can quickly become unmaintainble. \$\endgroup\$ – adrian Oct 5 at 4:07
  • \$\begingroup\$ I understand. Thank you sir. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 8:24
  • \$\begingroup\$ I am sorry for making a reply delay in all your answer. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 9:08
4
\$\begingroup\$

Indent your code!

Most of your code is completely unindented, which makes it very hard to read.

While the compiler can easily scan your code and count { and } signs to tell where each function and code block begins and ends, for humans this is much more difficult and prone to mistakes. That's why it's a good idea to indent the lines inside each function and block, so that the structure of the code is apparent to a human eye.

Does your code really look like something you'd want to read in six months, after you've forgotten what it looks like? If not, please make it cleaner. (If you think it is, please actually try this experiment!)

Turn on compiler warnings!

Compiling your code with warnings enabled (Clang with -Weverything and --std=c17) would alert you to several serious issues in it that you should fix. These include:

  • the lack of prototypes for your helper functions,
  • the unused value parameter to binary_conversion,
  • the incorrect use of the %d format specifier instead of %lld for printing a long long int value,
  • the fact that the return value of binary_conversion is truncated from a long long int to an int, and
  • the fact that reverse_digits is defined to return an int even though it actually doesn't.

Actually, it's quite surprising that your code even compiles and (sort of) works with all these bugs in it.

Incorrect output:

You left in the line:

printf("Completed integer number : %d\n",complete_integer);

that causes your code to print something that it's not supposed to. A simple and minor issue, really, but possibly enough to fail your assignment.

A bigger problem is that, because you forgot to change the return type of binary_conversion to long long int, your code will produce incorrect output for inputs larger than 1023 (= 1111111111 in binary). For example, the input 1025 causes your code to generate the nonsense output:

The binary number is: 455665549

(Even if you did fix this bug, your code would still fail for inputs larger than about 219 − 1, since a 64-bit signed long long int cannot store a decimal number with more than 19 digits.)

An even bigger problem is that your algorithm doesn't work for even numbers at all! For example, the input 1024 (or indeed any other power of 2) causes your program to print:

The binary number is: 1

Honestly, did you even test the code at all?

A better solution:

The computer already stores the input number read by scanf in binary. Instead of converting that binary number to a decimal number that looks the same when printed with printf (and reversing its decimal digits twice in the process), you should instead try to find some way of printing the bits of the binary number one by one directly.

Here's a quick sketch of something that should work:

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

void print_binary(uint32_t number) {
    uint32_t bit = (uint32_t)1 << 31;

    while (bit > number && bit > 1) {
        bit /= 2;  // skip leading zeros
    }
    while (bit > 0) {
        putchar(bit & number ? '1' : '0');
        bit /= 2;
    }
}

(Note the use of the fixed-length unsigned integer type uint32_t to avoid making unnecessary assumptions about the number of bits an int can store — which might be only 16 on some low-end non-POSIX systems — and the user of the bit shift operator << to easily calculate the constant 231. Also, if you're not familiar with the bitwise AND operator & or the ternary conditional operator ?:, this could be a good time learn about them.)

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Does your code really look like something you'd want to read in six months, after you've forgotten what it looks like? If not, please make it cleaner. (If you think it is, please actually try this experiment!). Would you update your answer by providing the proper indentation of my code?. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 8:47
  • \$\begingroup\$ the unused value parameter to binary_conversion, I wrote it by mistake. Thank you for your identification. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 8:53
  • \$\begingroup\$ the incorrect use of the %d format specifier instead of %lld for printing a long long int value, I wonder why the compiler named code blocks does not generate a warning for this mistake. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 8:57
  • \$\begingroup\$ You left in the line: printf("Completed integer number : %d\n",complete_integer); I removed this. Thank you. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 8:59
  • \$\begingroup\$ A bigger problem is that, because you forgot to change the return type of binary_conversion to long long int, I keep remain this function type as the same it was. I have changed the format specifier while printing the complete_integer number. But it gives the same output as what you have mentioned above(for the input 1023). \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 9:11
6
\$\begingroup\$

There is no indentation except in the function revers_digits(). The indentation within that function is fine, you should correct the rest of the program because it is basically unreadable.

While this may compile in a free online compiler, the code is broken for 2 reasons. The first is that in a one file program such as this one for the C programming language main() should be the last function in the file so that all of the other functions are defined previously. There is a workaround for this using function prototypes.

The second reason the code is broken is that binary_conversion(int number,int value) is declared with 2 variables, but is only called with one (remove value since it doesn't seem to be necessary).

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ (remove value since it doesn't seem to be necessary). I removed it. Thank you for your help to get the wrong of mine. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 8:42
  • \$\begingroup\$ main() should be the last function in the file so that all of the other functions are defined previously Why?. Whatever I did in my program. It works fine. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 8:43
  • \$\begingroup\$ Thank you for your established information. Keep up the good work. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 9:21
5
\$\begingroup\$

Repeating short comings

The indentation of your post is very bad (and others) of previous post with scant improvement here.

Omitting #1 productivity step

Turn on all warnings.

Below code suffers from mis-match of specifier and type. A good well enabled compile will warn. My compiler provided about 10 warnings. Example:

long long complete_integer = 0;
...
printf("Completed integer number : %d\n",complete_integer);
// warning: format '%d' expects argument of type 'int', but argument 2 has type 'long long int' [-Wformat=]

Omitting #2 productivity step

Use auto-format to format code.

Not full range solutions

Both binary_conversion() and reverse_digits() fail to handle large int values. Code architecture needs a new approach. I recommend forming the result in a string or array.

Code should detail expected results when n is negative.

Missing check

Robust code would check the result of scanf("%d",&number) and only convert when 1.

Strange output

Reported output is "The binary number is : 1100101". I get 2 lines of output. Post true output.

printf("Completed integer number : %d\n",complete_integer); makes more sense as the "binary"

printf("The binary number is: %d",last_digit); makes more sense as the "reversed number".


To print non-negatives in binary, a candidate simplification:

#include <stdio.h>

void print_binary(int n) {
  if (n > 1) print_binary(n/2);
  printf("%d", n % 2);
}
    
int main(void) {
  print_binary(101);
  puts("");
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I run my program on the code blocks. The compiler gives me a total of three warnings. You told me that your compiler gives a total of ten warnings. Why warning varies compiler to compiler? \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 8:31
  • \$\begingroup\$ Use auto-format to format code. I think this is not a good strategy to follow. If I can write good coding styles and formats by practicing then it would be better for me. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 8:35
  • \$\begingroup\$ Reported output is "The binary number is : 1100101". I get 2 lines of output. Sorry for this inconvenience. I was trying to appear the first output called complete_integer for the checking purposes. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 8:38
  • \$\begingroup\$ Thank you for your established guidelines and information. Thank you so much. \$\endgroup\$ – Ashiful Islam Prince Oct 5 at 9:21
  • \$\begingroup\$ @AshifulIslamPrince "Why warning varies compiler to compiler?" C does not require all compilers to warn in the same way or amount. Also consider enabling more warnings. e.g. gcc: '-Wpedantic' '-Wall' '-Wextra' '-Wconversion' \$\endgroup\$ – chux - Reinstate Monica Oct 9 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.