Search code examples
arrayscloopsdigitsunsigned-integer

storing digits of a number in array


How do I store different digits of an integer in any array like 1234 to {1,2,3,4} It can be done using char str[]="1234"; printf("%c",str[0]; but how to do it without using string and in integer itself


Solution

  • Here's a snippet that creates an array of digits and prints them out:

    #include <stdio.h>
    #include <math.h>
    #include <stdlib.h>
    
    
    // Print digits 1 by 1
    void numToDigits (int number, int base) {
      int i;
      int n_digits = (int)ceil(log(number+1) / log(base));
      printf("%d digits\n", n_digits);
      int * digits = calloc(n_digits, sizeof(int));
    
      for (i=0; i<n_digits; ++i) {
        digits[i] = number % base;
        number /= base;
      }
    
      // digits[0] is the 1's place, so print them starting from the largest index
    
      for (i=n_digits-1; i>=0; --i) {
        printf("%d", digits[i]);
      }
      printf("\n");
    
      free(digits);
    }
    

    You'll likely want to modify this, but I think it exposes all the important ideas. Don't forget to add -lm when you compile to include math libraries needed for log and ceil. Also note that the printing code isn't made to work with bases larger than 10.