jhschwartz
jhschwartz

Reputation: 300

How can I convert a long long into an array in C?

I would like to convert an integer into an array. My goal is to be able to take a long long, for example 123456789..., and make an array in which each digit holds one spot, like this {1, 2, 3, 4, 5, 6, 7, 8, 9, ...}.

I can't use iota() because I am not allowed to, and I don't want to use snprintf because I don't want to print the array. I just want to make it.

After thinking about it for awhile, the only solution I thought of was to

  1. Create a loop to divide the number by ten for each digit, leaving the quotient as an int
  2. Let the decimals of the quotient go away via the restrictions of the int data type
  3. Make a for loop to decrement the number until it becomes divisible by ten, all while incrementing a counter i
  4. Let the i effectively become the digit and pass it into the array

But I feel like I am making this extremely overcomplicated, and there must be a simpler way to do this. So, have I answered my own question or is there and easier way?

Upvotes: 1

Views: 11772

Answers (2)

This is an iterative approach for your problem which I guess works perfectly

The code below is commented ! Hope it helps

#include <stdio.h>

int main()
{
    // a will hold the number
    int a=548763,i=0;
    // str will hold the result which is the array
    char str[20]= "";
    // first we need to see the length of the number a
    int b=a;
    while(b>=10)
    {
        b=b/10;
        i++;
    }
    // the length of the number a will be stored in variable i 
    // we set the end of the string str as we know the length needed
    str[i+1]='\0';
    // the while loop below will store the digit from the end of str to the 
    // the beginning 
    while(i>=0)
    {
        str[i]=a%10+48;
        a=a/10;
        i--;
    }
    // only for test 
    printf("the value of str is \"%s\"",str);

    return 0;
}

if you want the array to store only ints you need only to change the type of the array str and change

str[i]=a%10+48;

to

str[i]=a%10;

Upvotes: 1

Kevin Winata
Kevin Winata

Reputation: 379

You can use only 1 loop :

#include <math.h>

int main() {
    int number = 123456789;
    int digit = floor(log10(number)) + 1;
    printf("%d\n", digit);
    int arr[digit];
    int i;
    for (i = digit; i > 0; i--) {
        arr[digit-i] = (int)(number/pow(10,i-1)) % 10;
        printf("%d : %d\n", digit-i, arr[digit-i]);
    }
}

Upvotes: 1

Related Questions