Home > Software engineering >  How to add element from the end to the start in empty array?
How to add element from the end to the start in empty array?

Time:11-27

I ran into the theoretical problem, which doesn't let me solve my task.

I have an algorithms, that convert decimal to binary. It looks like this:

  1. We have a decimal 65.
  2. 65%2 = 32(remainder 1), 32 % 2 = 16(remainder 0) etc. till we get 1. It's just "1".
  3. So now I have something like this: "1000001" It's written from the last division with reminder to the first. And I have to add it in the empty array. But I can't find the information how to add elements in array from the end to the start.

CodePudding user response:

... to add elements in array from the end to the start.

In C, an array can not change size once it is declared. With int to string of binary text we know the maximally array size needed. For now, let us assume it is 12.

Set up an index to the end of the array.

In the %2 loop, decrement the index to work from end to start.

#define N 12
char buf[N];
int index = N-1;
buf [index] = '\0';  // Assign the last element of the array.
int negative = num < 0;    

do {
  int digit = num%2;
  buf[--i] = abs(digit)   '0'; // Assign the previous array element.
  num /= 2;
} while (num);

if (negative) {
  buf[--i] = '-';
}     

printf("<%s>\n", buf   i);

Notice the initial array elements were not used for small values of num.


Alternatives: We could use memmove() to shift the string to the first part of the array. Or loop though num twice, first to find the array size needed and the again, using a right-sized array, populate it. We could populate the array from the beginning (with the least significant digits first) and then reverse the string.

In the next version of C2x, we likely can simply do snprint(array, sizeof array, "%b", num);

  •  Tags:  
  • c
  • Related