Please post your code as plain text next time, so the forum can apply line numbers and syntax highlighting.
It's int main(), and you should return an integer at the end. Read this
link.
Note, '\0' is a character literal with a numeric value of 0, thus, the following are equivalent:
Code:
char a[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, '\0'};
char a[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
char a[11] = {0}; // short hand for initialize all elements to 0
You allow 11 characters in the array/string. That is 10 chars for binary digits, and the 11th char is for null terminator. Thus, you can only support 10-bit numbers, but ints are at least 16 bits (1 for sign, 15 for value). Thus, you need bigger arrays/strings. Also, your while loop has the potential to overrun the end of the array/string since you don't check that i is always less than the size of the string. This is a good time to point out constants. Avoid magic numbers like 11. #define a constant for the max binary string length. Here's the easy solution
Code:
#define MAX_BINARY_STR 64 // support up to 64-bit numbers
// this is not meant to be a global, declare it in main
char binary_string[MAX_BINARY_STR + 1]; // +1 for the null terminator; notice how much more descriptive the variable name is compared to 'a' or 'string'
If you specifically want this to work for int type, and to be portable, then I would do the following
Code:
#include <limits.h> // has the definition of CHAR_BIT
#define INT_BITS (sizeof(int) * CHAR_BIT)
#define MAX_BINARY_STR INT_BITS
// this is not meant to be a global, declare it in main
char binary_string[MAX_BINARY_STR + 1]; // +1 for the null terminator; notice how much more descriptive the variable name is compared to 'a' or 'string'
I'm not sure if you really need a second array, if you are doing everything as a string. Just convert num directly to the string representation (i.e. using '0' and '1' instead of 0 and 1). Besides, that way you don't have to worry about how long the array is, since the null termination of the string will tell you where the end is.
Code:
while (num > 0 && i < MAX_BINARY_STR) {
if (num % 2)
binary_string[i++] = '1';
else
'0'
}
binary_string[i] = '\0'; // null-terminate the string
// reverse the string in place if needed -- you can probably figure this out yourself -- or simply print from the end of the string to the beginning